diff --git a/.eslintignore b/.eslintignore
index 26d6131f..d736e136 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,2 +1,10 @@
/vendor
/node_modules
+/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example
+/cloudfunctions/ARDemo/wx-server-sdk-wxg-service/index.js
+/miniprogram/packageSkylineExamples
+/miniprogram/_commons/0.js
+/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf
+/miniprogram/packageAPI/components/tdesign-miniprogram
+/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/gl-matrix-min.js
+/miniprogram/packageChatTool/components/tdesign-miniprogram
\ No newline at end of file
diff --git a/.eslintrc.js b/.eslintrc.js
index 141fa110..9c06dd31 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,32 +1,32 @@
module.exports = {
- 'extends': [
+ extends: [
'airbnb-base',
'plugin:promise/recommended'
],
- 'parserOptions': {
- 'ecmaVersion': 9,
- 'ecmaFeatures': {
- 'jsx': false
+ parserOptions: {
+ ecmaVersion: 9,
+ ecmaFeatures: {
+ jsx: false
},
- 'sourceType': 'module'
+ sourceType: 'module'
},
- 'env': {
- 'es6': true,
- 'node': true,
- 'jest': true
+ env: {
+ es6: true,
+ node: true,
+ jest: true
},
- 'plugins': [
+ plugins: [
'import',
'node',
'promise'
],
- 'rules': {
+ rules: {
'arrow-parens': 'off',
'comma-dangle': [
'error',
'only-multiline'
],
- 'complexity': ['error', 10],
+ complexity: ['error', 10],
'func-names': 'off',
'global-require': 'off',
'handle-callback-err': [
@@ -36,9 +36,9 @@ module.exports = {
'import/no-unresolved': [
'error',
{
- 'caseSensitive': true,
- 'commonjs': true,
- 'ignore': ['^[^.]']
+ caseSensitive: true,
+ commonjs: true,
+ ignore: ['^[^.]']
}
],
'import/prefer-default-export': 'off',
@@ -58,13 +58,13 @@ module.exports = {
'node/process-exit-as-throw': 'error',
'object-curly-spacing': [
'error',
- 'never'
+ 'always'
],
'operator-linebreak': [
'error',
'after',
{
- 'overrides': {
+ overrides: {
':': 'before',
'?': 'before'
}
@@ -77,23 +77,23 @@ module.exports = {
1,
'as-needed',
{
- 'unnecessary': true
+ unnecessary: true
}
],
- 'semi': [
+ semi: [
'error',
'never'
]
},
- 'globals': {
- 'window': true,
- 'document': true,
- 'App': true,
- 'Page': true,
- 'Component': true,
- 'Behavior': true,
- 'wx': true,
- 'worker': true,
- 'getApp': true
+ globals: {
+ window: true,
+ document: true,
+ App: true,
+ Page: true,
+ Component: true,
+ Behavior: true,
+ wx: true,
+ worker: true,
+ getApp: true
}
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..49f1f81b
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,19 @@
+name: WeChat MiniProgram Demo CI/CD
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ branches:
+ - master
+jobs:
+ upload:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Upload MiniProgram
+ env:
+ WX_PRIVATE_KEY: ${{ secrets.WX_PRIVATE_KEY }}
+ run: |
+ echo "$WX_PRIVATE_KEY" > ./build/key
+ node ./build/ci.js
diff --git a/build/ci.js b/build/ci.js
new file mode 100644
index 00000000..9b78edc9
--- /dev/null
+++ b/build/ci.js
@@ -0,0 +1,47 @@
+const path = require('path')
+const ci = require('miniprogram-ci')
+const fs = require('fs')
+const packageJson = require('../package.json')
+
+const privateKeyContent = process.env.WX_PRIVATE_KEY
+if (!privateKeyContent) {
+ throw new Error('未找到私钥内容,请确保已正确配置 GitHub Secrets')
+}
+
+const privateKeyPath = path.resolve(__dirname, './private.key')
+fs.writeFileSync(privateKeyPath, privateKeyContent)
+
+const project = new ci.Project({
+ appid: 'wxe5f52902cf4de896',
+ type: 'miniProgram',
+ projectPath: path.resolve(__dirname, '../'),
+ privateKeyPath: path.resolve(__dirname, './key'),
+ ignores: [path.resolve(__dirname, '../miniprogram/node_modules/**/*')]
+})
+const robotNumber = 2
+const params = {
+ onProgressUpdate: console.log,
+ robot: robotNumber,
+ version: packageJson.version,
+ desc: packageJson.bundleDescription,
+ setting: {
+ es7: true,
+ minifyJS: true,
+ minifyWXML: true,
+ minifyWXSS: true,
+ codeProtect: false,
+ autoPrefixWXSS: true
+ },
+}
+ci.upload({
+ project,
+ ...params
+}).then(res => {
+ console.debug('>>>>upload res', res)
+}).catch(err => {
+ console.error('>>>>upload error', err)
+ throw err
+}).finally(() => {
+ // 删除临时私钥文件
+ fs.unlinkSync(privateKeyPath)
+})
diff --git a/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js b/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js
index 21a4a144..d1c3ae70 100644
--- a/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js
+++ b/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js
@@ -1,4 +1,3 @@
-
function generate(options) {
if (!options) {
throw new Error('options must be provided')
@@ -6,7 +5,7 @@ function generate(options) {
const { serviceName, funcName, data } = options
- const serviceConfig = config.find(c => c.serviceName === serviceName)
+ const serviceConfig = config.find(c => c.serviceName === serviceName)
if (!serviceConfig) {
throw new Error('service not found')
}
@@ -38,7 +37,7 @@ function generate(options) {
if (!reqProtoJSON.fields[key]) {
throw new Error(`'${key}' doesn't exist in '${reqProtoName}' proto, valid keys are ${Object.keys(reqProtoJSON.fields)}`)
}
- }
+ }
} else {
throw new Error('data must be object')
}
@@ -91,7 +90,7 @@ function generateV2(options) {
if (!reqProtoJSON.fields[key]) {
throw new Error(`'${key}' doesn't exist in '${reqProtoName}' proto, valid keys are ${Object.keys(reqProtoJSON.fields)}`)
}
- }
+ }
} else {
throw new Error('data must be object')
}
diff --git a/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils.js b/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils.js
index a1f33a6a..79ed1198 100644
--- a/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils.js
+++ b/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils.js
@@ -3,7 +3,7 @@ const path = require('path')
const yargs = require('yargs')
const chalk = require('chalk')
const debug = require('debug')('cli')
-const pbjs = require("protobufjs/cli/pbjs")
+const pbjs = require('protobufjs/cli/pbjs')
const log = (...msg) => {
console.log(chalk.blue('svrkit-utils'), ...msg)
@@ -50,7 +50,7 @@ function main() {
throw err
}
- let staticModuleContent = fs.readFileSync(staticModuleFilePath, 'utf8')
+ const staticModuleContent = fs.readFileSync(staticModuleFilePath, 'utf8')
fs.writeFileSync(staticModuleFilePath, `// #lizard forgives
${staticModuleContent}`, 'utf8')
@@ -95,4 +95,3 @@ ${protoUtils}
module.exports = {
main,
}
-
diff --git a/cloudfunctions/ARDemo/index.js b/cloudfunctions/ARDemo/index.js
index a1c41299..e1acb1df 100644
--- a/cloudfunctions/ARDemo/index.js
+++ b/cloudfunctions/ARDemo/index.js
@@ -11,13 +11,13 @@ exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
const bizuin = wxContext.APPUIN
switch (event.type) {
- case "GenerateARModel":
+ case 'GenerateARModel':
return await cloud.callWXSvrkit({
pbInstance: svrkitUtils.generate({
- serviceName: "Mmbizwxaintpar",
- funcName: "GenerateARModel",
+ serviceName: 'Mmbizwxaintpar',
+ funcName: 'GenerateARModel',
data: {
- bizuin: bizuin,
+ bizuin,
name: event.name,
url: event.url,
algoType: event.algoType,
@@ -26,14 +26,14 @@ exports.main = async (event, context) => {
},
}),
timeout: 30000,
- });
- case "GetARModel":
+ })
+ case 'GetARModel':
return await cloud.callWXSvrkit({
pbInstance: svrkitUtils.generate({
- serviceName: "Mmbizwxaintpar",
- funcName: "GetARModel",
+ serviceName: 'Mmbizwxaintpar',
+ funcName: 'GetARModel',
data: {
- bizuin: bizuin,
+ bizuin,
cosid: event.cosid,
modelType: event.modelType,
needData: event.needData,
@@ -42,7 +42,7 @@ exports.main = async (event, context) => {
},
}),
timeout: 30000,
- });
+ })
// GetARModelList 废弃,完全依赖本地缓存
// case "GetARModelList":
// return await cloud.callWXSvrkit({
@@ -58,5 +58,4 @@ exports.main = async (event, context) => {
// timeout: 30000,
// });
}
-
-}
\ No newline at end of file
+}
diff --git a/cloudfunctions/ARDemo/svrkit-utils.js b/cloudfunctions/ARDemo/svrkit-utils.js
index 941b9848..d50911b6 100644
--- a/cloudfunctions/ARDemo/svrkit-utils.js
+++ b/cloudfunctions/ARDemo/svrkit-utils.js
@@ -1,23 +1,23 @@
-
const config = require('./svrkit.config.js')
const proto = require('./svrkit-utils.static.js')
const protoJSON = require('./svrkit-utils.static.json')
+
function getProto(proto, serviceName, protoName) {
if (proto[protoName]) {
- return proto[protoName];
+ return proto[protoName]
}
if (proto[serviceName] && proto[serviceName][protoName]) {
- return proto[serviceName][protoName];
+ return proto[serviceName][protoName]
}
- /** 处理 mmpayolcirclemodel.QueryActivityReq 的形式*/
+ /** 处理 mmpayolcirclemodel.QueryActivityReq 的形式 */
const [realServiceName, realProtoName] = protoName.split('.')
if (proto[realServiceName]) {
return proto[realServiceName][realProtoName]
}
- return undefined;
+ return undefined
}
function generate(options) {
@@ -37,14 +37,14 @@ function generate(options) {
}
const reqProtoName = serviceConfig.functions[funcName].req
- const reqProto = getProto(proto, serviceName, reqProtoName);
+ const reqProto = getProto(proto, serviceName, reqProtoName)
if (!reqProto) {
throw new Error('request proto not found')
}
const resProtoName = serviceConfig.functions[funcName].res
- const resProto = resProtoName && getProto(proto, serviceName, resProtoName);
+ const resProto = resProtoName && getProto(proto, serviceName, resProtoName)
const reqProtoVerifyErr = reqProto.verify(data)
if (reqProtoVerifyErr) {
@@ -133,4 +133,3 @@ module.exports = {
generate,
generateV2,
}
-
diff --git a/cloudfunctions/ARDemo/svrkit.config.js b/cloudfunctions/ARDemo/svrkit.config.js
index 962f5499..87aa4070 100644
--- a/cloudfunctions/ARDemo/svrkit.config.js
+++ b/cloudfunctions/ARDemo/svrkit.config.js
@@ -31,4 +31,4 @@ module.exports = [
}
}
}
-]
\ No newline at end of file
+]
diff --git a/gulpfile.js b/gulpfile.js
index ccd846f6..6c41caac 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -13,74 +13,75 @@ gulp.task('transform-css-vars', () => {
cssvars({
preserve: false,
variables: {
- "--weui-BTN-DISABLED-FONT-COLOR": "rgba(0, 0, 0, .2)",
- "--weui-BTN-DEFAULT-BG": "#f2f2f2",
- "--weui-BTN-DEFAULT-COLOR": "#06ae56",
- "--weui-BTN-DEFAULT-ACTIVE-BG": "#e6e6e6",
- "--weui-DIALOG-LINE-COLOR": "rgba(0, 0, 0, .1)",
- "--weui-BG-0": "#ededed",
- "--weui-BG-1": "#f7f7f7",
- "--weui-BG-2": "#fff",
- "--weui-BG-3": "#f7f7f7",
- "--weui-BG-4": "#4c4c4c",
- "--weui-BG-5": "#fff",
- "--weui-FG-0": "rgba(0, 0, 0, .9)",
- "--weui-FG-HALF": "rgba(0, 0, 0, .9)",
- "--weui-FG-1": "rgba(0, 0, 0, .5)",
- "--weui-FG-2": "rgba(0, 0, 0, .3)",
- "--weui-FG-3": "rgba(0, 0, 0, .1)",
- "--weui-RED": "#fa5151",
- "--weui-ORANGE": "#fa9d3b",
- "--weui-YELLOW": "#ffc300",
- "--weui-GREEN": "#91d300",
- "--weui-LIGHTGREEN": "#95ec69",
- "--weui-BRAND": "#07c160",
- "--weui-BLUE": "#10aeff",
- "--weui-INDIGO": "#1485ee",
- "--weui-PURPLE": "#6467f0",
- "--weui-WHITE": "#fff",
- "--weui-LINK": "#576b95",
- "--weui-TEXTGREEN": "#06ae56",
- "--weui-FG": "#000",
- "--weui-BG": "#fff",
- "--weui-TAG-TEXT-ORANGE": "#fa9d3b",
- "--weui-TAG-BACKGROUND-ORANGE": "rgba(250, 157, 59, .1)",
- "--weui-TAG-TEXT-GREEN": "#06ae56",
- "--weui-TAG-BACKGROUND-GREEN": "rgba(6, 174, 86, .1)",
- "--weui-TAG-TEXT-BLUE": "#10aeff",
- "--weui-TAG-BACKGROUND-BLUE": "rgba(16, 174, 255, .1)",
- "--weui-TAG-TEXT-BLACK": "rgba(0, 0, 0, .5)",
- "--weui-TAG-BACKGROUND-BLACK": "rgba(0, 0, 0, .05)",
- "--weui-BG-COLOR-ACTIVE": "#ececec",
- "--height": "44px",
- "--right": "95px",
+ '--weui-BTN-DISABLED-FONT-COLOR': 'rgba(0, 0, 0, .2)',
+ '--weui-BTN-DEFAULT-BG': '#f2f2f2',
+ '--weui-BTN-DEFAULT-COLOR': '#06ae56',
+ '--weui-BTN-DEFAULT-ACTIVE-BG': '#e6e6e6',
+ '--weui-DIALOG-LINE-COLOR': 'rgba(0, 0, 0, .1)',
+ '--weui-BG-0': '#ededed',
+ '--weui-BG-1': '#f7f7f7',
+ '--weui-BG-2': '#fff',
+ '--weui-BG-3': '#f7f7f7',
+ '--weui-BG-4': '#4c4c4c',
+ '--weui-BG-5': '#fff',
+ '--weui-FG-0': 'rgba(0, 0, 0, .9)',
+ '--weui-FG-HALF': 'rgba(0, 0, 0, .9)',
+ '--weui-FG-1': 'rgba(0, 0, 0, .5)',
+ '--weui-FG-2': 'rgba(0, 0, 0, .3)',
+ '--weui-FG-3': 'rgba(0, 0, 0, .1)',
+ '--weui-RED': '#fa5151',
+ '--weui-ORANGE': '#fa9d3b',
+ '--weui-YELLOW': '#ffc300',
+ '--weui-GREEN': '#91d300',
+ '--weui-LIGHTGREEN': '#95ec69',
+ '--weui-BRAND': '#07c160',
+ '--weui-BLUE': '#10aeff',
+ '--weui-INDIGO': '#1485ee',
+ '--weui-PURPLE': '#6467f0',
+ '--weui-WHITE': '#fff',
+ '--weui-LINK': '#576b95',
+ '--weui-TEXTGREEN': '#06ae56',
+ '--weui-FG': '#000',
+ '--weui-BG': '#fff',
+ '--weui-TAG-TEXT-ORANGE': '#fa9d3b',
+ '--weui-TAG-BACKGROUND-ORANGE': 'rgba(250, 157, 59, .1)',
+ '--weui-TAG-TEXT-GREEN': '#06ae56',
+ '--weui-TAG-BACKGROUND-GREEN': 'rgba(6, 174, 86, .1)',
+ '--weui-TAG-TEXT-BLUE': '#10aeff',
+ '--weui-TAG-BACKGROUND-BLUE': 'rgba(16, 174, 255, .1)',
+ '--weui-TAG-TEXT-BLACK': 'rgba(0, 0, 0, .5)',
+ '--weui-TAG-BACKGROUND-BLACK': 'rgba(0, 0, 0, .05)',
+ '--weui-BG-COLOR-ACTIVE': '#ececec',
+ '--height': '44px',
+ '--right': '95px',
},
preserveInjectedVariables: false,
})
]
return gulp.src([
- './miniprogram/app.wxss',
- './miniprogram/common/common.wxss',
- './miniprogram/page/common/common.wxss',
- './miniprogram/page/common/index.wxss',
- './miniprogram/page/component/index.wxss',
- './miniprogram/page/cloud/index.wxss',
- './miniprogram/page/API/index.wxss',
- './miniprogram/page/extend/index.wxss',
- './miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.wxss',
- ])
- .pipe(gulpIgnore.exclude(
- file => {
- try {
- fs.accessSync(file.path.replace(/\.wxss$/, '-skyline.wxss'))
- } catch(e) {
- return false
- }
- return true
- }))
- .pipe(postcss(plugins))
- .pipe(replace(/\:root ?{}\n/g, ''))
- .pipe(gulpIf(file => file.path.includes('miniprogram/page/common'), rename({suffix: '-skyline'})))
- .pipe(gulpIf(file => file.path.includes('miniprogram/common'), rename({suffix: '-skyline'})))
- .pipe(gulp.dest(file => file.base))
+ './miniprogram/app.wxss',
+ './miniprogram/common/common.wxss',
+ './miniprogram/page/common/common.wxss',
+ './miniprogram/page/common/index.wxss',
+ './miniprogram/page/component/index.wxss',
+ './miniprogram/page/cloud/index.wxss',
+ './miniprogram/page/API/index.wxss',
+ './miniprogram/page/extend/index.wxss',
+ './miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.wxss',
+ ])
+ .pipe(gulpIgnore.exclude(
+ file => {
+ try {
+ fs.accessSync(file.path.replace(/\.wxss$/, '-skyline.wxss'))
+ } catch (e) {
+ return false
+ }
+ return true
+ }
+ ))
+ .pipe(postcss(plugins))
+ .pipe(replace(/\:root ?{}\n/g, ''))
+ .pipe(gulpIf(file => file.path.includes('miniprogram/page/common'), rename({ suffix: '-skyline' })))
+ .pipe(gulpIf(file => file.path.includes('miniprogram/common'), rename({ suffix: '-skyline' })))
+ .pipe(gulp.dest(file => file.base))
})
diff --git a/miniprogram/app-bar/index.js b/miniprogram/app-bar/index.js
index 9ee282fd..2000ecc7 100644
--- a/miniprogram/app-bar/index.js
+++ b/miniprogram/app-bar/index.js
@@ -7,4 +7,4 @@ Component({
data: {
showAppbar: false
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/app.js b/miniprogram/app.js
index d9599608..3262bf86 100644
--- a/miniprogram/app.js
+++ b/miniprogram/app.js
@@ -45,20 +45,28 @@ App({
traceUser: true,
})
}
- // skyline
- const systemInfo = wx.getSystemInfoSync()
- console.log('@@@ systemInfo ', systemInfo)
- Object.assign(this.globalData, systemInfo)
+ const getSystemInfo = [
+ 'getSystemSetting',
+ 'getAppAuthorizeSetting',
+ 'getDeviceInfo',
+ 'getAppBaseInfo',
+ 'getWindowInfo'
+ ]
+
+ getSystemInfo.forEach(apiName => {
+ if (wx[apiName]) {
+ Object.assign(this.globalData, wx[apiName]())
+ }
+ })
// eslint-disable-next-line promise/always-return
require.async('./packageSkyline/common/custom-route/index.js').then(utils => {
console.log('--------begin installRouteBuilder')
utils.installRouteBuilder() // 'common'
- }).catch(({mod, errMsg}) => {
+ }).catch(({ mod, errMsg }) => {
console.error(`installRouteBuilder path: ${mod}, ${errMsg}`)
})
},
-
onShow(opts) {
console.log('App Show', opts)
console.log('USER_DATA_PATH', wx.env.USER_DATA_PATH)
@@ -67,7 +75,7 @@ App({
onHide() {
console.log('App Hide')
},
- onThemeChange({theme}) {
+ onThemeChange({ theme }) {
this.globalData.theme = theme
themeListeners.forEach((listener) => {
listener(theme)
@@ -85,7 +93,7 @@ App({
}
},
globalData: {
- theme: wx.getSystemInfoSync().theme,
+ theme: wx.getAppBaseInfo().theme,
hasLogin: false,
openid: null,
iconTabbar: '/page/extend/images/icon_tabbar.png',
diff --git a/miniprogram/component/navigation-bar/navigation-bar.js b/miniprogram/component/navigation-bar/navigation-bar.js
index 4335baa6..2408512f 100644
--- a/miniprogram/component/navigation-bar/navigation-bar.js
+++ b/miniprogram/component/navigation-bar/navigation-bar.js
@@ -1,85 +1,80 @@
+const app = getApp().globalData
Component({
options: {
- multipleSlots: true // 在组件定义时的选项中启用多slot支持
+ styleIsolation: 'apply-shared', // 表示页面 wxss 样式将影响到自定义组件,但自定义组件 wxss 中指定的样式不会影响页面
+ multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
/**
* 组件的属性列表
*/
properties: {
- extClass: {
- type: String,
- value: ''
- },
- title: {
- type: String,
- value: ''
- },
- background: {
- type: String,
- value: ''
- },
- color: {
- type: String,
- value: ''
- },
- back: {
- type: Boolean,
- value: true
- },
- loading: {
- type: Boolean,
- value: false
- },
- animated: {
- // 显示隐藏的时候opacity动画效果
- type: Boolean,
- value: true
- },
- show: {
- // 显示隐藏导航,隐藏的时候navigation-bar的高度占位还在
- type: Boolean,
- value: true,
- observer: '_showChange'
- },
- // back为true的时候,返回的页面深度
- delta: {
- type: Number,
- value: 1
- }
+ extClass: {
+ type: String,
+ value: ''
+ },
+ title: {
+ type: String,
+ value: ''
+ },
+ background: {
+ type: String,
+ value: ''
+ },
+ color: {
+ type: String,
+ value: ''
+ },
+ back: {
+ type: Boolean,
+ value: true
+ },
+ loading: {
+ type: Boolean,
+ value: false
+ },
+ animated: {
+ // 显示隐藏的时候opacity动画效果
+ type: Boolean,
+ value: true
+ },
+ show: {
+ // 显示隐藏导航,隐藏的时候navigation-bar的高度占位还在
+ type: Boolean,
+ value: true,
+ observer: '_showChange'
+ },
+ // back为true的时候,返回的页面深度
+ delta: {
+ type: Number,
+ value: 1
+ }
},
/**
- * 组件的初始数据
- */
+ * 组件的初始数据
+ */
data: {
- displayStyle: ''
+ displayStyle: ''
},
attached() {
const isSupport = !!wx.getMenuButtonBoundingClientRect
const rect = wx.getMenuButtonBoundingClientRect
- ? wx.getMenuButtonBoundingClientRect()
- : null
- const isSkyline = this.renderer ==='skyline'
- wx.getSystemInfo({
- success: (res) => {
- const ios = !!(res.system.toLowerCase().search('ios') + 1)
- this.setData({
- ios,
- statusBarHeight: res.statusBarHeight,
- // skyline defaultContentBox:true ; webview border-box
- navBarHeight: rect.bottom - rect.top + 10 + ( isSkyline ? 0 : res.statusBarHeight),
- innerWidth: isSupport ? `width:${rect.left}px` : '',
- innerPaddingRight: isSupport
- ? `padding-right:${res.windowWidth - rect.left}px`
- : '',
- leftWidth: isSupport ? `width:${res.windowWidth - rect.left}px` : '',
- theme: res.theme || 'light',
- })
- }
+ ? wx.getMenuButtonBoundingClientRect()
+ : null
+ const isSkyline = this.renderer === 'skyline'
+ this.setData({
+ ios: !!(app.system.toLowerCase().search('ios') + 1),
+ theme: app.theme || 'light',
+ statusBarHeight: app.statusBarHeight,
+ navBarHeight: rect.bottom - rect.top + 10 + (isSkyline ? 0 : app.statusBarHeight),
+ innerWidth: isSupport ? `width:${rect.left}px` : '',
+ innerPaddingRight: isSupport
+ ? `padding-right:${app.windowWidth - rect.left}px`
+ : '',
+ leftWidth: isSupport ? `width:${app.windowWidth - rect.left}px` : '',
})
-
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
@@ -89,42 +84,39 @@ Component({
}
},
/**
- * 组件的方法列表
- */
+ * 组件的方法列表
+ */
methods: {
- _showChange(show) {
- const animated = this.data.animated
- let displayStyle = ''
- if (animated) {
- displayStyle = `opacity: ${
- show ? '1' : '0'
- };-webkit-transition:opacity 0.5s;transition:opacity 0.5s;`
- } else {
- displayStyle = `display: ${show ? '' : 'none'}`
- }
- this.setData({
- displayStyle
- })
- },
- back() {
- const data = this.data
- console.log('---------222',getCurrentPages().length)
- if (data.delta) {
- wx.navigateBack({
- delta: data.delta
- })
- }
- // 如果是直接打开的,就默认回首页
- if (getCurrentPages().length == 1) {
- console.log('---------333')
- wx.switchTab({
- url: '/page/component/index',
- complete: (res) => {
- console.log(res)
- }
- })
+ _showChange(show) {
+ const animated = this.data.animated
+ let displayStyle = ''
+ if (animated) {
+ displayStyle = `opacity: ${show ? '1' : '0'
+ };-webkit-transition:opacity 0.5s;transition:opacity 0.5s;`
+ } else {
+ displayStyle = `display: ${show ? '' : 'none'}`
+ }
+ this.setData({
+ displayStyle
+ })
+ },
+ back() {
+ const data = this.data
+ if (data.delta) {
+ wx.navigateBack({
+ delta: data.delta
+ })
+ }
+ // 如果是直接打开的,就默认回首页
+ if (getCurrentPages().length == 1) {
+ wx.switchTab({
+ url: '/page/component/index',
+ complete: (res) => {
+ console.log(res)
}
- this.triggerEvent('back', { delta: data.delta }, {})
+ })
}
+ this.triggerEvent('back', { delta: data.delta }, {})
+ }
}
})
diff --git a/miniprogram/component/navigation-bar/navigation-bar.json b/miniprogram/component/navigation-bar/navigation-bar.json
index 23109a50..6245cfa7 100644
--- a/miniprogram/component/navigation-bar/navigation-bar.json
+++ b/miniprogram/component/navigation-bar/navigation-bar.json
@@ -2,6 +2,5 @@
"component": true,
"usingComponents": {},
"componentFramework": "glass-easel",
- "renderer": "skyline",
- "styleIsolation": "apply-shared"
+ "renderer": "skyline"
}
diff --git a/miniprogram/component/navigation-bar/navigation-bar.wxml b/miniprogram/component/navigation-bar/navigation-bar.wxml
index 69976661..b52e7382 100644
--- a/miniprogram/component/navigation-bar/navigation-bar.wxml
+++ b/miniprogram/component/navigation-bar/navigation-bar.wxml
@@ -36,7 +36,7 @@
-
+
diff --git a/miniprogram/components/navigation-bar/index.js b/miniprogram/components/navigation-bar/index.js
index 1b86cafe..34aad82b 100644
--- a/miniprogram/components/navigation-bar/index.js
+++ b/miniprogram/components/navigation-bar/index.js
@@ -1,3 +1,4 @@
+const app = getApp().globalData
Component({
options: {
multipleSlots: true, // 在组件定义时的选项中启用多slot支持
@@ -38,33 +39,28 @@ Component({
},
attached() {
- const isSupport = !!wx.getMenuButtonBoundingClientRect;
- const rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null;
- wx.getSystemInfo({
- success: (res) => {
- const ios = !!(res.system.toLowerCase().search('ios') + 1);
- const sideWidth = isSupport ? res.windowWidth - rect.left : 0;
+ const isSupport = !!wx.getMenuButtonBoundingClientRect
+ const rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null
+ const sideWidth = isSupport ? app.windowWidth - rect.left : 0
- this.setData({
- ios,
- sideWidth: this.data.sideWidth || sideWidth,
- statusBarHeight: res.statusBarHeight,
- });
- },
- });
+ this.setData({
+ ios: !!(app.system.toLowerCase().search('ios') + 1),
+ sideWidth: this.data.sideWidth || sideWidth,
+ statusBarHeight: app.statusBarHeight,
+ })
},
/**
* 组件的方法列表
*/
methods: {
back() {
- const { data } = this;
+ const { data } = this
if (data.delta) {
wx.navigateBack({
delta: data.delta,
- });
+ })
}
- this.triggerEvent('back', { delta: data.delta }, {});
+ this.triggerEvent('back', { delta: data.delta }, {})
},
},
-});
+})
diff --git a/miniprogram/components/page-scroll/index.js b/miniprogram/components/page-scroll/index.js
index a897a256..5f292cf4 100644
--- a/miniprogram/components/page-scroll/index.js
+++ b/miniprogram/components/page-scroll/index.js
@@ -1,89 +1,86 @@
-var globalThis = this, self = this;
+const globalThis = this; const
+ self = this
module.exports =
-require("../../_commons/0.js")([
-{
-"ids": [6],
-"modules":{
+require('../../_commons/0.js')([
+ {
+ ids: [6],
+ modules: {
-/***/ "./node_modules/@mpflow/webpack-plugin/lib/loaders/page-loader.js?appContext=src&outputPath=components%2Fpage-scroll%2Findex!./src/components/page-scroll/index.ts":
-/*!*************************************************************************************************************************************************************************!*\
+ /***/ './node_modules/@mpflow/webpack-plugin/lib/loaders/page-loader.js?appContext=src&outputPath=components%2Fpage-scroll%2Findex!./src/components/page-scroll/index.ts':
+ /*! *************************************************************************************************************************************************************************!*\
!*** ./node_modules/@mpflow/webpack-plugin/lib/loaders/page-loader.js?appContext=src&outputPath=components%2Fpage-scroll%2Findex!./src/components/page-scroll/index.ts ***!
- \*************************************************************************************************************************************************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
+ \************************************************************************************************************************************************************************ */
+ /*! no static exports found */
+ /***/ (function (module, exports, __webpack_require__) {
+ module.exports = __webpack_require__(/*! ./index.ts */ './src/components/page-scroll/index.ts')
+ /***/ }),
-module.exports = __webpack_require__(/*! ./index.ts */ "./src/components/page-scroll/index.ts")
-
-/***/ }),
-
-/***/ "./src/components/page-scroll/index.ts":
-/*!*********************************************!*\
+ /***/ './src/components/page-scroll/index.ts':
+ /*! *********************************************!*\
!*** ./src/components/page-scroll/index.ts ***!
- \*********************************************/
-/*! no static exports found */
-/***/ (function(module, exports) {
+ \******************************************** */
+ /*! no static exports found */
+ /***/ (function (module, exports) {
+ Component({
+ options: {
+ virtualHost: true
+ },
+ properties: {
+ refresherEnabled: {
+ type: Boolean,
+ value: false
+ },
+ refresherThreshold: {
+ type: Number,
+ value: 45
+ },
+ refresherDefaultStyle: {
+ type: String,
+ value: 'black'
+ },
+ refresherBackground: {
+ type: String,
+ value: '#FFF'
+ },
+ refresherTriggered: {
+ type: Boolean,
+ value: false
+ },
+ lowerThreshold: {
+ type: Number,
+ value: 50
+ },
+ scrollIntoView: {
+ type: String,
+ value: ''
+ }
+ },
+ methods: {
+ onScroll: function onScroll(e) {
+ this.triggerEvent('scroll', e.detail)
+ },
+ onScrollToLower: function onScrollToLower(e) {
+ this.triggerEvent('scrollToLower', e.detail)
+ },
+ onPulling: function onPulling(e) {
+ this.triggerEvent('pulling', e.detail)
+ },
+ onRefresh: function onRefresh(e) {
+ this.triggerEvent('refresh', e.detail)
+ },
+ onRestore: function onRestore(e) {
+ this.triggerEvent('restore', e.detail)
+ },
+ onAbort: function onAbort(e) {
+ this.triggerEvent('abort', e.detail)
+ }
+ }
+ })
+ /***/ })
-Component({
- options: {
- virtualHost: true
- },
- properties: {
- refresherEnabled: {
- type: Boolean,
- value: false
- },
- refresherThreshold: {
- type: Number,
- value: 45
- },
- refresherDefaultStyle: {
- type: String,
- value: 'black'
- },
- refresherBackground: {
- type: String,
- value: '#FFF'
- },
- refresherTriggered: {
- type: Boolean,
- value: false
- },
- lowerThreshold: {
- type: Number,
- value: 50
},
- scrollIntoView: {
- type: String,
- value: ''
- }
+ entries: [['./node_modules/@mpflow/webpack-plugin/lib/loaders/page-loader.js?appContext=src&outputPath=components%2Fpage-scroll%2Findex!./src/components/page-scroll/index.ts', 0]]
},
- methods: {
- onScroll: function onScroll(e) {
- this.triggerEvent('scroll', e.detail);
- },
- onScrollToLower: function onScrollToLower(e) {
- this.triggerEvent('scrollToLower', e.detail);
- },
- onPulling: function onPulling(e) {
- this.triggerEvent('pulling', e.detail);
- },
- onRefresh: function onRefresh(e) {
- this.triggerEvent('refresh', e.detail);
- },
- onRestore: function onRestore(e) {
- this.triggerEvent('restore', e.detail);
- },
- onAbort: function onAbort(e) {
- this.triggerEvent('abort', e.detail);
- }
- }
-});
-
-/***/ })
-
-},
-"entries": [["./node_modules/@mpflow/webpack-plugin/lib/loaders/page-loader.js?appContext=src&outputPath=components%2Fpage-scroll%2Findex!./src/components/page-scroll/index.ts",0]]
-},
-]);
+])
-// # sourceMappingURL=index.js.map
\ No newline at end of file
+// # sourceMappingURL=index.js.map
diff --git a/miniprogram/components/popup/index.js b/miniprogram/components/popup/index.js
index 0c30ad2f..f333b411 100644
--- a/miniprogram/components/popup/index.js
+++ b/miniprogram/components/popup/index.js
@@ -25,14 +25,14 @@ Component({
},
methods: {
close() {
- const { data } = this;
+ const { data } = this
console.log('@@@ close', data.maskClosable)
- if (!data.maskClosable) return;
+ if (!data.maskClosable) return
this.setData({
enable: !this.data.enable
- });
- this.triggerEvent('close', {}, {});
+ })
+ this.triggerEvent('close', {}, {})
},
// stopEvent() {},
},
-});
+})
diff --git a/miniprogram/packageAPI/pages/ai/mobilenet/index.js b/miniprogram/packageAPI/pages/ai/mobilenet/index.js
index 89ef3291..e06c7ff3 100644
--- a/miniprogram/packageAPI/pages/ai/mobilenet/index.js
+++ b/miniprogram/packageAPI/pages/ai/mobilenet/index.js
@@ -4,23 +4,23 @@ import { Classifier } from './classify'
import { FpsHelper } from '../../../../util/fps_helper'
-const { appWidth, appHeight, benchmarkLevel } = getApp().globalData;
+const { appWidth, appHeight, benchmarkLevel } = getApp().globalData
Page({
classifier: null,
ctx: null,
- fpsHelper:null,
+ fpsHelper: null,
predicting: false,
// For Speed Test
- constBuffer : null,
+ constBuffer: null,
/**
* 页面的初始数据
*/
data: {
- predClass: "None",
+ predClass: 'None',
classifier: null,
enableSpeedTest: false,
avgTime: 110.0,
@@ -31,8 +31,7 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad() {
- if (this.data.enableSpeedTest)
- {
+ if (this.data.enableSpeedTest) {
this.constBuffer = new Float32Array(3 * 224 * 224)
}
},
@@ -40,46 +39,45 @@ Page({
/**
* 生命周期函数--监听页面初次渲染完成
*/
- onReady() {
- this.ctx = wx.createCanvasContext('ssd1');
- const context = wx.createCameraContext(this);
- this.initClassifier();
- this.fpsHelper = new FpsHelper();
+ onReady() {
+ this.ctx = wx.createCanvasContext('ssd1')
+ const context = wx.createCameraContext(this)
+ this.initClassifier()
+ this.fpsHelper = new FpsHelper()
const listener = context.onCameraFrame(frame => {
+ const fps = this.fpsHelper.getAverageFps()
+ console.log(`fps=${fps}`)
- const fps = this.fpsHelper.getAverageFps();
- console.log(`fps=${fps}`);
-
- if (this.classifier && this.classifier.isReady() && !this.predicting) {
- this.executeClassify(frame);
- }
- });
- listener.start();
- this.fpsHelper.reset();
+ if (this.classifier && this.classifier.isReady() && !this.predicting) {
+ this.executeClassify(frame)
+ }
+ })
+ listener.start()
+ this.fpsHelper.reset()
},
/**
* 初始化 SSD models
*/
initClassifier() {
- wx.showLoading({ title: '模型正在加载...' });
- this.classifier = new Classifier({ width: appWidth, height: appHeight });
+ wx.showLoading({ title: '模型正在加载...' })
+ this.classifier = new Classifier({ width: appWidth, height: appHeight })
this.classifier.load().then(() => {
- wx.hideLoading();
+ wx.hideLoading()
}).catch(err => {
- console.log('模型加载报错:', err);
+ console.log('模型加载报错:', err)
})
},
- /**
+ /**
* 构建模型
*/
-async executeClassify (frame) {
- this.predicting = true;
+ async executeClassify(frame) {
+ this.predicting = true
if (this.classifier && this.classifier.isReady()) {
- this.fpsHelper.updateFPS();
+ this.fpsHelper.updateFPS()
this.setData({
predClass: this.classifier.predClass(),
@@ -92,82 +90,75 @@ async executeClassify (frame) {
})
}).catch((err) => {
console.log(err)
- })
+ })
- if (this.data.enableSpeedTest)
- {
- await this.inferSpeedTest();
+ if (this.data.enableSpeedTest) {
+ await this.inferSpeedTest()
}
}
- this.predicting = false;
+ this.predicting = false
},
- async inferSpeedTest()
- {
- console.log("runInferenceSession speed test start run===============================")
+ async inferSpeedTest() {
+ console.log('runInferenceSession speed test start run===============================')
- const xinput = {
- shape: [1, 3, 224, 224],
- data: this.constBuffer.buffer,
- type: 'float32',
- };
-
- this.data.classifier = this.classifier;
+ const xinput = {
+ shape: [1, 3, 224, 224],
+ data: this.constBuffer.buffer,
+ type: 'float32',
+ }
- // warm up
- for (let index = 0; index < 20; index++) {
+ this.data.classifier = this.classifier
- await this.inferOnce(xinput, this.data);
- }
+ // warm up
+ for (let index = 0; index < 20; index++) {
+ await this.inferOnce(xinput, this.data)
+ }
- for (var l = 0; l < 5; ++l)
- {
- var beMs = new Date().getTime()
+ for (let l = 0; l < 5; ++l) {
+ const beMs = new Date().getTime()
- for (let index = 0; index < 100; index++) {
+ for (let index = 0; index < 100; index++) {
+ await this.inferOnce(xinput, this.data)
+ }
- await this.inferOnce(xinput, this.data);
- }
+ const afMs = new Date().getTime()
- var afMs = new Date().getTime()
-
- var avgTime = (afMs - beMs) / 100.0;
+ const avgTime = (afMs - beMs) / 100.0
- var overall = 0.0;
- var minTime = 1000000.0;
+ let overall = 0.0
+ let minTime = 1000000.0
- for (let index = 0; index < 100; index++) {
- var beMsTmp = new Date().getTime()
- await this.inferOnce(xinput, this.data);
- var afMsTmp = new Date().getTime()
- var tmpTime = (afMsTmp - beMsTmp)
- if (minTime > tmpTime)
- {
- minTime = tmpTime;
- }
- overall += (afMsTmp - beMsTmp)
- }
+ for (let index = 0; index < 100; index++) {
+ const beMsTmp = new Date().getTime()
+ await this.inferOnce(xinput, this.data)
+ const afMsTmp = new Date().getTime()
+ const tmpTime = (afMsTmp - beMsTmp)
+ if (minTime > tmpTime) {
+ minTime = tmpTime
+ }
+ overall += (afMsTmp - beMsTmp)
+ }
- console.log("Inference min time: ", minTime)
- console.log("Inference avg time: ", avgTime)
+ console.log('Inference min time: ', minTime)
+ console.log('Inference avg time: ', avgTime)
- this.setData({
- predClass: this.classifier.predClass(),
- minTime : minTime,
- avgTime : avgTime,
- })
- }
+ this.setData({
+ predClass: this.classifier.predClass(),
+ minTime,
+ avgTime,
+ })
+ }
},
inferOnce(xinput, data) {
return new Promise(function (resolve, reject) {
data.classifier.session.run({
- "input": xinput,
+ input: xinput,
}).then(async function (res) {
resolve()
})
-
})
},
@@ -190,7 +181,7 @@ async executeClassify (frame) {
*/
onUnload() {
if (this.classifier && this.classifier.isReady()) {
- this.classifier.dispose();
+ this.classifier.dispose()
}
},
@@ -217,4 +208,4 @@ async executeClassify (frame) {
path: 'packageAPI/pages/ai/mobilenet/index',
}
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js b/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js
index a403af68..4fcf22a2 100644
--- a/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js
+++ b/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js
@@ -4,23 +4,23 @@ import { Classifier } from './classify'
import { FpsHelper } from '../../../../util/fps_helper'
-const { appWidth, appHeight, benchmarkLevel } = getApp().globalData;
+const { appWidth, appHeight, benchmarkLevel } = getApp().globalData
Page({
classifier: null,
ctx: null,
- fpsHelper:null,
+ fpsHelper: null,
predicting: false,
// For Speed Test
- constBuffer : null,
+ constBuffer: null,
/**
* 页面的初始数据
*/
data: {
- predClass: "None",
+ predClass: 'None',
classifier: null,
enableSpeedTest: false,
avgTime: 110.0,
@@ -31,8 +31,7 @@ Page({
* 生命周期函数--监听页面加载
*/
onLoad() {
- if (this.data.enableSpeedTest)
- {
+ if (this.data.enableSpeedTest) {
this.constBuffer = new Float32Array(3 * 224 * 224)
}
},
@@ -40,46 +39,45 @@ Page({
/**
* 生命周期函数--监听页面初次渲染完成
*/
- onReady() {
- this.ctx = wx.createCanvasContext('ssd');
- const context = wx.createCameraContext(this);
- this.initClassifier();
- this.fpsHelper = new FpsHelper();
+ onReady() {
+ this.ctx = wx.createCanvasContext('ssd')
+ const context = wx.createCameraContext(this)
+ this.initClassifier()
+ this.fpsHelper = new FpsHelper()
const listener = context.onCameraFrame(frame => {
+ const fps = this.fpsHelper.getAverageFps()
+ console.log(`fps=${fps}`)
- const fps = this.fpsHelper.getAverageFps();
- console.log(`fps=${fps}`);
-
- if (this.classifier && this.classifier.isReady() && !this.predicting) {
- this.executeClassify(frame);
- }
- });
- listener.start();
- this.fpsHelper.reset();
+ if (this.classifier && this.classifier.isReady() && !this.predicting) {
+ this.executeClassify(frame)
+ }
+ })
+ listener.start()
+ this.fpsHelper.reset()
},
/**
* 初始化 SSD models
*/
initClassifier() {
- wx.showLoading({ title: '模型正在加载...' });
- this.classifier = new Classifier({ width: appWidth, height: appHeight });
+ wx.showLoading({ title: '模型正在加载...' })
+ this.classifier = new Classifier({ width: appWidth, height: appHeight })
this.classifier.load().then(() => {
- wx.hideLoading();
+ wx.hideLoading()
}).catch(err => {
- console.log('模型加载报错:', err);
+ console.log('模型加载报错:', err)
})
},
- /**
+ /**
* 构建模型
*/
-async executeClassify (frame) {
- this.predicting = true;
+ async executeClassify(frame) {
+ this.predicting = true
if (this.classifier && this.classifier.isReady()) {
- this.fpsHelper.updateFPS();
+ this.fpsHelper.updateFPS()
this.setData({
predClass: this.classifier.predClass(),
@@ -92,81 +90,75 @@ async executeClassify (frame) {
})
}).catch((err) => {
console.log(err)
- })
+ })
- if (this.data.enableSpeedTest)
- {
- await this.inferSpeedTest();
+ if (this.data.enableSpeedTest) {
+ await this.inferSpeedTest()
}
}
- this.predicting = false;
+ this.predicting = false
},
- async inferSpeedTest()
- {
- console.log("runInferenceSession speed test start run===============================")
-
- const xinput = {
- shape: [1, 3, 224, 224],
- data: this.constBuffer.buffer,
- type: 'float32',
- };
-
- this.data.classifier = this.classifier;
-
- // warm up
- for (let index = 0; index < 20; index++) {
- await this.inferOnce(xinput, this.data);
- }
+ async inferSpeedTest() {
+ console.log('runInferenceSession speed test start run===============================')
- for (var l = 0; l < 5; ++l)
- {
- var beMs = new Date().getTime()
+ const xinput = {
+ shape: [1, 3, 224, 224],
+ data: this.constBuffer.buffer,
+ type: 'float32',
+ }
- for (let index = 0; index < 100; index++) {
+ this.data.classifier = this.classifier
- await this.inferOnce(xinput, this.data);
- }
+ // warm up
+ for (let index = 0; index < 20; index++) {
+ await this.inferOnce(xinput, this.data)
+ }
+
+ for (let l = 0; l < 5; ++l) {
+ const beMs = new Date().getTime()
- var afMs = new Date().getTime()
-
- var avgTime = (afMs - beMs) / 100.0;
+ for (let index = 0; index < 100; index++) {
+ await this.inferOnce(xinput, this.data)
+ }
- var overall = 0.0;
- var minTime = 1000000.0;
+ const afMs = new Date().getTime()
- for (let index = 0; index < 100; index++) {
- var beMsTmp = new Date().getTime()
- await this.inferOnce(xinput, this.data);
- var afMsTmp = new Date().getTime()
- var tmpTime = (afMsTmp - beMsTmp)
- if (minTime > tmpTime)
- {
- minTime = tmpTime;
- }
- overall += (afMsTmp - beMsTmp)
- }
+ const avgTime = (afMs - beMs) / 100.0
- console.log("Inference min time: ", minTime)
- console.log("Inference avg time: ", avgTime)
+ let overall = 0.0
+ let minTime = 1000000.0
- this.setData({
- predClass: this.classifier.predClass(),
- minTime : minTime,
- avgTime : avgTime,
- })
+ for (let index = 0; index < 100; index++) {
+ const beMsTmp = new Date().getTime()
+ await this.inferOnce(xinput, this.data)
+ const afMsTmp = new Date().getTime()
+ const tmpTime = (afMsTmp - beMsTmp)
+ if (minTime > tmpTime) {
+ minTime = tmpTime
+ }
+ overall += (afMsTmp - beMsTmp)
}
+
+ console.log('Inference min time: ', minTime)
+ console.log('Inference avg time: ', avgTime)
+
+ this.setData({
+ predClass: this.classifier.predClass(),
+ minTime,
+ avgTime,
+ })
+ }
},
inferOnce(xinput, data) {
return new Promise(function (resolve, reject) {
data.classifier.session.run({
- "onnx::QuantizeLinear_0": xinput,
+ 'onnx::QuantizeLinear_0': xinput,
}).then(async function (res) {
resolve()
})
-
})
},
@@ -189,7 +181,7 @@ async executeClassify (frame) {
*/
onUnload() {
if (this.classifier && this.classifier.isReady()) {
- this.classifier.dispose();
+ this.classifier.dispose()
}
},
@@ -216,4 +208,4 @@ async executeClassify (frame) {
path: 'packageAPI/pages/ai/mobilenet_int8/index',
}
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ai/style-trans/index.js b/miniprogram/packageAPI/pages/ai/style-trans/index.js
index b1bafefc..f896ec13 100644
--- a/miniprogram/packageAPI/pages/ai/style-trans/index.js
+++ b/miniprogram/packageAPI/pages/ai/style-trans/index.js
@@ -1,4 +1,3 @@
-
// pages/stype-trans/index.js.ts
Page({
session: null,
@@ -8,10 +7,10 @@ Page({
* 页面的初始数据
*/
data: {
- src : '',
- imageWidth : 224,
- imageHeight : 224,
- imageChannel : 3,
+ src: '',
+ imageWidth: 224,
+ imageHeight: 224,
+ imageChannel: 3,
},
/**
@@ -70,7 +69,7 @@ Page({
},
- takePhoto() {
+ takePhoto() {
const camera = wx.createCameraContext()
camera.takePhoto({
quality: 'normal',
@@ -79,7 +78,7 @@ Page({
src: res.tempImagePath
})
- const canvas = wx.createOffscreenCanvas({type: '2d', width: this.data.imageWidth, height: this.data.imageHeight})
+ const canvas = wx.createOffscreenCanvas({ type: '2d', width: this.data.imageWidth, height: this.data.imageHeight })
const ctx = canvas.getContext('2d')
@@ -105,58 +104,53 @@ Page({
})
}
})
-
},
- InitSession()
- {
+ InitSession() {
return new Promise((resolve, reject) => {
- const modelPath = `${wx.env.USER_DATA_PATH}/mosaic-8.onnx`;
+ const modelPath = `${wx.env.USER_DATA_PATH}/mosaic-8.onnx`
// 判断之前是否已经下载过onnx模型
wx.getFileSystemManager().access({
- path: modelPath,
- success: (res) =>
- {
- console.log("file already exist at: " + modelPath)
- this.createInferenceSession(modelPath).then(() =>
- {
- resolve();
- })
- },
- fail: (res) => {
- console.error(res)
+ path: modelPath,
+ success: (res) => {
+ console.log('file already exist at: ' + modelPath)
+ this.createInferenceSession(modelPath).then(() => {
+ resolve()
+ })
+ },
+ fail: (res) => {
+ console.error(res)
- wx.cloud.init();
- console.log("begin download model");
+ wx.cloud.init()
+ console.log('begin download model')
- const cloudPath = 'cloud://containertest-0gmw3ulnd8d9bc7b.636f-containertest-0gmw3ulnd8d9bc7b-1258211818/mosaic-8.onnx'
+ const cloudPath = 'cloud://containertest-0gmw3ulnd8d9bc7b.636f-containertest-0gmw3ulnd8d9bc7b-1258211818/mosaic-8.onnx'
- this.downloadFile(cloudPath, function(r) {
- console.log(`下载进度:${r.progress}%,已下载${r.totalBytesWritten}B,共${r.totalBytesExpectedToWrite}B`)
- }).then(result => {
+ this.downloadFile(cloudPath, function (r) {
+ console.log(`下载进度:${r.progress}%,已下载${r.totalBytesWritten}B,共${r.totalBytesExpectedToWrite}B`)
+ }).then(result => {
wx.getFileSystemManager().saveFile({
- tempFilePath:result.tempFilePath,
+ tempFilePath: result.tempFilePath,
filePath: modelPath,
success: (res) => { // 注册回调函数
console.log(res)
-
- const modelPath = res.savedFilePath;
- console.log("save onnx model at path: " + modelPath)
+
+ const modelPath = res.savedFilePath
+ console.log('save onnx model at path: ' + modelPath)
this.createInferenceSession(modelPath).then(() => {
- resolve();
+ resolve()
})
},
fail(res) {
console.error(res)
- return
}
})
- });
+ })
}
})
- })
+ })
},
createInferenceSession(modelPath) {
@@ -171,23 +165,23 @@ Page({
Higher precision always require longer time to run session
*/
- precisionLevel : 4,
- allowNPU : false, // wheather use NPU for inference, only useful for IOS
+ precisionLevel: 4,
+ allowNPU: false, // wheather use NPU for inference, only useful for IOS
allowQuantize: false, // wheather generate quantize model
- });
+ })
// 监听error事件
this.session.onError((error) => {
- console.error(error);
- reject(error);
- });
+ console.error(error)
+ reject(error)
+ })
this.session.onLoad(() => {
- resolve();
- });
+ resolve()
+ })
})
},
-downloadFile(fileID, onCall = () => {}) {
+ downloadFile(fileID, onCall = () => {}) {
return new Promise((resolve, reject) => {
const task = wx.cloud.downloadFile({
fileID,
@@ -209,83 +203,76 @@ downloadFile(fileID, onCall = () => {}) {
})
},
- detect(imgData)
- {
- return new Promise((resolve, reject) =>
- {
+ detect(imgData) {
+ return new Promise((resolve, reject) => {
const uint8Data = new Uint8Array(imgData.data)
- var floatData = new Float32Array(this.data.imageChannel * this.data.imageHeight * this.data.imageWidth);
+ const floatData = new Float32Array(this.data.imageChannel * this.data.imageHeight * this.data.imageWidth)
// nhwc uint8 data to nchw float32 data, and ignore the alpha channel
const modelChannel = this.data.imageChannel
-
- const imageWH = this.data.imageHeight * this.data.imageWidth;
-
- var idx = 0;
- for (var c = 0; c < modelChannel; ++c)
- {
- for (var wh = 0; wh < imageWH; ++wh)
- {
- var inputIdx = wh * 4 + c;
- floatData[idx] = uint8Data[inputIdx];
- idx++;
+
+ const imageWH = this.data.imageHeight * this.data.imageWidth
+
+ let idx = 0
+ for (let c = 0; c < modelChannel; ++c) {
+ for (let wh = 0; wh < imageWH; ++wh) {
+ const inputIdx = wh * 4 + c
+ floatData[idx] = uint8Data[inputIdx]
+ idx++
}
- }
+ }
const xinput = {
- shape: [1, 3, 224, 224], // Input data shape in NCHW
+ shape: [1, 3, 224, 224], // Input data shape in NCHW
data: floatData.buffer,
- type: 'float32', // Input data type
- };
+ type: 'float32', // Input data type
+ }
this.session.run({
- // Here string "input1" Should be the same with the input name in onnx file
- "input1" : xinput,
+ // Here string "input1" Should be the same with the input name in onnx file
+ input1: xinput,
}).then((res) => {
- // Here use res.outputname.data, outputname
+ // Here use res.outputname.data, outputname
// Should be the same with the output name in onnx file
- let output = new Float32Array(res.output1.data)
+ const output = new Float32Array(res.output1.data)
- const hwSize = imgData.height * imgData.width;
+ const hwSize = imgData.height * imgData.width
- var finalout = new Uint8ClampedArray(4 * hwSize);
+ const finalout = new Uint8ClampedArray(4 * hwSize)
// fill the alpha channel
- finalout.fill(255);
+ finalout.fill(255)
// convert from nchw to nhwc
- idx = 0;
- for (var c = 0; c < modelChannel; ++c)
- {
- for (var hw = 0; hw < hwSize; ++hw)
- {
- var dstIdx = hw * 4 + c;
- finalout[dstIdx] = Math.max(0, Math.min(Math.round(output[idx]), 255));
- idx++;
+ idx = 0
+ for (let c = 0; c < modelChannel; ++c) {
+ for (let hw = 0; hw < hwSize; ++hw) {
+ const dstIdx = hw * 4 + c
+ finalout[dstIdx] = Math.max(0, Math.min(Math.round(output[idx]), 255))
+ idx++
}
}
this.canvasCtx = wx.createCanvasContext('trans')
- wx.canvasPutImageData
- ({
+ wx.canvasPutImageData({
canvasId: 'trans',
data: finalout,
height: 224,
width: 224,
x: 0,
y: 0,
- }).then((res) =>{
+ }).then((res) => {
console.log(res)
})
})
- resolve();
+ resolve()
})
},
error(e) {
console.log(e.detail)
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/api/choose-address/choose-address.js b/miniprogram/packageAPI/pages/api/choose-address/choose-address.js
index c7e67c1d..8234545f 100644
--- a/miniprogram/packageAPI/pages/api/choose-address/choose-address.js
+++ b/miniprogram/packageAPI/pages/api/choose-address/choose-address.js
@@ -29,12 +29,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/choose-invoice-title/choose-invoice-title.js b/miniprogram/packageAPI/pages/api/choose-invoice-title/choose-invoice-title.js
index ba976ab0..5878845a 100644
--- a/miniprogram/packageAPI/pages/api/choose-invoice-title/choose-invoice-title.js
+++ b/miniprogram/packageAPI/pages/api/choose-invoice-title/choose-invoice-title.js
@@ -41,12 +41,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/custom-message/custom-message.js b/miniprogram/packageAPI/pages/api/custom-message/custom-message.js
index d4e307ac..b5361819 100644
--- a/miniprogram/packageAPI/pages/api/custom-message/custom-message.js
+++ b/miniprogram/packageAPI/pages/api/custom-message/custom-message.js
@@ -5,7 +5,7 @@ Page({
path: 'packageAPI/pages/api/custom-message/custom-message'
}
},
- handleContact (e) {
+ handleContact(e) {
console.log(e.detail.path)
console.log(e.detail.query)
},
@@ -16,12 +16,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/get-user-info/get-user-info.js b/miniprogram/packageAPI/pages/api/get-user-info/get-user-info.js
index 272ea109..aade5ce3 100644
--- a/miniprogram/packageAPI/pages/api/get-user-info/get-user-info.js
+++ b/miniprogram/packageAPI/pages/api/get-user-info/get-user-info.js
@@ -45,12 +45,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (wx.getUserProfile) {
diff --git a/miniprogram/packageAPI/pages/api/jump/jump.js b/miniprogram/packageAPI/pages/api/jump/jump.js
index 70c62018..3da1fbde 100644
--- a/miniprogram/packageAPI/pages/api/jump/jump.js
+++ b/miniprogram/packageAPI/pages/api/jump/jump.js
@@ -10,49 +10,49 @@ Page({
theme: 'light',
setting: {}
},
- //打开半屏小程序
- openhalfscreenminiprogram(){
+ // 打开半屏小程序
+ openhalfscreenminiprogram() {
wx.openEmbeddedMiniProgram({
- appId: 'wxfdcee92a299bcaf1', // 腾讯公益
- extraData: {
- foo: 'bar'
- },
- // envVersion: 'develop',
- success(res) {
- // 打开成功
- }
+ appId: 'wxfdcee92a299bcaf1', // 腾讯公益
+ extraData: {
+ foo: 'bar'
+ },
+ // envVersion: 'develop',
+ success(res) {
+ // 打开成功
+ }
})
},
- //打开另一个小程序
- openanotherminiprogram(){
+ // 打开另一个小程序
+ openanotherminiprogram() {
wx.navigateToMiniProgram({
- appId: 'wxfdcee92a299bcaf1', // 腾讯公益
- // extraData: {
- // foo: 'bar'
- // },
- // envVersion: 'develop',
- success(res) {
- // 打开成功
- }
+ appId: 'wxfdcee92a299bcaf1', // 腾讯公益
+ // extraData: {
+ // foo: 'bar'
+ // },
+ // envVersion: 'develop',
+ success(res) {
+ // 打开成功
+ }
})
},
- //退出当前小程序
- exitminiprogram(){
+ // 退出当前小程序
+ exitminiprogram() {
wx.exitMiniProgram({
- success(){
- wx.showToast({
- title: '退出成功',
- icon: 'none',
- duration: 2000
- })
- },
- fail(){
- wx.showToast({
- title: '退出失败',
- icon: 'none',
- duration: 2000
- })
- }
+ success() {
+ wx.showToast({
+ title: '退出成功',
+ icon: 'none',
+ duration: 2000
+ })
+ },
+ fail() {
+ wx.showToast({
+ title: '退出失败',
+ icon: 'none',
+ duration: 2000
+ })
+ }
})
},
onUnload() {
@@ -62,12 +62,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/login/login.js b/miniprogram/packageAPI/pages/api/login/login.js
index 3baeb750..16c2b4a8 100644
--- a/miniprogram/packageAPI/pages/api/login/login.js
+++ b/miniprogram/packageAPI/pages/api/login/login.js
@@ -14,20 +14,19 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
hasLogin: app.globalData.hasLogin
})
},
- data: {
- theme: 'light',},
+ data: { theme: 'light' },
login() {
const that = this
wx.login({
diff --git a/miniprogram/packageAPI/pages/api/request-payment/request-payment.js b/miniprogram/packageAPI/pages/api/request-payment/request-payment.js
index aed144fe..5620a80d 100644
--- a/miniprogram/packageAPI/pages/api/request-payment/request-payment.js
+++ b/miniprogram/packageAPI/pages/api/request-payment/request-payment.js
@@ -1,4 +1,3 @@
-
const app = getApp()
Page({
@@ -16,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
@@ -40,7 +39,7 @@ Page({
wx.cloud.callFunction({
name: 'pay',
data: {
- theme: 'light',
+ theme: 'light',
action: 'unifiedorder',
userInfo: {
openId: openid
@@ -57,7 +56,7 @@ Page({
signType: 'MD5',
paySign: data.sign,
success: () => {
- wx.showToast({title: '支付成功'})
+ wx.showToast({ title: '支付成功' })
},
fail(err) {
self.setData({
diff --git a/miniprogram/packageAPI/pages/api/setting/setting.js b/miniprogram/packageAPI/pages/api/setting/setting.js
index 7fdff7b9..fa17cefa 100644
--- a/miniprogram/packageAPI/pages/api/setting/setting.js
+++ b/miniprogram/packageAPI/pages/api/setting/setting.js
@@ -15,7 +15,7 @@ Page({
wx.getSetting({
success: (res) => {
console.log(res)
- this.setData({setting: res.authSetting})
+ this.setData({ setting: res.authSetting })
}
})
},
@@ -26,12 +26,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/share-button/share-button.js b/miniprogram/packageAPI/pages/api/share-button/share-button.js
index 7d8a20eb..66b69160 100644
--- a/miniprogram/packageAPI/pages/api/share-button/share-button.js
+++ b/miniprogram/packageAPI/pages/api/share-button/share-button.js
@@ -21,12 +21,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/share/share.js b/miniprogram/packageAPI/pages/api/share/share.js
index b70870d7..6d50d1d6 100644
--- a/miniprogram/packageAPI/pages/api/share/share.js
+++ b/miniprogram/packageAPI/pages/api/share/share.js
@@ -2,7 +2,7 @@ Page({
data: {
theme: 'light',
sharedata: {
- theme: 'light',
+ theme: 'light',
title: '自定义转发标题',
desc: '自定义转发描述',
path: 'packageAPI/pages/api/share/share'
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js b/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js
index 23d91313..5ab8d8be 100644
--- a/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js
+++ b/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js
@@ -1,4 +1,3 @@
-
Page({
onShareAppMessage() {
return {
@@ -83,12 +82,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js b/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js
index 52a4fac3..2e10e175 100644
--- a/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js
+++ b/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js
@@ -30,7 +30,7 @@ Page({
wx.cloud.callFunction({
name: 'openapi',
data: {
- theme: 'light',
+ theme: 'light',
action: 'sendSubscribeMessage'
},
success: res => {
@@ -54,22 +54,16 @@ Page({
/**
* 生命周期函数--监听页面加载
*/
- onUnload() {
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
-
},
/**
@@ -97,7 +91,9 @@ Page({
* 生命周期函数--监听页面卸载
*/
onUnload() {
-
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
/**
diff --git a/miniprogram/packageAPI/pages/ar/2dmarker-ar/2dmarker-ar.js b/miniprogram/packageAPI/pages/ar/2dmarker-ar/2dmarker-ar.js
index fac3559d..632d3f4c 100644
--- a/miniprogram/packageAPI/pages/ar/2dmarker-ar/2dmarker-ar.js
+++ b/miniprogram/packageAPI/pages/ar/2dmarker-ar/2dmarker-ar.js
@@ -9,36 +9,36 @@ Component({
behaviors: [arBehavior, threeBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.6, // canvas高度缩放值
- markerImgList: [], // 使用的 marker 列表
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.6, // canvas高度缩放值
+ markerImgList: [], // 使用的 marker 列表
chooseImgList: [], // 使用的 图片 列表
- hintBoxList: [], // 显示提示盒子列表
+ hintBoxList: [], // 显示提示盒子列表
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
@@ -52,12 +52,12 @@ Component({
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
- this.markerIndex = 0;
+ this.markerIndex = 0
// 添加 识别包围盒子
- this.add3DBox();
+ this.add3DBox()
},
initVK() {
// VKSession 配置
@@ -70,7 +70,7 @@ Component({
},
version: 'v1',
gl: this.gl
- });
+ })
session.start(err => {
if (err) return console.error('VK error: ', err)
@@ -79,55 +79,53 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
// console.log("addAnchor", anchors);
- this.left.visible = true;
- this.right.visible = true;
- this.top.visible = true;
- this.bottom.visible = true;
+ this.left.visible = true
+ this.right.visible = true
+ this.top.visible = true
+ this.bottom.visible = true
})
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// marker 模式下,目前仅有一个识别目标,可以直接取
- const anchor = anchors[0];
- const markerId = anchor.id;
- const size = anchor.size;
+ const anchor = anchors[0]
+ const markerId = anchor.id
+ const size = anchor.size
this.hintInfo = {
- markerId: markerId,
- size: size
+ markerId,
+ size
}
})
-
+
// VKSession removeAnchors
// 识别目标丢失时,会触发一次
session.on('removeAnchors', anchors => {
- this.left.visible = false;
- this.right.visible = false;
- this.top.visible = false;
- this.bottom.visible = false;
+ this.left.visible = false
+ this.right.visible = false
+ this.top.visible = false
+ this.bottom.visible = false
if (this.data.hintBoxList && this.data.hintBoxList.length > 0) {
// 清理信息
- this.hintInfo = undefined;
+ this.hintInfo = undefined
// 存在列表的情况,去除remove
this.setData({
hintBoxList: []
- });
+ })
}
- });
-
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
+ this.initLoop()
+ })
},
loop() {
// console.log('loop')
@@ -136,7 +134,7 @@ Component({
const frame = this.session.getVKFrame(this.canvas.width, this.canvas.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
this.renderYUV(frame)
@@ -150,8 +148,8 @@ Component({
this.camera.matrixAutoUpdate = false
// 视图矩阵
- this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix);
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse);
+ this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
// 投影矩阵
const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR)
@@ -162,28 +160,28 @@ Component({
// 绘制而为提示框的逻辑
if (this.hintInfo) {
// 存在提示信息,则更新
- const THREE = this.THREE;
+ const THREE = this.THREE
// 原点偏移矩阵,VK情况下,marker 点对应就是 0 0 0,世界矩阵可以认为是一个单位矩阵
// marker 右侧点可以理解是 0.5 0 0
- const center = new THREE.Vector3();
- const right = new THREE.Vector3(0.5, 0, 0);
+ const center = new THREE.Vector3()
+ const right = new THREE.Vector3(0.5, 0, 0)
// 获取设备空间坐标
- const devicePos = center.clone().project(this.camera);
+ const devicePos = center.clone().project(this.camera)
// 转换坐标系,从 (-1, 1) 转到 (0, 100),同时移到左上角 0 0,右下角 1 1
- const screenPos = new THREE.Vector3(0, 0, 0);
- screenPos.x = devicePos.x * 50 + 50;
- screenPos.y = 50 - devicePos.y * 50;
+ const screenPos = new THREE.Vector3(0, 0, 0)
+ screenPos.x = devicePos.x * 50 + 50
+ screenPos.y = 50 - devicePos.y * 50
// 获取右侧点信息
- const deviceRightPos = right.clone().project(this.camera);
- const screenRightPos = new THREE.Vector3(0, 0, 0);
- screenRightPos.x = deviceRightPos.x * 50 + 50;
+ const deviceRightPos = right.clone().project(this.camera)
+ const screenRightPos = new THREE.Vector3(0, 0, 0)
+ screenRightPos.x = deviceRightPos.x * 50 + 50
+
+ const markerHalfWidth = screenRightPos.x - screenPos.x
- const markerHalfWidth = screenRightPos.x - screenPos.x;
-
this.setData({
hintBoxList: [
{
@@ -194,7 +192,7 @@ Component({
height: markerHalfWidth * this.data.domWidth * 2 / 100,
}
]
- });
+ })
}
this.renderer.autoClearColor = false
@@ -205,53 +203,53 @@ Component({
add3DBox() {
// 添加marker需要的 三维包围框
- const THREE = this.THREE;
- const scene = this.scene;
+ const THREE = this.THREE
+ const scene = this.scene
- const material = new THREE.MeshPhysicalMaterial( {
+ const material = new THREE.MeshPhysicalMaterial({
metalness: 0.0,
roughness: 0.1,
color: 0x64f573,
- } );
- const geometry = new THREE.BoxGeometry( 1, 1, 1 );
-
- const borderSize = 0.1;
-
- const left = new THREE.Mesh( geometry, material );
- left.position.set(-0.5, 0, 0 );
- left.rotation.set(-Math.PI / 2, 0, 0 )
- left.scale.set(borderSize, 1.1, borderSize);
- scene.add( left );
- left.visible = false;
- this.left = left;
-
- const right = new THREE.Mesh( geometry, material );
- right.position.set(0.5, 0, 0 );
- right.rotation.set(-Math.PI / 2, 0, 0 )
- right.scale.set(borderSize, 1.1, borderSize);
- scene.add( right );
- right.visible = false;
- this.right = right;
-
- const top = new THREE.Mesh( geometry, material );
- top.position.set(0, 0, 0.5 );
- top.rotation.set(0, 0, 0 )
- top.scale.set(1.1, borderSize, borderSize);
- scene.add( top );
- top.visible = false;
- this.top = top;
-
- const bottom = new THREE.Mesh( geometry, material );
- bottom.position.set(0, 0, -0.5 );
- bottom.rotation.set(0, 0, 0 )
- bottom.scale.set(1.1, borderSize, borderSize);
- scene.add( bottom );
- bottom.visible = false;
- this.bottom = bottom;
+ })
+ const geometry = new THREE.BoxGeometry(1, 1, 1)
+
+ const borderSize = 0.1
+
+ const left = new THREE.Mesh(geometry, material)
+ left.position.set(-0.5, 0, 0)
+ left.rotation.set(-Math.PI / 2, 0, 0)
+ left.scale.set(borderSize, 1.1, borderSize)
+ scene.add(left)
+ left.visible = false
+ this.left = left
+
+ const right = new THREE.Mesh(geometry, material)
+ right.position.set(0.5, 0, 0)
+ right.rotation.set(-Math.PI / 2, 0, 0)
+ right.scale.set(borderSize, 1.1, borderSize)
+ scene.add(right)
+ right.visible = false
+ this.right = right
+
+ const top = new THREE.Mesh(geometry, material)
+ top.position.set(0, 0, 0.5)
+ top.rotation.set(0, 0, 0)
+ top.scale.set(1.1, borderSize, borderSize)
+ scene.add(top)
+ top.visible = false
+ this.top = top
+
+ const bottom = new THREE.Mesh(geometry, material)
+ bottom.position.set(0, 0, -0.5)
+ bottom.rotation.set(0, 0, 0)
+ bottom.scale.set(1.1, borderSize, borderSize)
+ scene.add(bottom)
+ bottom.visible = false
+ this.bottom = bottom
console.log('add3DBox is finish')
},
- chooseMedia() {
+ chooseMedia() {
// marker图片上传逻辑
wx.chooseMedia({
count: 9,
@@ -260,10 +258,10 @@ Component({
success: res => {
console.log('chooseMedia res', res)
- const chooseImgListRes = [];
+ const chooseImgListRes = []
for (let i = 0; i < res.tempFiles.length; i++) {
- const imgUrl = res.tempFiles[i].tempFilePath;
- chooseImgListRes.push(imgUrl);
+ const imgUrl = res.tempFiles[i].tempFilePath
+ chooseImgListRes.push(imgUrl)
}
console.log('set chooseImgList', chooseImgListRes)
@@ -279,88 +277,87 @@ Component({
async addMarker() {
console.log('addMarker')
const fs = wx.getFileSystemManager()
-
- const markerImgListRes = this.data.markerImgList.concat([]);
- const preMarkerIndex = this.markerIndex;
- console.log('pre markerImgList', preMarkerIndex, markerImgListRes);
-
+ const markerImgListRes = this.data.markerImgList.concat([])
+ const preMarkerIndex = this.markerIndex
+
+ console.log('pre markerImgList', preMarkerIndex, markerImgListRes)
+
// 检查与添加 marker 函数
- const chooseImgCount = this.data.chooseImgList.length;
- let handledCount = 0;
+ const chooseImgCount = this.data.chooseImgList.length
+ let handledCount = 0
const checkMarkerAdded = () => {
if (handledCount === chooseImgCount) {
- this.markerIndex = markerImgListRes.length;
+ this.markerIndex = markerImgListRes.length
- console.log('markerImgList set', markerImgListRes, this.markerIndex);
+ console.log('markerImgList set', markerImgListRes, this.markerIndex)
this.setData({
chooseImgList: [],
markerImgList: markerImgListRes
- });
+ })
}
}
-
+
// 准备进行choose的图片保存到fs
for (let i = 0; i < chooseImgCount; i++) {
- const chooseImgUrl = this.data.chooseImgList[i];
- const fileEnd = chooseImgUrl.split('.').slice(-1)[0];
- const fileIndex = preMarkerIndex + i;
+ const chooseImgUrl = this.data.chooseImgList[i]
+ const fileEnd = chooseImgUrl.split('.').slice(-1)[0]
+ const fileIndex = preMarkerIndex + i
// 算法侧目前只认 map png jpg jpeg 后缀文件
- const filePath = `${wx.env.USER_DATA_PATH}/marker-ar-${fileIndex}.${fileEnd}`;
+ const filePath = `${wx.env.USER_DATA_PATH}/marker-ar-${fileIndex}.${fileEnd}`
const saveAndAddMarker = () => {
- console.log('saveFileSync start', filePath, chooseImgUrl);
+ console.log('saveFileSync start', filePath, chooseImgUrl)
// 存入文件系统,并添加到marker
fs.saveFile({
filePath,
tempFilePath: chooseImgUrl,
- success: ()=> {
+ success: () => {
console.log('[addMarker] --> ', filePath)
const markerId = this.session.addMarker(filePath)
markerImgListRes.push({
- markerId: markerId,
- filePath: filePath
+ markerId,
+ filePath
})
- handledCount++;
- checkMarkerAdded();
+ handledCount++
+ checkMarkerAdded()
},
fail: res => {
console.error(res)
- console.log('文件保存失败', filePath);
- handledCount++;
- checkMarkerAdded();
+ console.log('文件保存失败', filePath)
+ handledCount++
+ checkMarkerAdded()
}
})
}
- console.log('uploadFile Path', filePath);
+ console.log('uploadFile Path', filePath)
// 确定文件,存在即删除
fs.stat({
path: filePath,
success: (res) => {
if (res.stats.isFile()) {
- fs.unlinkSync(filePath);
- console.log('fs unlinkSync', filePath);
+ fs.unlinkSync(filePath)
+ console.log('fs unlinkSync', filePath)
}
- saveAndAddMarker();
+ saveAndAddMarker()
},
fail: (res) => {
console.error(res)
- console.log('fs中不存在,直接写入', filePath);
+ console.log('fs中不存在,直接写入', filePath)
- saveAndAddMarker();
+ saveAndAddMarker()
}
})
}
-
},
removeMarker() {
if (this.data.markerImgList) {
for (let i = 0; i < this.data.markerImgList.length; i++) {
- const markerImg = this.data.markerImgList[i];
- this.session.removeMarker(markerImg.markerId);
+ const markerImg = this.data.markerImgList[i]
+ this.session.removeMarker(markerImg.markerId)
}
- this.markerIndex = 0;
+ this.markerIndex = 0
this.setData({
markerImgList: [],
})
@@ -370,4 +367,4 @@ Component({
console.log(this.session.getAllMarker())
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/3dmarker-ar.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/3dmarker-ar.js
index 3826bbf8..e38bbf35 100644
--- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/3dmarker-ar.js
+++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/3dmarker-ar.js
@@ -1,70 +1,70 @@
import arBehavior from '../behavior/behavior-ar'
import xrFrameBehavior from '../behavior/behavior-xrframe'
-
// protobuf 相关逻辑
-let protobuf = require("./protobuf/protobuf.js");
-let json = require("./proto/arModelProto.js");
-let root = protobuf.Root.fromJSON(json)
-let message = root.lookupType("ARModelData");
+const protobuf = require('./protobuf/protobuf.js')
+const json = require('./proto/arModelProto.js')
+
+const root = protobuf.Root.fromJSON(json)
+const message = root.lookupType('ARModelData')
-let gltfIndex = 0;
+let gltfIndex = 0
// VK 投影矩阵参数定义
const NEAR = 0.01
const FAR = 1000
// 针对 vk 生成模型的矫正
-const modelScale = 0.16;
+const modelScale = 0.16
Component({
behaviors: [arBehavior, xrFrameBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.6, // canvas高度缩放值
- hintBoxList: [], // 显示提示盒子列表
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.6, // canvas高度缩放值
+ hintBoxList: [], // 显示提示盒子列表
usingMarkerId: false, // 使用中的markerId
haveMap: false, // 存在map
haveGLTF: false, // 存在gltf
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
selectCosid: 0, // 选中的cosid
- selectResp: undefined, // 选中的回调信息
+ selectResp: undefined, // 选中的回调信息
parsedMapUrl: undefined, // 使用中的mapUrl
- parsedGlbUrl: undefined,// 使用中的glbUrl
+ parsedGlbUrl: undefined, // 使用中的glbUrl
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
// 对应案例的初始化逻辑,由统一的 behavior 触发
init() {
- this.markerIndex = 0;
+ this.markerIndex = 0
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -77,7 +77,7 @@ Component({
},
version: 'v1',
gl: this.gl
- });
+ })
session.start(err => {
if (err) return console.error('VK error: ', err)
@@ -86,212 +86,208 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
- console.log("addAnchor", anchors);
+ console.log('addAnchor', anchors)
})
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// marker 模式下,目前仅有一个识别目标,可以直接取
- const anchor = anchors[0];
- const markerId = anchor.id;
- const size = anchor.size;
+ const anchor = anchors[0]
+ const markerId = anchor.id
+ const size = anchor.size
this.hintInfo = {
- markerId: markerId,
- size: size
+ markerId,
+ size
}
console.log('update a')
if (!this.modelShow) {
if (this.modelTrs) {
- this.modelTrs.scale.x = modelScale;
- this.modelTrs.scale.y = modelScale;
- this.modelTrs.scale.z = modelScale;
+ this.modelTrs.scale.x = modelScale
+ this.modelTrs.scale.y = modelScale
+ this.modelTrs.scale.z = modelScale
}
- this.xAxis.visible = true;
- this.yAxis.visible = true;
- this.zAxis.visible = true;
+ this.xAxis.visible = true
+ this.yAxis.visible = true
+ this.zAxis.visible = true
- this.modelShow = true;
+ this.modelShow = true
}
})
-
+
// VKSession removeAnchors
// 识别目标丢失时,会触发一次
session.on('removeAnchors', anchors => {
console.log('remove a')
if (this.modelShow) {
-
if (this.modelTrs) {
- this.modelTrs.scale.x = 0;
- this.modelTrs.scale.y = 0;
- this.modelTrs.scale.z = 0;
+ this.modelTrs.scale.x = 0
+ this.modelTrs.scale.y = 0
+ this.modelTrs.scale.z = 0
}
- this.xAxis.visible = false;
- this.yAxis.visible = false;
- this.zAxis.visible = false;
+ this.xAxis.visible = false
+ this.yAxis.visible = false
+ this.zAxis.visible = false
- this.modelShow = false;
+ this.modelShow = false
}
- });
-
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
+ this.initLoop()
+ })
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
-
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// 添加marker 提示用的 三个轴
- const geometryCube = scene.assets.getAsset('geometry', 'cube');
- const effectCube = scene.assets.getAsset('effect', 'standard');
- const axisScale = 1.0;
- const lineScale = 0.05;
+ const geometryCube = scene.assets.getAsset('geometry', 'cube')
+ const effectCube = scene.assets.getAsset('effect', 'standard')
+ const axisScale = 1.0
+ const lineScale = 0.05
const elX = scene.createElement(xrFrameSystem.XRNode, {
position: `${axisScale / 2} 0 0`,
scale: `${axisScale} ${lineScale} ${lineScale}`,
- });
- const elXTrs = elX.getComponent(xrFrameSystem.Transform);
- const matX = scene.createMaterial(effectCube);
- matX.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 0.2, 0.2, 1.0));
+ })
+ const elXTrs = elX.getComponent(xrFrameSystem.Transform)
+ const matX = scene.createMaterial(effectCube)
+ matX.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 0.2, 0.2, 1.0))
const meshX = elX.addComponent(xrFrameSystem.Mesh, {
geometry: geometryCube,
material: matX,
- });
- this.xAxis = elXTrs;
- rootShadow.addChild(elX);
- this.xAxis.visible = false;
+ })
+ this.xAxis = elXTrs
+ rootShadow.addChild(elX)
+ this.xAxis.visible = false
const elY = scene.createElement(xrFrameSystem.XRNode, {
position: `0 ${axisScale / 2} 0`,
scale: `${lineScale} ${axisScale} ${lineScale}`,
- });
- const elYTrs = elY.getComponent(xrFrameSystem.Transform);
- const matY = scene.createMaterial(effectCube);
- matY.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(0.2, 1, 0.2, 1.0));
+ })
+ const elYTrs = elY.getComponent(xrFrameSystem.Transform)
+ const matY = scene.createMaterial(effectCube)
+ matY.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(0.2, 1, 0.2, 1.0))
const meshY = elY.addComponent(xrFrameSystem.Mesh, {
geometry: geometryCube,
material: matY,
- });
- this.yAxis = elYTrs;
- rootShadow.addChild(elY);
- this.yAxis.visible = false;
+ })
+ this.yAxis = elYTrs
+ rootShadow.addChild(elY)
+ this.yAxis.visible = false
const elZ = scene.createElement(xrFrameSystem.XRNode, {
position: `0 0 ${axisScale / 2}`,
scale: `${lineScale} ${lineScale} ${axisScale}`,
- });
- const elZTrs = elZ.getComponent(xrFrameSystem.Transform);
- const matZ = scene.createMaterial(effectCube);
- matZ.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(0.2, 0.2, 1, 1.0));
+ })
+ const elZTrs = elZ.getComponent(xrFrameSystem.Transform)
+ const matZ = scene.createMaterial(effectCube)
+ matZ.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(0.2, 0.2, 1, 1.0))
const meshZ = elZ.addComponent(xrFrameSystem.Mesh, {
geometry: geometryCube,
material: matZ,
- });
- this.zAxis = elZTrs;
- rootShadow.addChild(elZ);
- this.zAxis.visible = false;
+ })
+ this.zAxis = elZTrs
+ rootShadow.addChild(elZ)
+ this.zAxis.visible = false
console.log('add3DAxis is finish')
-
},
loop() {
// 获取 VKFrame
const frame = this.session.getVKFrame(this.data.domWidth, this.data.domHeight)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
},
async parseAddMarker() {
// 目前未选中cosid 跳过
if (!this.selectCosid) {
- console.log("目前未选中cosid,请选中后重试");
- return;
+ console.log('目前未选中cosid,请选中后重试')
+ return
}
// 存在marker的情况下,无法继续添加marker
if (this.data.usingMarkerId) {
- console.log("已添加 marker,请删除后重试");
- return;
+ console.log('已添加 marker,请删除后重试')
+ return
}
- if (!!this.parseAddMarkerLoading) {
- console.log("加载中,请稍后重试");
- return;
+ if (this.parseAddMarkerLoading) {
+ console.log('加载中,请稍后重试')
+ return
}
- const resp = this.selectResp;
- console.log("开始添加 marker");
- console.log("获取的模型的cosID为", this.selectCosid);
- console.log(this.selectResp);
- var filePath = wx.env.USER_DATA_PATH + '/temp'
- console.log('请求地址');
+ const resp = this.selectResp
+ console.log('开始添加 marker')
+ console.log('获取的模型的cosID为', this.selectCosid)
+ console.log(this.selectResp)
+ const filePath = wx.env.USER_DATA_PATH + '/temp'
+ console.log('请求地址')
console.log(resp.result.respBody.url)
// 简单的加载锁
- this.parseAddMarkerLoading = true;
+ this.parseAddMarkerLoading = true
// 开始下载文件
wx.downloadFile({
- filePath: filePath,
+ filePath,
url: resp.result.respBody.url,
success: (res) => {
- console.log("下载回调", res);
+ console.log('下载回调', res)
const fs = wx.getFileSystemManager()
fs.readFile({
filePath: res.filePath,
position: 0,
success: async (res) => {
- console.log("读文件回调,结果返回为", res)
- wx.hideLoading();
+ console.log('读文件回调,结果返回为', res)
+ wx.hideLoading()
// 开始解析具体信息 protobuf
- try{
+ try {
console.log('开始解析回调')
- var data = message.decode(res.data);
- console.log("反序列化完成");
- console.log(data);
- } catch(e){
- wx.hideLoading();
- console.log("模型数据解析有误")
+ var data = message.decode(res.data)
+ console.log('反序列化完成')
+ console.log(data)
+ } catch (e) {
+ wx.hideLoading()
+ console.log('模型数据解析有误')
console.log(e)
- if(e instanceof protobuf.util.ProtocolError){
+ if (e instanceof protobuf.util.ProtocolError) {
// missing required field
console.log('missing required field')
- }else{
+ } else {
// wire format is invalid
console.log('wire format is invalid')
}
- throw e;
+ throw e
}
- let mapSuccess = true;
- let gltfSuccess = true;
-
+ let mapSuccess = true
+ let gltfSuccess = true
+
// map文件
- if (data.meshModel && data.meshModel.byteLength !== 0) {
+ if (data.meshModel && data.meshModel.byteLength !== 0) {
// map文件成功
this.setData({
haveMap: true,
@@ -302,23 +298,22 @@ Component({
const byteOffset = data.meshModel.byteOffset
const byteLength = data.meshModel.byteLength
const mapContent = data.meshModel.buffer.slice(byteOffset, byteOffset + byteLength)
- console.log("byteOffset:", byteOffset)
- console.log("byteLength:", byteLength)
-
+ console.log('byteOffset:', byteOffset)
+ console.log('byteLength:', byteLength)
// 写入文件后的地址
- const mapUrl = this.saveLocalFile(mapContent, 'model.map');
- console.log("map文件的本地路径", mapUrl)
- this.parsedMapUrl = mapUrl;
+ const mapUrl = this.saveLocalFile(mapContent, 'model.map')
+ console.log('map文件的本地路径', mapUrl)
+ this.parsedMapUrl = mapUrl
// 添加marker
- const markerId = this.session.addMarker(mapUrl);
+ const markerId = this.session.addMarker(mapUrl)
console.log('add Marker', markerId, mapUrl)
this.setData({
usingMarkerId: markerId
- });
+ })
} else {
- mapSuccess = false;
+ mapSuccess = false
}
// glb文件
@@ -327,38 +322,38 @@ Component({
const glbByteOffset = data.meshBlob.byteOffset
const glbByteLength = data.meshBlob.byteLength
const glbContent = data.meshBlob.buffer.slice(glbByteOffset, glbByteOffset + glbByteLength)
- console.log('glbContent', glbContent);
- const glbUrl = this.saveLocalFile(glbContent, 'result.glb');
- console.log("glb文件的本地路径", glbUrl)
- this.parsedGlbUrl = glbUrl;
+ console.log('glbContent', glbContent)
+ const glbUrl = this.saveLocalFile(glbContent, 'result.glb')
+ console.log('glb文件的本地路径', glbUrl)
+ this.parsedGlbUrl = glbUrl
// @optional
- // 后续为添加渲染产物模型的逻辑
+ // 后续为添加渲染产物模型的逻辑
// xrFrame 加载模型相关
// 加载生成模型
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
// gltf索引更新
- gltfIndex++;
+ gltfIndex++
const resultModel = await scene.assets.loadAsset({
type: 'gltf',
assetId: `gltf-result-${gltfIndex}`,
src: `${wx.env.USER_DATA_PATH}/result.glb`,
})
- console.log('resultModel', resultModel.value);
+ console.log('resultModel', resultModel.value)
const el = scene.createElement(xrFrameSystem.XRGLTF, {
model: `gltf-result-${gltfIndex}`,
position: `0 -${modelScale} -${modelScale}`,
rotation: '90 0 0',
- scale: `0 0 0`, // 默认先不显示
- });
- this.model = el;
- this.modelTrs = el.getComponent(xrFrameSystem.Transform);
- this.modelShow = false;
- this.xrScene.rootShadow.addChild(el);
+ scale: '0 0 0', // 默认先不显示
+ })
+ this.model = el
+ this.modelTrs = el.getComponent(xrFrameSystem.Transform)
+ this.modelShow = false
+ this.xrScene.rootShadow.addChild(el)
// Three 场景相关
// const THREE = this.THREE;
@@ -384,9 +379,9 @@ Component({
// this.modelWrap.add(this.model);
// });
} else {
- gltfSuccess = false;
+ gltfSuccess = false
}
-
+
// 更新产物状态
this.setData({
haveMap: mapSuccess,
@@ -395,8 +390,8 @@ Component({
if (!mapSuccess || !gltfSuccess) {
// 文件生成失败提示
- let mapWord = !mapSuccess ? 'map文件' : '';
- let gltfWord = !gltfSuccess ? 'glTF文件' : '';
+ const mapWord = !mapSuccess ? 'map文件' : ''
+ const gltfWord = !gltfSuccess ? 'glTF文件' : ''
wx.showToast({
title: `${mapWord} ${gltfWord} 生成失败`,
@@ -405,35 +400,34 @@ Component({
})
}
- this.parseAddMarkerLoading = false;
+ this.parseAddMarkerLoading = false
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
duration: 2000
})
- this.parseAddMarkerLoading = false;
+ this.parseAddMarkerLoading = false
}
})
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
duration: 2000
})
console.error(res)
- this.parseAddMarkerLoading = false;
+ this.parseAddMarkerLoading = false
}
})
-
},
saveLocalFile(bufferContent, name) {
- var url = `${wx.env.USER_DATA_PATH}/${name}`
+ const url = `${wx.env.USER_DATA_PATH}/${name}`
const fs = wx.getFileSystemManager()
try {
@@ -443,8 +437,8 @@ Component({
'utf8'
)
console.log(res)
- } catch(e) {
- console.error(e);
+ } catch (e) {
+ console.error(e)
}
return url
@@ -457,78 +451,77 @@ Component({
})
// 释放xrframe资源
if (this.model) {
- const scene = this.xrScene;
- scene.assets.releaseAsset('gltf',`gltf-result-${gltfIndex}`);
- scene.rootShadow.removeChild(this.model);
- this.model = undefined;
+ const scene = this.xrScene
+ scene.assets.releaseAsset('gltf', `gltf-result-${gltfIndex}`)
+ scene.rootShadow.removeChild(this.model)
+ this.model = undefined
}
},
getAllMarker() {
console.log(this.session.getAllMarker())
},
changeSelect(e) {
- console.log('触发选择更改');
- console.log(e.detail);
+ console.log('触发选择更改')
+ console.log(e.detail)
- this.selectCosid = e.detail.cosid;
- this.selectResp = e.detail.modelResp;
+ this.selectCosid = e.detail.cosid
+ this.selectResp = e.detail.modelResp
},
- saveMap(){
+ saveMap() {
if (!this.parsedMapUrl) {
console.log('不存在使用中的map地址')
- return;
+ return
}
wx.shareFileMessage({
filePath: this.parsedMapUrl,
- });
+ })
},
saveGlTF() {
if (!this.parsedGlbUrl) {
console.log('不存在使用中的glb地址')
- return;
+ return
}
wx.shareFileMessage({
filePath: this.parsedGlbUrl,
- });
+ })
},
useDefaultMarker() {
// 简单的加载锁
- if (!!this.parseAddMarkerLoading) {
- console.log("加载中,请稍后重试");
- return;
+ if (this.parseAddMarkerLoading) {
+ console.log('加载中,请稍后重试')
+ return
}
- this.parseAddMarkerLoading = true;
-
+ this.parseAddMarkerLoading = true
// 开始下载文件
- const filePath = wx.env.USER_DATA_PATH + '/default.map';
+ const filePath = wx.env.USER_DATA_PATH + '/default.map'
wx.downloadFile({
- filePath: filePath,
+ filePath,
url: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/default.map',
success: (res) => {
- console.log("下载回调", res);
+ console.log('下载回调', res)
// 添加marker
- const markerId = this.session.addMarker(res.filePath);
+ const markerId = this.session.addMarker(res.filePath)
console.log('add Default Marker', markerId)
- this.modelShow = false;
+ this.modelShow = false
this.setData({
usingMarkerId: markerId
- });
+ })
- this.parseAddMarkerLoading = false;
+ this.parseAddMarkerLoading = false
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
duration: 2000
})
console.error(res)
- this.parseAddMarkerLoading = false;
+ this.parseAddMarkerLoading = false
}
})
}
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js
index 1a90c417..25e4e29d 100644
--- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js
+++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js
@@ -1,7 +1,7 @@
Component({
behaviors: ['wx://component-export'],
- export(){
- return {getARModelList: this.getARModelList.bind(this)}
+ export() {
+ return { getARModelList: this.getARModelList.bind(this) }
},
data: {
chooseMapFile: null,
@@ -16,28 +16,28 @@ Component({
},
modelRespMap: {},
lifetimes: {
- ready: function () {
+ ready() {
if (!wx.cloud) {
- console.error('请使用 2.2.3 或以上的基础库以使用云能力');
+ console.error('请使用 2.2.3 或以上的基础库以使用云能力')
} else {
wx.cloud.init({
traceUser: true,
- });
- console.log("初始化云函数成功")
+ })
+ console.log('初始化云函数成功')
}
// 缓存resp map
- this.modelRespMap = {};
+ this.modelRespMap = {}
- const keyNumber = (new Date()).getTime() * 10 + Math.floor(Math.random() * 10);
+ const keyNumber = (new Date()).getTime() * 10 + Math.floor(Math.random() * 10)
this.setData({
modelName: 'arDemo' + keyNumber
})
- console.log('当前上传模型名称为 ' + 'arDemo' + keyNumber);
+ console.log('当前上传模型名称为 ' + 'arDemo' + keyNumber)
// 获取已有数据
- this.getARModelList();
+ this.getARModelList()
}
},
@@ -46,18 +46,18 @@ Component({
uploadARModel() {
const callback = this.generateARModel.bind(this)
const cloudUpload = this.cloudUploadARModel.bind(this)
- const timeNow = Date.now() / 1000 | 0;
- const modelInfos = wx.getStorageSync('modelsInfo');
- console.log("modelInfos的值为:")
+ const timeNow = Date.now() / 1000 | 0
+ const modelInfos = wx.getStorageSync('modelsInfo')
+ console.log('modelInfos的值为:')
console.log(modelInfos)
- if(modelInfos && modelInfos.length != 0){
- if(timeNow - modelInfos[0].timeStamp < 100){
+ if (modelInfos && modelInfos.length != 0) {
+ if (timeNow - modelInfos[0].timeStamp < 100) {
wx.showToast({
- title: "每15分钟允许上传一次视频",
+ title: '每15分钟允许上传一次视频',
icon: 'none',
duration: 2000
})
- return;
+ return
}
}
// 上传视频
@@ -69,23 +69,23 @@ Component({
maxDuration: 60,
camera: 'back',
success: (res) => {
- console.log("录制成功,结果为")
+ console.log('录制成功,结果为')
console.log(res)
const tempFileInfo = res.tempFiles[0]
// 保证视频时长在 10-30秒 之间
if (tempFileInfo.duration >= 10 && tempFileInfo.duration <= 30) {
- const rate = tempFileInfo.width / tempFileInfo.height;
+ const rate = tempFileInfo.width / tempFileInfo.height
- let min = tempFileInfo.width;
- let max = tempFileInfo.height;
+ let min = tempFileInfo.width
+ let max = tempFileInfo.height
if (rate > 1) {
- min = tempFileInfo.height;
- max = tempFileInfo.width;
+ min = tempFileInfo.height
+ max = tempFileInfo.width
}
// 保证长边在 720 以上
if (max > 720) {
// 不接受比例在 3:1 以上的视频
- if(rate < 1 / 3 || rate > 3){
+ if (rate < 1 / 3 || rate > 3) {
wx.showModal({
content: '长宽比尽量为16:9或4:3,不接受比例大于3:1的视频',
confirmText: '继续上传',
@@ -97,10 +97,10 @@ Component({
}
}
})
- }else{
+ } else {
cloudUpload(res, callback)
}
- }else{
+ } else {
wx.showModal({
content: '建议长边在720以上',
confirmText: '继续上传',
@@ -113,7 +113,7 @@ Component({
}
})
}
- }else{
+ } else {
wx.showToast({
title: '请录制10~30秒内的视频',
icon: 'none',
@@ -125,21 +125,21 @@ Component({
},
// 生成具体模型
generateARModel(url) {
- console.log("当前地址为:", url)
+ console.log('当前地址为:', url)
wx.showLoading({
title: '生成模型中……',
- });
+ })
- const reqData = {
+ const reqData = {
type: 'GenerateARModel',
name: this.data.modelName,
- url: url,
+ url,
algoType: 2,
getMesh: true,
getTexture: true
}
- console.log("调用参数为:",reqData)
+ console.log('调用参数为:', reqData)
wx.cloud.callFunction({
name: 'ARDemo',
@@ -148,35 +148,35 @@ Component({
},
data: reqData
}).then((resp) => {
- console.log("生成模型成功")
+ console.log('生成模型成功')
console.log(resp)
wx.showToast({
- title: "生成模型成功",
+ title: '生成模型成功',
icon: 'none',
duration: 2000
})
- wx.hideLoading();
+ wx.hideLoading()
let modelInfos = wx.getStorageSync('modelsInfo')
- if (modelInfos == undefined || modelInfos.length == 0 ) {
+ if (modelInfos == undefined || modelInfos.length == 0) {
modelInfos = []
}
console.log('原有的缓存列表', modelInfos)
- const returnCosid = resp.result.respBody.cosid;
+ const returnCosid = resp.result.respBody.cosid
// 5分钟内上传相同文件,会返回相同的cosid,需要过滤掉
- let matched = false;
- for( let j = modelInfos.length - 1; j >= 0; j-- ) {
+ let matched = false
+ for (let j = modelInfos.length - 1; j >= 0; j--) {
if (modelInfos[j].cosid === returnCosid) {
- matched = true;
- break;
+ matched = true
+ break
}
}
if (!matched) {
- console.log("缓存对cosid进行push")
- console.log("当前生成模型的cosid为:", returnCosid)
+ console.log('缓存对cosid进行push')
+ console.log('当前生成模型的cosid为:', returnCosid)
console.log()
modelInfos.push({
@@ -185,95 +185,94 @@ Component({
timeStamp: Date.now() / 1000 | 0,
modelStatus: 0,
restTime: 0,
- statusMsg: "准备中"
+ statusMsg: '准备中'
})
}
-
+
modelInfos.sort(function (a, b) {
- if(a.uploadTime > b.uploadTime){
- return -1;
- }else if(a.uploadTime < b.uploadTime){
- return 1;
+ if (a.uploadTime > b.uploadTime) {
+ return -1
+ } else if (a.uploadTime < b.uploadTime) {
+ return 1
}
- return 0;
- })
+ return 0
+ })
wx.setStorage({
- key: "modelsInfo",
+ key: 'modelsInfo',
data: modelInfos,
success() {
- console.log("存储cosID集合为:", modelInfos)
+ console.log('存储cosID集合为:', modelInfos)
}
})
this.setData({
models: modelInfos
- });
-
+ })
}).catch((e) => {
console.log(e)
wx.showToast({
title: e.errMsg,
icon: 'none',
duration: 2000
- })
+ })
this.setData({
showUploadTip: true
- });
- wx.hideLoading();
- });
+ })
+ wx.hideLoading()
+ })
},
// 获取现有模型列表
getARModelList() {
// 获取本地缓存
- var modelInfos = wx.getStorageSync('modelsInfo')
- if (modelInfos == undefined || modelInfos.length == 0 ) {
+ const modelInfos = wx.getStorageSync('modelsInfo')
+ if (modelInfos == undefined || modelInfos.length == 0) {
// 无缓存,跳过
- return;
+ return
}
- const countModelInfo = modelInfos.length;
- let countLoaded = 0;
+ const countModelInfo = modelInfos.length
+ let countLoaded = 0
- const modelInfosNew = [];
+ const modelInfosNew = []
// 统一的获取处理回调
const handleLoadModelInfo = () => {
if (countLoaded === countModelInfo) {
// 加载完毕
console.log('基于本地缓存请求列表结束', modelInfosNew)
-
+
// 新列表,基于创建时间排序
modelInfosNew.sort(function (a, b) {
- if(a.uploadTime > b.uploadTime){
- return -1;
- }else if(a.uploadTime < b.uploadTime){
- return 1;
+ if (a.uploadTime > b.uploadTime) {
+ return -1
+ } else if (a.uploadTime < b.uploadTime) {
+ return 1
}
- return 0;
+ return 0
})
-
+
// 写入缓存
wx.setStorage({
- key: "modelsInfo",
+ key: 'modelsInfo',
data: modelInfosNew,
success() {
- console.log("存储cosID集合为:", modelInfosNew)
+ console.log('存储cosID集合为:', modelInfosNew)
wx.hideLoading()
}
})
-
+
// 更新显示列表
this.setData({
models: modelInfosNew,
- });
+ })
}
}
// 基于缓存列表请求
for (let i = 0; i < countModelInfo; i++) {
- const modelInfo = modelInfos[i];
- const cosid = modelInfo.cosid
+ const modelInfo = modelInfos[i]
+ const cosid = modelInfo.cosid
wx.cloud.callFunction({
name: 'ARDemo',
config: {
@@ -281,79 +280,75 @@ Component({
},
data: {
type: 'GetARModel',
- cosid: cosid,
+ cosid,
modelType: 3,
needData: 0,
useIntranet: 0,
expireTime: 1200
}
}).then(resp => {
- countLoaded++;
+ countLoaded++
- const modelStatus = resp.result.respBody.status;
+ const modelStatus = resp.result.respBody.status
- console.log("获取的模型的cosID为", cosid)
+ console.log('获取的模型的cosID为', cosid)
console.log(resp)
- console.log('status', modelStatus);
+ console.log('status', modelStatus)
// 根据返回信息,更新模型信息
const modelInfoNew = {
- cosid: cosid,
+ cosid,
uploadTime: modelInfo.uploadTime,
timeStamp: modelInfo.timeStamp,
- modelStatus: modelStatus, // 0 生成中 1 生成成功 2 过期 3 生成失败
+ modelStatus, // 0 生成中 1 生成成功 2 过期 3 生成失败
restTime: 0,
statusMsg: '准备中',
- };
+ }
// 回调写入缓存map,方便读取
- this.modelRespMap[cosid] = resp;
+ this.modelRespMap[cosid] = resp
// 根据状态设置描述
if (modelStatus === 1) {
// 生成成功
- modelInfoNew.statusMsg = '已完成';
+ modelInfoNew.statusMsg = '已完成'
// 运算过期时间
- const expireTime = resp.result.respBody.expireTime;
- const nowTime = Date.now() / 1000 | 0;
- const restTime = Math.floor((expireTime - nowTime) / 60 / 60 / 24);
- modelInfoNew.restTime = restTime;
+ const expireTime = resp.result.respBody.expireTime
+ const nowTime = Date.now() / 1000 | 0
+ const restTime = Math.floor((expireTime - nowTime) / 60 / 60 / 24)
+ modelInfoNew.restTime = restTime
} else if (modelStatus === 2) {
// 资源过期
- modelInfoNew.statusMsg = '资源过期';
-
+ modelInfoNew.statusMsg = '资源过期'
} else if (modelStatus === 3) {
// 生成失败
- const errMsg = resp.result.respBody.errMsg;
- console.log('errMsg', errMsg);
+ const errMsg = resp.result.respBody.errMsg
+ console.log('errMsg', errMsg)
- modelInfoNew.statusMsg = '生成失败';
+ modelInfoNew.statusMsg = '生成失败'
if (errMsg) {
- modelInfoNew.errMsg = errMsg;
+ modelInfoNew.errMsg = errMsg
}
}
+ modelInfosNew.push(modelInfoNew)
- modelInfosNew.push(modelInfoNew);
-
- handleLoadModelInfo();
+ handleLoadModelInfo()
}).catch((e) => {
- countLoaded++;
+ countLoaded++
console.log(e)
-
- });
+ })
}
-
},
- cloudUploadARModel(res, callback){
+ cloudUploadARModel(res, callback) {
wx.showLoading({
title: '文件上传中……',
- });
+ })
+
+ const second = (new Date()).getSeconds()
- const second = (new Date()).getSeconds();
-
// 组成规则 第一位随机数(1 / 2)第二位是秒的个位
- const id = Math.ceil(Math.random() * 2) * 10 + second % 10;
+ const id = Math.ceil(Math.random() * 2) * 10 + second % 10
wx.cloud.uploadFile({
cloudPath: `3dmarker/arVideo${id}.mp4`,
@@ -365,9 +360,9 @@ Component({
success(res) {
wx.hideLoading()
const data = res.data
- console.log("上传文件success:", res)
+ console.log('上传文件success:', res)
wx.showToast({
- title: "上传文件成功",
+ title: '上传文件成功',
icon: 'none',
duration: 2000
})
@@ -375,10 +370,10 @@ Component({
fileList: [res.fileID],
success: res => {
callback(res.fileList[0].tempFileURL)
- console.log("生成模型中……")
+ console.log('生成模型中……')
},
fail: err => {
- console.log("发生错误:", err)
+ console.log('发生错误:', err)
wx.showToast({
title: err.errMsg,
icon: 'none',
@@ -389,7 +384,7 @@ Component({
},
fail: err => {
wx.hideLoading()
- console.log("上传文件error:", err)
+ console.log('上传文件error:', err)
wx.showToast({
title: err.errMsg,
icon: 'none',
@@ -400,45 +395,43 @@ Component({
},
// 工具函数 转换时间戳
convertToTime(timestamp) {
- var now = new Date(timestamp * 1000)
- var y = now.getFullYear()
- var m = now.getMonth() + 1
- var d = now.getDate()
- var x = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " \n" + now.toTimeString().substr(0, 8);
+ const now = new Date(timestamp * 1000)
+ const y = now.getFullYear()
+ const m = now.getMonth() + 1
+ const d = now.getDate()
+ const x = y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d) + ' \n' + now.toTimeString().substr(0, 8)
return x
},
// 选择模型
chooseARModel(event) {
// 被选中cosid
- const selectCosid = event.currentTarget.dataset.cosid;
+ const selectCosid = event.currentTarget.dataset.cosid
// 已选中cosid
- const targetCosId = this.data.targetCosId;
+ const targetCosId = this.data.targetCosId
// 不同的情况下,更新选中目标
if (selectCosid !== targetCosId) {
+ const modelResp = this.modelRespMap[selectCosid]
- const modelResp = this.modelRespMap[selectCosid];
-
- const modelStatus = modelResp.result.respBody.status;
+ const modelStatus = modelResp.result.respBody.status
// 成功才允许点击
if (modelStatus === 1) {
this.setData({
targetCosId: selectCosid
- });
-
+ })
+
// 选择的时候,通知上层
this.triggerEvent('selectEvent', {
- cosid: selectCosid,
- modelResp: modelResp,
- }
- );
+ cosid: selectCosid,
+ modelResp,
+ })
}
}
},
// 删除模型本地缓存
deleteARModel(event) {
// 被选中cosid
- const selectCosid = event.currentTarget.dataset.cosid;
+ const selectCosid = event.currentTarget.dataset.cosid
wx.showModal({
content: `是否删除当前缓存模型(删除后不可恢复),模型id ${selectCosid}`,
@@ -446,39 +439,38 @@ Component({
cancelText: '取消',
success: (res) => {
if (res.confirm) {
- console.log('确定删除');
+ console.log('确定删除')
// 获取本地缓存
- var modelInfos = wx.getStorageSync('modelsInfo')
- if (modelInfos == undefined || modelInfos.length == 0 ) {
+ const modelInfos = wx.getStorageSync('modelsInfo')
+ if (modelInfos == undefined || modelInfos.length == 0) {
// 无缓存,跳过
- return;
+ return
}
// 新列表,过滤掉删除的cosid
- const modelInfosNew = modelInfos.filter(
+ const modelInfosNew = modelInfos.filter(
(modelInfo) => modelInfo.cosid !== selectCosid
- );
-
+ )
+
// 写入缓存
wx.setStorage({
- key: "modelsInfo",
+ key: 'modelsInfo',
data: modelInfosNew,
success() {
- console.log("存储cosID集合为:", modelInfosNew)
+ console.log('存储cosID集合为:', modelInfosNew)
wx.hideLoading()
}
})
-
+
// 更新显示列表
this.setData({
models: modelInfosNew,
- });
+ })
} else if (res.cancel) {
console.log('取消')
}
}
})
-
},
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/proto/arModelProto.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/proto/arModelProto.js
index 62649773..081ac742 100644
--- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/proto/arModelProto.js
+++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/proto/arModelProto.js
@@ -1,28 +1,28 @@
module.exports = {
- "nested": {
- "ARModelData": {
- "fields": {
- "meshModel": {
- "type": "bytes",
- "id": 1
- },
- "textureModel": {
- "type": "bytes",
- "id": 2
- },
- "preview": {
- "type": "bytes",
- "id": 3
- },
- "meshBlob": {
- "type": "bytes",
- "id": 4
- },
- "textureBlob": {
- "type": "bytes",
- "id": 5
- }
+ nested: {
+ ARModelData: {
+ fields: {
+ meshModel: {
+ type: 'bytes',
+ id: 1
+ },
+ textureModel: {
+ type: 'bytes',
+ id: 2
+ },
+ preview: {
+ type: 'bytes',
+ id: 3
+ },
+ meshBlob: {
+ type: 'bytes',
+ id: 4
+ },
+ textureBlob: {
+ type: 'bytes',
+ id: 5
}
}
}
- }
\ No newline at end of file
+ }
+}
diff --git a/miniprogram/packageAPI/pages/ar/behavior/behavior-ar.js b/miniprogram/packageAPI/pages/ar/behavior/behavior-ar.js
index 6f4a89aa..c6b3453d 100644
--- a/miniprogram/packageAPI/pages/ar/behavior/behavior-ar.js
+++ b/miniprogram/packageAPI/pages/ar/behavior/behavior-ar.js
@@ -1,102 +1,102 @@
module.exports = Behavior({
- // 全局变量
- session: undefined, // 全局的VKsession对象
- canvas: undefined, // canvas
- // XRFrame相关变量
- xrScene: undefined, // xr-frame 的场景
- xrCamera: undefined, // xr-frame 的相机
- xrFrameReady: undefined, // xr-frame初始化完毕
- // WebGL相关
- camera: undefined, // 主要相机
- // ThreeJs 相关变量
- gl: undefined, // 全局gl对象
- THREE: undefined, // THREE 对象
- // 全局 data
- data: {
- domWidth: 0,
- domHeight: 0,
- width: 0, // canvas大小
- height: 0, // canvas大小
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.8, // canvas高度缩放值
- cameraPosition: 0, // 相机朝向,默认后置摄像头
- },
- methods: {
- onReady() {
- // 获取canvas
- wx.createSelectorQuery()
- .select('#canvas')
- .node()
- .exec(res => {
- this.canvas = res[0].node
+ // 全局变量
+ session: undefined, // 全局的VKsession对象
+ canvas: undefined, // canvas
+ // XRFrame相关变量
+ xrScene: undefined, // xr-frame 的场景
+ xrCamera: undefined, // xr-frame 的相机
+ xrFrameReady: undefined, // xr-frame初始化完毕
+ // WebGL相关
+ camera: undefined, // 主要相机
+ // ThreeJs 相关变量
+ gl: undefined, // 全局gl对象
+ THREE: undefined, // THREE 对象
+ // 全局 data
+ data: {
+ domWidth: 0,
+ domHeight: 0,
+ width: 0, // canvas大小
+ height: 0, // canvas大小
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.8, // canvas高度缩放值
+ cameraPosition: 0, // 相机朝向,默认后置摄像头
+ },
+ methods: {
+ onReady() {
+ // 获取canvas
+ wx.createSelectorQuery()
+ .select('#canvas')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
- // 运算画布大小
- this.calcCanvasSize()
+ // 运算画布大小
+ this.calcCanvasSize()
- // 页面自定义初始化
- if (this.init) this.init()
- })
- },
- calcCanvasSize () {
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio;
- const width = info.windowWidth * this.data.widthScale * pixelRatio;
- const height = info.windowHeight * this.data.heightScale * pixelRatio;
- // 存在 webgl Canvas的情况下,写入大小
- if (this.canvas) {
- this.canvas.width = width;
- this.canvas.height = height;
- }
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.setData({
- width: width,
- height: height,
- domWidth: info.windowWidth * this.data.widthScale,
- domHeight: info.windowHeight * this.data.heightScale,
- });
- },
- // 前后摄像头
- switchCamera(){
- if(this.session.config){
- const config = this.session.config
- let cameraPosNext;
- if (this.data.cameraPosition === 0) {
- cameraPosNext = 1;
- } else {
- cameraPosNext = 0;
- }
- config.cameraPosition = cameraPosNext
- this.session.config = config
- this.setData({
- cameraPosition: cameraPosNext
- })
- }
- },
- // 限帧逻辑
- initLoop() {
- // 限制调用帧率,暂时去掉
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
+ // 页面自定义初始化
+ if (this.init) this.init()
+ })
+ },
+ calcCanvasSize() {
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const width = info.windowWidth * this.data.widthScale * pixelRatio
+ const height = info.windowHeight * this.data.heightScale * pixelRatio
+ // 存在 webgl Canvas的情况下,写入大小
+ if (this.canvas) {
+ this.canvas.width = width
+ this.canvas.height = height
+ }
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.setData({
+ width,
+ height,
+ domWidth: info.windowWidth * this.data.widthScale,
+ domHeight: info.windowHeight * this.data.heightScale,
+ })
+ },
+ // 前后摄像头
+ switchCamera() {
+ if (this.session.config) {
+ const config = this.session.config
+ let cameraPosNext
+ if (this.data.cameraPosition === 0) {
+ cameraPosNext = 1
+ } else {
+ cameraPosNext = 0
+ }
+ config.cameraPosition = cameraPosNext
+ this.session.config = config
+ this.setData({
+ cameraPosition: cameraPosNext
+ })
+ }
+ },
+ // 限帧逻辑
+ initLoop() {
+ // 限制调用帧率,暂时去掉
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
- const session = this.session;
+ const session = this.session
- // 逐帧渲染
- const onFrame = timestamp => {
- try {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- this.loop();
- }
- } catch(e) {
- console.error(e);
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- },
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ try {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ this.loop()
+ }
+ } catch (e) {
+ console.error(e)
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
},
-});
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/behavior/behavior-three-shoe.js b/miniprogram/packageAPI/pages/ar/behavior/behavior-three-shoe.js
index 28234cf1..0557bf90 100644
--- a/miniprogram/packageAPI/pages/ar/behavior/behavior-three-shoe.js
+++ b/miniprogram/packageAPI/pages/ar/behavior/behavior-three-shoe.js
@@ -1,136 +1,146 @@
const threeBehavior = Behavior({
- methods: {
- updateThreeMatrix() {
- // 同步 VKCamera 矩阵信息到 Three Camera
- if (VKCamera) {
- // VK接管相机矩阵
- this.camera.matrixAutoUpdate = false
-
- // VK ViewMatrix 返回列主序
- this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
-
- const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR)
-
- // projectionMatrix[0] = projectionMatrix[0] / 2;
- // projectionMatrix[5] = projectionMatrix[5] / 2;
-
- // VK 返回列主序
- // 设置 投影矩阵
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
-
-
- // 存在model,更新矩阵
- if (this.modelWrap && this.points3d && this.shoeTransform) {
- // console.log('toUpdate')
- const THREE = this.THREE;
-
- // 顶点偏移矩阵
- const positionMat = new THREE.Matrix4();
- // 认为点 0 0 0
- positionMat.setPosition(0, 0, 0);
-
- // Anchor返回矩阵,实际上就是完整的 modelView matrix
- const anchorMatrix = new THREE.Matrix4();
- // 目前返回的是行主序矩阵
- anchorMatrix.set(
- this.shoeTransform[0], this.shoeTransform[1], this.shoeTransform[2], this.shoeTransform[3],
- this.shoeTransform[4], this.shoeTransform[5], this.shoeTransform[6], this.shoeTransform[7],
- this.shoeTransform[8], this.shoeTransform[9], this.shoeTransform[10], this.shoeTransform[11],
- this.shoeTransform[12], this.shoeTransform[13], this.shoeTransform[14], this.shoeTransform[15],
- );
- // 两者叠加
- // const modelWorld = positionMat.multiply(anchorMatrix);
-
- const modelWorld = anchorMatrix;
-
- const pos = new THREE.Vector3();
- const quaternion = new THREE.Quaternion();
- const scale = new THREE.Vector3();
-
- // 解析出 实际的 信息
- modelWorld.decompose(pos, quaternion, scale );
- console.log(pos, quaternion, scale);
-
- // 设置到容器节点上
- this.modelWrap.position.set(pos.x, pos.y, pos.z);
- this.modelWrap.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
- this.modelWrap.scale.set(scale.x, scale.y, scale.z);
-
- if (this.model) {
- // 先把模型放置在脚踝
- // this.model.position.set(this.points3d[0].x, this.points3d[0].y, this.points3d[0].z);
- }
-
- if (this.hintBoxList && this.hintBoxList.length > 0) {
- // console.log('ready to set', this.hintBoxList);
- // 存在提示列表,则更新点信息
- for (let i = 0; i < this.hintBoxList.length; i++) {
- const hintBox = this.hintBoxList[i];
- hintBox.position.set(this.points3d[i].x, this.points3d[i].y, this.points3d[i].z);
- }
- // console.log('seted', this.hintBoxList);
- }
-
-
- // debug 用信息
- if (!loggerOnce) {
- // console.log('positionMat', positionMat);
- // console.log('anchorMat', anchorMat);
- // console.log('modelWorld', modelWorld);
-
- // console.log('projectionMatrix', this.camera.projectionMatrix);
-
- // console.log('this.modelWrap.position', this.modelWrap.position);
- // console.log('this.modelWrap.quaternion', this.modelWrap.quaternion);
- // console.log('this.modelWrap.scale', this.modelWrap.scale);
-
- // console.log('domSize', this.data.domWidth, this.data.domHeight)
- // VK 直接数值
- console.log('joints', Array.from(this.points3d))
- console.log('viewMatrix', Array.from(VKCamera.viewMatrix))
- console.log('projectionMatrix', Array.from(VKCamera.getProjectionMatrix(NEAR, FAR)))
- console.log('anchorTransform', Array.from(this.shoeTransform));
-
- loggerOnce = true;
- }
- }
-
- // 渲染 Three 场景
- this.renderer.autoClearColor = false
- this.renderer.state.setCullFace(this.THREE.CullFaceBack)
- this.renderer.render(this.scene, this.camera);
- // 为什么去掉这句话会画不出来,我感觉大概率是YUV的面朝向错了
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
- addShoeHintBox() {
- const THREE = this.THREE;
-
- const wrap = this.modelWrap;
-
- const geometry = new THREE.BoxGeometry( 1, 1, 1 );
- const boxScale = 0.3;
-
- const hintBoxList = [];
- for (let i = 0; i < 8; i++) {
- const colorHex = (i * 2).toString(16);
- const material = new THREE.MeshPhysicalMaterial( {
- metalness: 0.0,
- roughness: 0.5,
- color: parseInt(`${colorHex}${colorHex}${colorHex}${colorHex}${colorHex}${colorHex}`, 16),
- });
- const mesh = new THREE.Mesh( geometry, material );
- mesh.position.set(0, 0, 0);
- mesh.scale.set(boxScale, boxScale, boxScale);
- wrap.add( mesh );
- hintBoxList.push(mesh);
- }
-
- this.hintBoxList = hintBoxList;
- },
+ methods: {
+ updateThreeMatrix() {
+ // 同步 VKCamera 矩阵信息到 Three Camera
+ if (VKCamera) {
+ // VK接管相机矩阵
+ this.camera.matrixAutoUpdate = false
+
+ // VK ViewMatrix 返回列主序
+ this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+
+ const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR)
+
+ // projectionMatrix[0] = projectionMatrix[0] / 2;
+ // projectionMatrix[5] = projectionMatrix[5] / 2;
+
+ // VK 返回列主序
+ // 设置 投影矩阵
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
+
+ // 存在model,更新矩阵
+ if (this.modelWrap && this.points3d && this.shoeTransform) {
+ // console.log('toUpdate')
+ const THREE = this.THREE
+
+ // 顶点偏移矩阵
+ const positionMat = new THREE.Matrix4()
+ // 认为点 0 0 0
+ positionMat.setPosition(0, 0, 0)
+
+ // Anchor返回矩阵,实际上就是完整的 modelView matrix
+ const anchorMatrix = new THREE.Matrix4()
+ // 目前返回的是行主序矩阵
+ anchorMatrix.set(
+ this.shoeTransform[0],
+ this.shoeTransform[1],
+ this.shoeTransform[2],
+ this.shoeTransform[3],
+ this.shoeTransform[4],
+ this.shoeTransform[5],
+ this.shoeTransform[6],
+ this.shoeTransform[7],
+ this.shoeTransform[8],
+ this.shoeTransform[9],
+ this.shoeTransform[10],
+ this.shoeTransform[11],
+ this.shoeTransform[12],
+ this.shoeTransform[13],
+ this.shoeTransform[14],
+ this.shoeTransform[15],
+ )
+ // 两者叠加
+ // const modelWorld = positionMat.multiply(anchorMatrix);
+
+ const modelWorld = anchorMatrix
+
+ const pos = new THREE.Vector3()
+ const quaternion = new THREE.Quaternion()
+ const scale = new THREE.Vector3()
+
+ // 解析出 实际的 信息
+ modelWorld.decompose(pos, quaternion, scale)
+ console.log(pos, quaternion, scale)
+
+ // 设置到容器节点上
+ this.modelWrap.position.set(pos.x, pos.y, pos.z)
+ this.modelWrap.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w)
+ this.modelWrap.scale.set(scale.x, scale.y, scale.z)
+
+ if (this.model) {
+ // 先把模型放置在脚踝
+ // this.model.position.set(this.points3d[0].x, this.points3d[0].y, this.points3d[0].z);
+ }
+
+ if (this.hintBoxList && this.hintBoxList.length > 0) {
+ // console.log('ready to set', this.hintBoxList);
+ // 存在提示列表,则更新点信息
+ for (let i = 0; i < this.hintBoxList.length; i++) {
+ const hintBox = this.hintBoxList[i]
+ hintBox.position.set(this.points3d[i].x, this.points3d[i].y, this.points3d[i].z)
+ }
+ // console.log('seted', this.hintBoxList);
+ }
+
+ // debug 用信息
+ if (!loggerOnce) {
+ // console.log('positionMat', positionMat);
+ // console.log('anchorMat', anchorMat);
+ // console.log('modelWorld', modelWorld);
+
+ // console.log('projectionMatrix', this.camera.projectionMatrix);
+
+ // console.log('this.modelWrap.position', this.modelWrap.position);
+ // console.log('this.modelWrap.quaternion', this.modelWrap.quaternion);
+ // console.log('this.modelWrap.scale', this.modelWrap.scale);
+
+ // console.log('domSize', this.data.domWidth, this.data.domHeight)
+ // VK 直接数值
+ console.log('joints', Array.from(this.points3d))
+ console.log('viewMatrix', Array.from(VKCamera.viewMatrix))
+ console.log('projectionMatrix', Array.from(VKCamera.getProjectionMatrix(NEAR, FAR)))
+ console.log('anchorTransform', Array.from(this.shoeTransform))
+
+ loggerOnce = true
+ }
+ }
+
+ // 渲染 Three 场景
+ this.renderer.autoClearColor = false
+ this.renderer.state.setCullFace(this.THREE.CullFaceBack)
+ this.renderer.render(this.scene, this.camera)
+ // 为什么去掉这句话会画不出来,我感觉大概率是YUV的面朝向错了
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
+ addShoeHintBox() {
+ const THREE = this.THREE
+
+ const wrap = this.modelWrap
+
+ const geometry = new THREE.BoxGeometry(1, 1, 1)
+ const boxScale = 0.3
+
+ const hintBoxList = []
+ for (let i = 0; i < 8; i++) {
+ const colorHex = (i * 2).toString(16)
+ const material = new THREE.MeshPhysicalMaterial({
+ metalness: 0.0,
+ roughness: 0.5,
+ color: parseInt(`${colorHex}${colorHex}${colorHex}${colorHex}${colorHex}${colorHex}`, 16),
+ })
+ const mesh = new THREE.Mesh(geometry, material)
+ mesh.position.set(0, 0, 0)
+ mesh.scale.set(boxScale, boxScale, boxScale)
+ wrap.add(mesh)
+ hintBoxList.push(mesh)
+ }
+
+ this.hintBoxList = hintBoxList
+ },
+ },
})
-export default threeBehavior;
\ No newline at end of file
+export default threeBehavior
diff --git a/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js b/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js
index c09697b4..8d8482b9 100644
--- a/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js
+++ b/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js
@@ -2,47 +2,47 @@ import { createScopedThreejs } from 'threejs-miniprogram'
import { registerGLTFLoader } from '../loaders/gltf-loader'
const threeBehavior = Behavior({
- methods: {
- // 针对 threejs 的初始化逻辑
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // glTF loader
- this.loader = new this.THREE.GLTFLoader()
-
- // 相机
- this.camera = new THREE.PerspectiveCamera(50, 0.7, 0.1, 1000);
-
- // 场景
- const scene = this.scene = new THREE.Scene()
- const sceneCull = this.sceneCull = new THREE.Scene()
-
- // 光源
- const ambientLight = new THREE.AmbientLight( 0x555555 ); // 氛围光
- scene.add( ambientLight );
- const dirLight = new THREE.DirectionalLight(0xffffff, 1) // 平行光
- dirLight.position.set(1, 1, 1);
- scene.add(dirLight)
-
- const ambientLightCull = new THREE.AmbientLight( 0x555555 ); // 氛围光
- sceneCull.add( ambientLightCull );
- const dirLightCull = new THREE.DirectionalLight(0xffffff, 1) // 平行光
- dirLightCull.position.set(1, 1, 1);
- sceneCull.add(dirLightCull)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- initYUVShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ // 针对 threejs 的初始化逻辑
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // glTF loader
+ this.loader = new this.THREE.GLTFLoader()
+
+ // 相机
+ this.camera = new THREE.PerspectiveCamera(50, 0.7, 0.1, 1000)
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+ const sceneCull = this.sceneCull = new THREE.Scene()
+
+ // 光源
+ const ambientLight = new THREE.AmbientLight(0x555555) // 氛围光
+ scene.add(ambientLight)
+ const dirLight = new THREE.DirectionalLight(0xffffff, 1) // 平行光
+ dirLight.position.set(1, 1, 1)
+ scene.add(dirLight)
+
+ const ambientLightCull = new THREE.AmbientLight(0x555555) // 氛围光
+ sceneCull.add(ambientLightCull)
+ const dirLightCull = new THREE.DirectionalLight(0xffffff, 1) // 平行光
+ dirLightCull.position.set(1, 1, 1)
+ sceneCull.add(dirLightCull)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ initYUVShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -53,7 +53,7 @@ const threeBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -76,109 +76,108 @@ const threeBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO(program) {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- return vao;
- },
- initYUV() {
- this.initYUVShader()
- this._vao = this.initVAO(this._program);
- },
- renderYUV(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
- initDepthShaderHint() {
- const gl = this.gl = this.renderer.getContext()
- const ext = gl.getExtension("OES_texture_float");
- if (!ext)
- console.warn('OES_texture_float not support');
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
+ },
+ initVAO(program) {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ return vao
+ },
+ initYUV() {
+ this.initYUVShader()
+ this._vao = this.initVAO(this._program)
+ },
+ renderYUV(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ initDepthShaderHint() {
+ const gl = this.gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_texture_float')
+ if (!ext) console.warn('OES_texture_float not support')
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
precision highp float;
attribute vec2 a_position;
attribute vec2 a_texCoord;
@@ -190,7 +189,7 @@ const threeBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D depth_texture;
varying vec2 v_texCoord;
@@ -199,64 +198,64 @@ const threeBehavior = Behavior({
gl_FragColor = vec4(depth_color.rgb, 1.0);
}
`
-
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._depthProgram = gl.createProgram()
- this._depthProgram.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformTexture = gl.getUniformLocation(program, 'depth_texture')
- gl.uniform1i(uniformTexture, 5)
-
- this._depthDt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initDepthVAOHint() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._depthProgram, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.3, 0.3, 1, 0.3, 0.3, 1, 1, 1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._depthProgram, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._depthVao = vao
- },
- initDepthShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
-
- const dvs = `#version 300 es
+
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._depthProgram = gl.createProgram()
+ this._depthProgram.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformTexture = gl.getUniformLocation(program, 'depth_texture')
+ gl.uniform1i(uniformTexture, 5)
+
+ this._depthDt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
+ },
+ initDepthVAOHint() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._depthProgram, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.3, 0.3, 1, 0.3, 0.3, 1, 1, 1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._depthProgram, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._depthVao = vao
+ },
+ initDepthShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+
+ const dvs = `#version 300 es
precision highp float;
in vec2 a_position;
in vec2 a_texCoord;
@@ -271,8 +270,8 @@ const threeBehavior = Behavior({
gl_Position = vec4(p.x, p.y, p.z, 1);
}
`
-
- const dfs = `#version 300 es
+
+ const dfs = `#version 300 es
precision highp float;
uniform sampler2D depth_texture;
out vec4 FragColor;
@@ -284,179 +283,176 @@ const threeBehavior = Behavior({
// FragColor = vec4(depth_color.rgb, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, dvs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, dfs)
- gl.compileShader(fragShader)
-
- const program = this._depthOutputProgram = gl.createProgram()
- this._depthOutputProgram.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformDepthTexture = gl.getUniformLocation(this._depthOutputProgram, 'depth_texture')
- gl.uniform1i(uniformDepthTexture, 5)
- gl.getUniformLocation(this._depthOutputProgram, 'displayTransform')
-
- gl.useProgram(currentProgram)
- },
- initDepthGL(){
- // 初始化提示
- this.initDepthShaderHint()
- this.initDepthVAOHint()
- // 初始化深度纹理相关
- this.initDepthShader();
- this._vaoDepth = this.initVAO(this._depthOutputProgram);
- },
- renderDepthGLHint(frame) {
- const gl = this.renderer.getContext();
- const displayTransform = frame.getDisplayTransform()
-
- // DepthBuffer
- const depthBufferRes = frame.getDepthBuffer();
- const depthBuffer = new Float32Array(depthBufferRes.DepthAddress);
-
- // console.log('depthBuffer', depthBuffer[0], depthBuffer[16], depthBuffer[16 * 16], depthBuffer[56 * 56]);
-
- const texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
-
- const width = depthBufferRes.width;
- const height = depthBufferRes.height;
-
- // 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
- const data = new Uint8Array(width * height * 4);
- for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i] = num;
- }
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
-
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._depthProgram)
- this.ext.bindVertexArrayOES(this._depthVao)
-
- gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, texture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- },
- renderDepthGL(frame) {
- const gl = this.renderer.getContext()
- const displayTransform = frame.getDisplayTransform()
-
- // DepthBuffer
- const depthBufferRes = frame.getDepthBuffer();
- const depthBuffer = new Float32Array(depthBufferRes.DepthAddress);
-
- const texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
-
- const width = depthBufferRes.width;
- const height = depthBufferRes.height;
-
- // 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
- const data = new Uint8Array(width * height * 4);
- for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i] = num;
- }
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
-
- // console.log('gl depth texture end')
-
- // 绘制左下角提示
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const bindingTexture = gl.getParameter(gl.TEXTURE_BINDING_2D)
-
- gl.useProgram(this._depthProgram)
- this.ext.bindVertexArrayOES(this._depthVao)
-
- gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, texture)
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, dvs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, dfs)
+ gl.compileShader(fragShader)
+
+ const program = this._depthOutputProgram = gl.createProgram()
+ this._depthOutputProgram.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformDepthTexture = gl.getUniformLocation(this._depthOutputProgram, 'depth_texture')
+ gl.uniform1i(uniformDepthTexture, 5)
+ gl.getUniformLocation(this._depthOutputProgram, 'displayTransform')
+
+ gl.useProgram(currentProgram)
+ },
+ initDepthGL() {
+ // 初始化提示
+ this.initDepthShaderHint()
+ this.initDepthVAOHint()
+ // 初始化深度纹理相关
+ this.initDepthShader()
+ this._vaoDepth = this.initVAO(this._depthOutputProgram)
+ },
+ renderDepthGLHint(frame) {
+ const gl = this.renderer.getContext()
+ const displayTransform = frame.getDisplayTransform()
+
+ // DepthBuffer
+ const depthBufferRes = frame.getDepthBuffer()
+ const depthBuffer = new Float32Array(depthBufferRes.DepthAddress)
+
+ // console.log('depthBuffer', depthBuffer[0], depthBuffer[16], depthBuffer[16 * 16], depthBuffer[56 * 56]);
+
+ const texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
+
+ const width = depthBufferRes.width
+ const height = depthBufferRes.height
+
+ // 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
+ const data = new Uint8Array(width * height * 4)
+ for (let i = 0; i < depthBuffer.length; i++) {
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i] = num
+ }
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
+
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._depthProgram)
+ this.ext.bindVertexArrayOES(this._depthVao)
+
+ gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ },
+ renderDepthGL(frame) {
+ const gl = this.renderer.getContext()
+ const displayTransform = frame.getDisplayTransform()
+
+ // DepthBuffer
+ const depthBufferRes = frame.getDepthBuffer()
+ const depthBuffer = new Float32Array(depthBufferRes.DepthAddress)
+
+ const texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
+
+ const width = depthBufferRes.width
+ const height = depthBufferRes.height
+
+ // 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
+ const data = new Uint8Array(width * height * 4)
+ for (let i = 0; i < depthBuffer.length; i++) {
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i] = num
+ }
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
+
+ // console.log('gl depth texture end')
+
+ // 绘制左下角提示
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const bindingTexture = gl.getParameter(gl.TEXTURE_BINDING_2D)
+
+ gl.useProgram(this._depthProgram)
+ this.ext.bindVertexArrayOES(this._depthVao)
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+ gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, texture)
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
- // console.log('gl hint end')
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
- // 写入深度遮挡纹理到深度值
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
- gl.enable(gl.DEPTH_TEST)
- gl.depthMask(true)
- gl.depthFunc(gl.ALWAYS)
-
- this.ext.bindVertexArrayOES(this._vaoDepth)
- gl.useProgram(this._depthOutputProgram)
+ // console.log('gl hint end')
- gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
+ // 写入深度遮挡纹理到深度值
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5Depth = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.enable(gl.DEPTH_TEST)
+ gl.depthMask(true)
+ gl.depthFunc(gl.ALWAYS)
- gl.bindTexture(gl.TEXTURE_2D, texture)
+ this.ext.bindVertexArrayOES(this._vaoDepth)
+ gl.useProgram(this._depthOutputProgram)
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+ gl.uniformMatrix3fv(this._depthDt, false, displayTransform)
- gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5Depth = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5Depth)
+ gl.bindTexture(gl.TEXTURE_2D, texture)
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture)
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
- this.ext.bindVertexArrayOES(currentVAO)
+ gl.activeTexture(gl.TEXTURE0 + 5)
- gl.depthMask(false)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5Depth)
- gl.depthFunc(gl.LESS)
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture)
- // console.log('gl depth draw end')
+ this.ext.bindVertexArrayOES(currentVAO)
+ gl.depthMask(false)
+ gl.depthFunc(gl.LESS)
- },
+ // console.log('gl depth draw end')
},
+ },
})
-export default threeBehavior;
\ No newline at end of file
+export default threeBehavior
diff --git a/miniprogram/packageAPI/pages/ar/behavior/behavior-xrframe.js b/miniprogram/packageAPI/pages/ar/behavior/behavior-xrframe.js
index ac9457b6..f9b88e6f 100644
--- a/miniprogram/packageAPI/pages/ar/behavior/behavior-xrframe.js
+++ b/miniprogram/packageAPI/pages/ar/behavior/behavior-xrframe.js
@@ -1,67 +1,67 @@
const xrFrameBehavior = Behavior({
- yuvMat: undefined, // yuv纹理
- yuvMatInit: undefined, // yuv纹理是否已经初始化
- DT: undefined, // 缓存displayMatrix
- methods: {
- // xrScene Ready 事件回调
- handleXRSceneReady(detail) {
- console.log('handleXRSceneReady', detail);
- const xrFrameSystem = wx.getXrFrameSystem();
-
- this.xrCamera = detail.detail.camera;
- this.xrCameraTrs = this.xrCamera.el.getComponent(xrFrameSystem.Transform);
- this.xrScene = detail.detail.scene;
- this.xrFrameReady = true;
- if (this.initXRFrame) {
- this.initXRFrame();
- }
- },
- // 绑定自定义 YUV effect
- registerYUVEffect() {
- const xrFrameSystem = wx.getXrFrameSystem();
- xrFrameSystem.registerEffect('ar-yuv-self', scene => scene.createEffect({
-properties: [
-{
- "key": 'u_displayMatrix',
- "type": 6,
- "default": [
- 1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- 0, 0, 0, 1
- ]
-}
-],
-images: [
- {
- key: 'u_yTexture',
- default: 'black',
- macro: 'WX_AR_CAMERA_READY'
- },
- {
- key: 'u_uvTexture',
- default: 'white'
- },
- {
- key: 'u_depthTexture',
- default: 'white',
- macro: 'WX_AR_CAMERA_DEPTH'
- }
-],
- defaultRenderQueue: 2000,
- passes: [{
- renderStates: {
- cullOn: false,
- blendOn: false,
- depthWrite: false
+ yuvMat: undefined, // yuv纹理
+ yuvMatInit: undefined, // yuv纹理是否已经初始化
+ DT: undefined, // 缓存displayMatrix
+ methods: {
+ // xrScene Ready 事件回调
+ handleXRSceneReady(detail) {
+ console.log('handleXRSceneReady', detail)
+ const xrFrameSystem = wx.getXrFrameSystem()
+
+ this.xrCamera = detail.detail.camera
+ this.xrCameraTrs = this.xrCamera.el.getComponent(xrFrameSystem.Transform)
+ this.xrScene = detail.detail.scene
+ this.xrFrameReady = true
+ if (this.initXRFrame) {
+ this.initXRFrame()
+ }
},
- lightMode: 'ForwardBase',
- useMaterialRenderStates: true,
- shaders: [0, 1]
- }],
- shaders:
+ // 绑定自定义 YUV effect
+ registerYUVEffect() {
+ const xrFrameSystem = wx.getXrFrameSystem()
+ xrFrameSystem.registerEffect('ar-yuv-self', scene => scene.createEffect({
+ properties: [
+ {
+ key: 'u_displayMatrix',
+ type: 6,
+ default: [
+ 1, 0, 0, 0,
+ 0, 1, 0, 0,
+ 0, 0, 1, 0,
+ 0, 0, 0, 1
+ ]
+ }
+ ],
+ images: [
+ {
+ key: 'u_yTexture',
+ default: 'black',
+ macro: 'WX_AR_CAMERA_READY'
+ },
+ {
+ key: 'u_uvTexture',
+ default: 'white'
+ },
+ {
+ key: 'u_depthTexture',
+ default: 'white',
+ macro: 'WX_AR_CAMERA_DEPTH'
+ }
+ ],
+ defaultRenderQueue: 2000,
+ passes: [{
+ renderStates: {
+ cullOn: false,
+ blendOn: false,
+ depthWrite: false
+ },
+ lightMode: 'ForwardBase',
+ useMaterialRenderStates: true,
+ shaders: [0, 1]
+ }],
+ shaders:
[
-`#version 100
+ `#version 100
attribute vec3 a_position;
attribute vec2 a_texCoord;
@@ -85,7 +85,7 @@ void main() {
gl_Position = pos;
}
`,
-`#version 100
+ `#version 100
precision mediump float;
precision highp int;
@@ -122,107 +122,108 @@ void main()
}
`
]
- }))
- },
- // 初始化 xr-frame 相机 YUV 数据绘制流程节点
- initXRYUVCamera() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {assets, rootShadow} = scene;
-
- const el = scene.createElement(xrFrameSystem.XRNode, {
- layer: 1
- });
-
- let yuvGeometry = assets.getAsset('geometry', `ar-camera-plane`);
- let yuvEffect = assets.getAsset('effect', 'ar-yuv-self');
-
- if (!yuvEffect) {
- this.registerYUVEffect();
- yuvEffect = assets.getAsset('effect', 'ar-yuv-self');
- }
-
- const yuvMat = scene.createMaterial(yuvEffect);
- yuvMat.renderQueue = 1; // 第一个绘制
- const mesh = el.addComponent(xrFrameSystem.Mesh, {
- geometry: yuvGeometry,
- material: yuvMat
- });
-
- // 相机yuv纹理
- this.yuvMat = yuvMat;
- this.yuvMatInit = false;
-
- // 不进入正常的剔除
- rootShadow.addChild(el);
-
- console.log('initXRYUVCamera end')
- },
- updataXRYUV(frame) {
- // console.log('update yuv')
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const yuv = frame.getCameraRawTextureData();
- // 未创建相机贴图缓存,先创建
- if (!this.cameraTexures) {
- this.cameraTexures = {
- y: scene.createTexture({
- width: yuv.width, height: yuv.height,
- source: [yuv.yAddress],
- pixelFormat: xrFrameSystem.ETextureFormat.R8
- }),
- uv: scene.createTexture({
- width: yuv.width / 2, height: yuv.height / 2,
- source: [yuv.uvAddress],
- pixelFormat: xrFrameSystem.ETextureFormat.RGBA4
- })
- }
- }
- const {y, uv, depth} = this.cameraTexures;
-
- const cameraYUVMat = this.yuvMat;
- // 未绑定贴图的情况下,绑定贴图
- if (!this.yuvMatInit) {
- cameraYUVMat.setTexture('u_yTexture', y);
- cameraYUVMat.setTexture('u_uvTexture', uv);
- // depth && cameraYUVMat.setTexture('u_depthTexture', depth);
- this.yuvMatInit = true;
- }
-
- // 更新displayMat
- const dt = frame.getDisplayTransform();
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- this.DT.setArray([
- dt[0], dt[1], dt[2], 0,
- dt[3], dt[4], dt[5], 0,
- dt[6], dt[7], dt[8], 0,
- 0, 0, 0, 1
- ]);
- cameraYUVMat.setMatrix('u_displayMatrix', this.DT);
-
- // YUV纹理更新
- y.update({buffer: yuv.yAddress});
- uv.update({buffer: yuv.uvAddress});
-
- // console.log('update yuv end')
- },
- updataXRCameraMatrix(VKCamera, near, far) {
- // 同步 VKCamera 矩阵信息到 xrFrame Camera
- if (VKCamera) {
- const viewMat = VKCamera.viewMatrix;
- const projMat = VKCamera.getProjectionMatrix(near, far);
-
- // 更新 viewMatrix
- this.xrCamera.changeViewMatrix(true, viewMat);
-
- // 更新 projectMatrix
- const halfFov = Math.atan(1 / projMat[5]) * 180 / Math.PI;
- this.xrCamera.setData({ near: near, far: far, fov: 2 * halfFov });
- this.xrCamera.changeProjectMatrix(true, projMat);
-
- }
- },
+ }))
+ },
+ // 初始化 xr-frame 相机 YUV 数据绘制流程节点
+ initXRYUVCamera() {
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { assets, rootShadow } = scene
+
+ const el = scene.createElement(xrFrameSystem.XRNode, {
+ layer: 1
+ })
+
+ const yuvGeometry = assets.getAsset('geometry', 'ar-camera-plane')
+ let yuvEffect = assets.getAsset('effect', 'ar-yuv-self')
+
+ if (!yuvEffect) {
+ this.registerYUVEffect()
+ yuvEffect = assets.getAsset('effect', 'ar-yuv-self')
+ }
+
+ const yuvMat = scene.createMaterial(yuvEffect)
+ yuvMat.renderQueue = 1 // 第一个绘制
+ const mesh = el.addComponent(xrFrameSystem.Mesh, {
+ geometry: yuvGeometry,
+ material: yuvMat
+ })
+
+ // 相机yuv纹理
+ this.yuvMat = yuvMat
+ this.yuvMatInit = false
+
+ // 不进入正常的剔除
+ rootShadow.addChild(el)
+
+ console.log('initXRYUVCamera end')
+ },
+ updataXRYUV(frame) {
+ // console.log('update yuv')
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const yuv = frame.getCameraRawTextureData()
+ // 未创建相机贴图缓存,先创建
+ if (!this.cameraTexures) {
+ this.cameraTexures = {
+ y: scene.createTexture({
+ width: yuv.width,
+ height: yuv.height,
+ source: [yuv.yAddress],
+ pixelFormat: xrFrameSystem.ETextureFormat.R8
+ }),
+ uv: scene.createTexture({
+ width: yuv.width / 2,
+ height: yuv.height / 2,
+ source: [yuv.uvAddress],
+ pixelFormat: xrFrameSystem.ETextureFormat.RGBA4
+ })
+ }
+ }
+ const { y, uv, depth } = this.cameraTexures
+
+ const cameraYUVMat = this.yuvMat
+ // 未绑定贴图的情况下,绑定贴图
+ if (!this.yuvMatInit) {
+ cameraYUVMat.setTexture('u_yTexture', y)
+ cameraYUVMat.setTexture('u_uvTexture', uv)
+ // depth && cameraYUVMat.setTexture('u_depthTexture', depth);
+ this.yuvMatInit = true
+ }
+
+ // 更新displayMat
+ const dt = frame.getDisplayTransform()
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ this.DT.setArray([
+ dt[0], dt[1], dt[2], 0,
+ dt[3], dt[4], dt[5], 0,
+ dt[6], dt[7], dt[8], 0,
+ 0, 0, 0, 1
+ ])
+ cameraYUVMat.setMatrix('u_displayMatrix', this.DT)
+
+ // YUV纹理更新
+ y.update({ buffer: yuv.yAddress })
+ uv.update({ buffer: yuv.uvAddress })
+
+ // console.log('update yuv end')
+ },
+ updataXRCameraMatrix(VKCamera, near, far) {
+ // 同步 VKCamera 矩阵信息到 xrFrame Camera
+ if (VKCamera) {
+ const viewMat = VKCamera.viewMatrix
+ const projMat = VKCamera.getProjectionMatrix(near, far)
+
+ // 更新 viewMatrix
+ this.xrCamera.changeViewMatrix(true, viewMat)
+
+ // 更新 projectMatrix
+ const halfFov = Math.atan(1 / projMat[5]) * 180 / Math.PI
+ this.xrCamera.setData({ near, far, fov: 2 * halfFov })
+ this.xrCamera.changeProjectMatrix(true, projMat)
+ }
},
+ },
})
-export default xrFrameBehavior;
\ No newline at end of file
+export default xrFrameBehavior
diff --git a/miniprogram/packageAPI/pages/ar/body-detect-3d/body-detect-3d.js b/miniprogram/packageAPI/pages/ar/body-detect-3d/body-detect-3d.js
index 782c2ba5..964f1c32 100644
--- a/miniprogram/packageAPI/pages/ar/body-detect-3d/body-detect-3d.js
+++ b/miniprogram/packageAPI/pages/ar/body-detect-3d/body-detect-3d.js
@@ -5,40 +5,40 @@ import xrFrameBehavior from '../behavior/behavior-xrframe'
const NEAR = 0.01
const FAR = 1000
-let loggerOnce = false;
+const loggerOnce = false
Component({
behaviors: [arBehavior, xrFrameBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.85, // canvas高度缩放值
- hintBoxList: [], // 显示提示盒子列表
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.85, // canvas高度缩放值
+ hintBoxList: [], // 显示提示盒子列表
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ }
+ },
},
methods: {
@@ -46,7 +46,7 @@ Component({
init() {
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -58,7 +58,7 @@ Component({
},
version: 'v1',
gl: this.gl
- });
+ })
try {
session.start(err => {
@@ -68,22 +68,22 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// 开启躯体三维识别
- session.update3DMode({open3d: true})
+ session.update3DMode({ open3d: true })
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
- console.log("addAnchor", anchors)
+ console.log('addAnchor', anchors)
})
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// console.log("updateAnchors", anchors);
- const anchor = anchors[0];
+ const anchor = anchors[0]
// 目前只处理一个返回的躯体
if (anchor) {
// console.log('id', anchor.id);
@@ -94,58 +94,51 @@ Component({
// console.log('size', anchor.size);
// console.log('detectId', anchor.detectId);
// console.log('confidence', anchor.confidence);
- // console.log('points3d', anchor.points3d);
+ // console.log('points3d', anchor.points3d);
- this.bodyTransform = anchor.transform;
- this.bodyPosition3D = anchor.points3d;
-
- this.updateHintBoxVisble(this.hintBoxList, true);
+ this.bodyTransform = anchor.transform
+ this.bodyPosition3D = anchor.points3d
+ this.updateHintBoxVisble(this.hintBoxList, true)
}
})
-
+
// VKSession removeAnchors
// 识别目标丢失时不断触发
session.on('removeAnchors', anchors => {
// console.log("removeAnchors");
- this.updateHintBoxVisble(this.hintBoxList, false);
-
- });
-
+ this.updateHintBoxVisble(this.hintBoxList, false)
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
- } catch(e) {
- console.error(e);
+ this.initLoop()
+ })
+ } catch (e) {
+ console.error(e)
}
-
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
// 缓存主相机
this.xrCameraMain = this.xrCamera
- this.xrCameraMainTrs = this.xrCameraTrs;
-
+ this.xrCameraMainTrs = this.xrCameraTrs
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// === 初始躯体挂载点 ===
- this.bodyWrap = scene.createElement(xrFrameSystem.XRNode);
- this.bodyWrapTrs = this.bodyWrap.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( this.bodyWrap );
+ this.bodyWrap = scene.createElement(xrFrameSystem.XRNode)
+ this.bodyWrapTrs = this.bodyWrap.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(this.bodyWrap)
// 加载提示点
- this.hintBoxList = this.getHintBox(xrFrameSystem, scene, this.bodyWrap);
-
-
+ this.hintBoxList = this.getHintBox(xrFrameSystem, scene, this.bodyWrap)
},
loop() {
// console.log('loop')
@@ -154,75 +147,74 @@ Component({
const frame = this.session.getVKFrame(this.data.width, this.data.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
// 存在bodyWrao,执行信息同步逻辑
if (this.bodyWrap && this.bodyTransform) {
- const xrFrameSystem = wx.getXrFrameSystem();
-
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ const xrFrameSystem = wx.getXrFrameSystem()
+
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(this.bodyTransform);
- this.DT.transpose(this.DT2);
- this.bodyWrapTrs.setLocalMatrix(this.DT2);
+ this.DT.setArray(this.bodyTransform)
+ this.DT.transpose(this.DT2)
+ this.bodyWrapTrs.setLocalMatrix(this.DT2)
// 更新提示点位置
- this.updateHintBoxPosition(this.hintBoxList, this.bodyPosition3D);
-
+ this.updateHintBoxPosition(this.hintBoxList, this.bodyPosition3D)
}
},
getHintBox(xrFrameSystem, scene, wrap) {
// 初始化提示点
- const geometryHint = scene.assets.getAsset('geometry', 'sphere');
- const effectCube = scene.assets.getAsset('effect', 'standard');
- const boxScale = 0.03;
- const hintBoxList = [];
+ const geometryHint = scene.assets.getAsset('geometry', 'sphere')
+ const effectCube = scene.assets.getAsset('effect', 'standard')
+ const boxScale = 0.03
+ const hintBoxList = []
for (let i = 0; i < 24; i++) {
- const colorFloat = i / 24;
+ const colorFloat = i / 24
const el = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
+ position: '0 0 0',
scale: `${boxScale} ${boxScale} ${boxScale}`,
- });
- const elTrs = el.getComponent(xrFrameSystem.Transform);
- const mat = scene.createMaterial(effectCube);
-
- const colorR = 1.0 - colorFloat;
- mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0));
+ })
+ const elTrs = el.getComponent(xrFrameSystem.Transform)
+ const mat = scene.createMaterial(effectCube)
+
+ const colorR = 1.0 - colorFloat
+ mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0))
const mesh = el.addComponent(xrFrameSystem.Mesh, {
geometry: geometryHint,
material: mat,
- });
+ })
- wrap.addChild( el );
+ wrap.addChild(el)
// elTrs.visible = false;
-
- hintBoxList.push( elTrs );
+
+ hintBoxList.push(elTrs)
}
- return hintBoxList;
+ return hintBoxList
},
updateHintBoxPosition(hintBoxList, points3d) {
if (hintBoxList && hintBoxList.length > 0) {
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
- hintBox.position.x = points3d[i].x;
- hintBox.position.y = points3d[i].y;
- hintBox.position.z = points3d[i].z;
+ const hintBox = hintBoxList[i]
+ hintBox.position.x = points3d[i].x
+ hintBox.position.y = points3d[i].y
+ hintBox.position.z = points3d[i].z
}
}
},
@@ -231,12 +223,12 @@ Component({
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
+ const hintBox = hintBoxList[i]
if (hintBox.visible !== visible) {
- hintBox.visible = visible;
+ hintBox.visible = visible
}
}
}
}
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/body-detect/behavior.js b/miniprogram/packageAPI/pages/ar/body-detect/behavior.js
index e1d09e9e..edcb2695 100644
--- a/miniprogram/packageAPI/pages/ar/body-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/body-detect/behavior.js
@@ -141,26 +141,25 @@ export default function getBehavior() {
size: anchor.size
})))
- console.log("显示data")
+ console.log('显示data')
console.log(this.data)
})
session.on('removeAnchors', anchors => {
this.data.anchor2DList = []
})
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
// 逐帧渲染
const onFrame = timestamp => {
- let now = Date.now()
+ const now = Date.now()
const mill = now - last
// 经过了足够的时间
if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
+ last = now - (mill % fpsInterval) // 校正当前时间
const frame = session.getVKFrame(canvas.width, canvas.height)
if (frame) {
this.render(frame)
@@ -199,4 +198,4 @@ export default function getBehavior() {
},
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/body-detect/body-detect.js b/miniprogram/packageAPI/pages/ar/body-detect/body-detect.js
index 55cccf2a..a1671252 100644
--- a/miniprogram/packageAPI/pages/ar/body-detect/body-detect.js
+++ b/miniprogram/packageAPI/pages/ar/body-detect/body-detect.js
@@ -4,70 +4,69 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-//顶点着色器
-var VSHADER_SOURCE = '' +
- 'attribute vec4 a_Position;\n' + //声明attribute变量a_Position,用来存放顶点位置信息
+// 顶点着色器
+const VSHADER_SOURCE = '' +
+ 'attribute vec4 a_Position;\n' + // 声明attribute变量a_Position,用来存放顶点位置信息
'void main(){\n' +
- ' gl_Position = a_Position;\n' + //将顶点坐标赋值给顶点着色器内置变量gl_Position
- ' gl_PointSize = 4.0;\n' + //设置顶点大小
+ ' gl_Position = a_Position;\n' + // 将顶点坐标赋值给顶点着色器内置变量gl_Position
+ ' gl_PointSize = 4.0;\n' + // 设置顶点大小
'}\n'
-//片元着色器
-var FSHADER_SOURCE = '' +
+// 片元着色器
+const FSHADER_SOURCE = '' +
'#ifdef GL_ES\n' +
' precision mediump float;\n' + // 设置精度
'#endif\n' +
- 'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
+ 'varying vec4 v_Color;\n' + // 声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
'void main(){\n' +
- ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + //计算像素距离中心点的距离
- ' if(d < 0.5) {\n' + //距离大于0.5放弃片元,小于0.5保留片元
+ ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + // 计算像素距离中心点的距离
+ ' if(d < 0.5) {\n' + // 距离大于0.5放弃片元,小于0.5保留片元
' gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n' +
' } else { discard; }\n' +
'}\n'
-
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
- //创建顶点着色器对象
- var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
- //创建片元着色器对象
- var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
+ // 创建顶点着色器对象
+ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
+ // 创建片元着色器对象
+ const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
if (!vertexShader || !fragmentShader) {
return null
}
- //创建程序对象program
- var program = gl.createProgram()
+ // 创建程序对象program
+ const program = gl.createProgram()
if (!gl.createProgram()) {
return null
}
- //分配顶点着色器和片元着色器到program
+ // 分配顶点着色器和片元着色器到program
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
- //链接program
+ // 链接program
gl.linkProgram(program)
- //检查程序对象是否连接成功
- var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
+ // 检查程序对象是否连接成功
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS)
if (!linked) {
- var error = gl.getProgramInfoLog(program)
+ const error = gl.getProgramInfoLog(program)
console.log('程序对象连接失败: ' + error)
gl.deleteProgram(program)
gl.deleteShader(fragmentShader)
gl.deleteShader(vertexShader)
return null
}
- //返回程序program对象
+ // 返回程序program对象
initShadersDone = true
return program
}
function loadShader(gl, type, source) {
// 创建顶点着色器对象
- var shader = gl.createShader(type)
+ const shader = gl.createShader(type)
if (shader == null) {
console.log('创建着色器失败')
return null
@@ -80,9 +79,9 @@ function loadShader(gl, type, source) {
gl.compileShader(shader)
// 检查顶是否编译成功
- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!compiled) {
- var error = gl.getShaderInfoLog(shader)
+ const error = gl.getShaderInfoLog(shader)
console.log('编译着色器失败: ' + error)
gl.deleteShader(shader)
return null
@@ -91,9 +90,8 @@ function loadShader(gl, type, source) {
return shader
}
-//初始化顶点坐标和顶点颜色
+// 初始化顶点坐标和顶点颜色
function initVertexBuffers(gl, anchor2DList) {
-
const flattenPoints = []
anchor2DList.forEach(anchor => {
anchor.points.forEach(point => {
@@ -105,23 +103,23 @@ function initVertexBuffers(gl, anchor2DList) {
})
})
- var vertices = new Float32Array(flattenPoints)
- var n = flattenPoints.length / 2
+ const vertices = new Float32Array(flattenPoints)
+ const n = flattenPoints.length / 2
- //创建缓冲区对象
- var buffer = gl.createBuffer()
- //将顶点坐标和顶点颜色信息写入缓冲区对象
+ // 创建缓冲区对象
+ const buffer = gl.createBuffer()
+ // 将顶点坐标和顶点颜色信息写入缓冲区对象
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
- //获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
- var a_Position = gl.getAttribLocation(gl.program, 'a_Position')
+ // 获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
+ const a_Position = gl.getAttribLocation(gl.program, 'a_Position')
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)
return n
}
-var EDGE_VSHADER_SOURCE =
+const EDGE_VSHADER_SOURCE =
`
attribute vec2 aPosition;
varying vec2 posJudge;
@@ -132,7 +130,7 @@ var EDGE_VSHADER_SOURCE =
}
`
-var EDGE_FSHADER_SOURCE =
+const EDGE_FSHADER_SOURCE =
`
precision highp float;
uniform vec2 rightTopPoint;
@@ -162,48 +160,47 @@ var EDGE_FSHADER_SOURCE =
`
function initRectEdgeBuffer(gl, x, y, width, height) {
- let shaderProgram = gl.program;
- let centerX = x * 2 - 1 + width;
- let centerY = -1 * (y * 2 - 1) - height;
- let right = width;
- let top = height;
- var vertices = [
+ const shaderProgram = gl.program
+ const centerX = x * 2 - 1 + width
+ const centerY = -1 * (y * 2 - 1) - height
+ const right = width
+ const top = height
+ const vertices = [
-1.0, 1.0,
-1.0, -1.0,
1.0, 1.0,
1.0, -1.0
- ];
+ ]
- var vertexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
- var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');
- gl.enableVertexAttribArray(aPosition);
- gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
+ const vertexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
+ const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition')
+ gl.enableVertexAttribArray(aPosition)
+ gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
-
- var rightTop = [
+ const rightTop = [
right, top
- ];
- var rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint');
- gl.uniform2fv(rightTopLoc, rightTop);
+ ]
+ const rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint')
+ gl.uniform2fv(rightTopLoc, rightTop)
- var centerPoint = [
+ const centerPoint = [
centerX, centerY
- ];
- var centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint');
- gl.uniform2fv(centerPointLoc, centerPoint);
+ ]
+ const centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint')
+ gl.uniform2fv(centerPointLoc, centerPoint)
- var length = vertices.length / 2;
+ const length = vertices.length / 2
- return length;
+ return length
}
function onDrawRectEdge(gl, x, y, width, height) {
width = Math.round(width * 100) / 100
height = Math.round(height * 100) / 100
- var n = initRectEdgeBuffer(gl, x, y, width, height);
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
+ const n = initRectEdgeBuffer(gl, x, y, width, height)
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, n)
}
Component({
@@ -217,15 +214,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -243,19 +240,19 @@ Component({
init() {
this.initGL()
},
- switchCamera(event){
- if(this.session.config){
+ switchCamera(event) {
+ if (this.session.config) {
const config = this.session.config
- let pos = Number(event.currentTarget.dataset.value)
+ const pos = Number(event.currentTarget.dataset.value)
config.cameraPosition = pos
this.session.config = config
this.setData({
- cameraPosition:event.currentTarget.dataset.value
+ cameraPosition: event.currentTarget.dataset.value
})
}
},
render(frame) {
- var gl = this.gl
+ const gl = this.gl
this.renderGL(frame)
@@ -279,7 +276,7 @@ Component({
const anchor2DList = this.data.anchor2DList
if (!anchor2DList || anchor2DList.length <= 0) {
- return
+
} else {
if (!initShadersDone) {
this.vertexProgram = initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)
@@ -293,19 +290,19 @@ Component({
gl.useProgram(this.vertexProgram)
gl.program = this.vertexProgram
- //初始化顶点坐标和顶点颜色
- var n = initVertexBuffers(gl, anchor2DList)
+ // 初始化顶点坐标和顶点颜色
+ const n = initVertexBuffers(gl, anchor2DList)
- //绘制点
+ // 绘制点
gl.drawArrays(gl.POINTS, 0, n)
gl.useProgram(this.rectEdgeProgram)
gl.program = this.rectEdgeProgram
- for (var i = 0; i < anchor2DList.length; i++) {
+ for (let i = 0; i < anchor2DList.length; i++) {
onDrawRectEdge(gl, anchor2DList[i].origin.x, anchor2DList[i].origin.y, anchor2DList[i].size.width, anchor2DList[i].size.height)
}
}
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/body-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/body-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/body-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/body-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/behavior.js b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/behavior.js
index 470142f8..ca548e4d 100644
--- a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/behavior.js
@@ -1,168 +1,167 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- cameraPosition: 0,
- gl: this.gl,
- version: 'v1'
- })
-
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- this.setData({
- buttonDisable:false
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ cameraPosition: 0,
+ gl: this.gl,
+ version: 'v1'
+ })
+
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ this.setData({
+ buttonDisable: false
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBuffer-detect.js b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBuffer-detect.js
index a8991296..5820d49f 100644
--- a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBuffer-detect.js
+++ b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBuffer-detect.js
@@ -5,7 +5,7 @@ import cameraBufferBehavior from './cameraBufferBehavior'
const NEAR = 0.001
const FAR = 1000
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
Component({
@@ -21,15 +21,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -51,14 +51,12 @@ Component({
initShadersDone = true
},
render(frame) {
- if(!initShadersDone)
- return;
- var gl = this.gl
+ if (!initShadersDone) return
+ const gl = this.gl
this.renderGL(frame)
this.renderCameraBufferGL(frame)
-
const camera = frame.camera
// 相机
@@ -77,4 +75,4 @@ Component({
this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBufferBehavior.js b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBufferBehavior.js
index 712bf7a3..278c4f5d 100644
--- a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBufferBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/cameraBufferBehavior.js
@@ -2,9 +2,8 @@ const cameraBufferBehavior = Behavior({
methods: {
initCameraBufferShader() {
const gl = this.gl = this.renderer.getContext()
- const ext = gl.getExtension("OES_texture_float");
- if (!ext)
- console.warn('OES_texture_float not support');
+ const ext = gl.getExtension('OES_texture_float')
+ if (!ext) console.warn('OES_texture_float not support')
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const vs = `
precision highp float;
@@ -60,9 +59,8 @@ const cameraBufferBehavior = Behavior({
ext.bindVertexArrayOES(vao)
-
- const width = Math.floor(this.canvas.width / 16) * 16;
- const height = this.canvas.height;
+ const width = Math.floor(this.canvas.width / 16) * 16
+ const height = this.canvas.height
const posAttr = gl.getAttribLocation(this._cameraBufferProgram, 'a_position')
const pos = gl.createBuffer()
@@ -94,35 +92,30 @@ const cameraBufferBehavior = Behavior({
gl.disable(gl.DEPTH_TEST)
const displayTransform = frame.getDisplayTransform()
- const width = Math.floor(this.canvas.width / 16) * 16;
- const height = this.canvas.height;
+ const width = Math.floor(this.canvas.width / 16) * 16
+ const height = this.canvas.height
- const cameraBufferRes = frame.getCameraBuffer(width, height);
+ const cameraBufferRes = frame.getCameraBuffer(width, height)
- const texture = gl.createTexture();
+ const texture = gl.createTexture()
if (cameraBufferRes) {
+ const cameraBuffer = new Uint8Array(cameraBufferRes)
- let cameraBuffer = new Uint8Array(cameraBufferRes);
-
- const data = new Uint8Array(width * height * 4);
- for (let i = 0; i < cameraBuffer.length; i++) {
- let num = parseInt(cameraBuffer[i] * 255);
- data[i] = num;
- }
-
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ const data = new Uint8Array(width * height * 4)
+ for (let i = 0; i < cameraBuffer.length; i++) {
+ const num = parseInt(cameraBuffer[i] * 255)
+ data[i] = num
+ }
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
}
-
-
-
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
@@ -144,9 +137,8 @@ const cameraBufferBehavior = Behavior({
gl.useProgram(currentProgram)
gl.activeTexture(currentActiveTexture)
this.ext.bindVertexArrayOES(currentVAO)
-
},
},
})
-export default cameraBufferBehavior
\ No newline at end of file
+export default cameraBufferBehavior
diff --git a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/yuvBehavior.js
index 5b63e876..147d1f65 100644
--- a/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/cameraBuffer-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
-
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/cameraBuffer-jpg/cameraBuffer-jpg.js b/miniprogram/packageAPI/pages/ar/cameraBuffer-jpg/cameraBuffer-jpg.js
index 5d667532..fd192560 100644
--- a/miniprogram/packageAPI/pages/ar/cameraBuffer-jpg/cameraBuffer-jpg.js
+++ b/miniprogram/packageAPI/pages/ar/cameraBuffer-jpg/cameraBuffer-jpg.js
@@ -9,34 +9,34 @@ Component({
behaviors: [arBehavior, threeBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.57, // canvas高度缩放值
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.57, // canvas高度缩放值
jpgUrl: '',
},
useLoopLog: false, // 是否开启循环log
imgIndex: 0,
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
@@ -50,11 +50,11 @@ Component({
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
- this.useLoopLog = false;
- this.imgIndex = 0;
- },
+ this.useLoopLog = false
+ this.imgIndex = 0
+ },
initVK() {
// VKSession 配置
const session = this.session = wx.createVKSession({
@@ -65,7 +65,7 @@ Component({
},
version: 'v2',
gl: this.gl
- });
+ })
session.start(err => {
if (err) return console.error('VK error: ', err)
@@ -74,7 +74,7 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// VKSession EVENT addAnchors
@@ -83,32 +83,29 @@ Component({
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
-
+
})
-
+
// VKSession removeAnchors
// 识别目标丢失时,会触发一次
session.on('removeAnchors', anchors => {
// console.log('removeAnchors', anchors)
- });
-
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
-
+ this.initLoop()
+
// 绘制双面,以及去掉清屏,用于显示yuv
this.renderer.state.setCullFace(this.THREE.CullFaceNone)
-
- });
+ })
},
loop() {
-
// 获取 VKFrame
const frame = this.session.getVKFrame(this.canvas.width, this.canvas.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
this.renderYUV(frame)
@@ -122,61 +119,56 @@ Component({
// transformStr += VKCamera.transform[i] + ' ';
// console.log('VKCamera.transform', transformStr);
- console.log('timeStamp', frame.timestamp);
-
+ console.log('timeStamp', frame.timestamp)
- let viewMatrixStr = '';
- for (let i = 0; i < 16; i++)
- viewMatrixStr += VKCamera.viewMatrix[i] + ' ';
+ let viewMatrixStr = ''
+ for (let i = 0; i < 16; i++) viewMatrixStr += VKCamera.viewMatrix[i] + ' '
// console.log('VKCamera.viewMatrix', viewMatrixStr);
if (this.preTimestamp && this.preTimestamp === frame.timestamp) {
if (this.preViewMatrixStr && this.preViewMatrixStr !== viewMatrixStr) {
console.log('preViewMatrixStr', this.preViewMatrixStr)
console.log('viewMatrixStr', viewMatrixStr)
- console.log('Timestamp is same. But viewMatrix is not same');
+ console.log('Timestamp is same. But viewMatrix is not same')
}
}
- this.preTimestamp = frame.timestamp;
- this.preViewMatrixStr = viewMatrixStr;
+ this.preTimestamp = frame.timestamp
+ this.preViewMatrixStr = viewMatrixStr
}
-
},
getJpgImg() {
- console.log('Function getJpgImg');
+ console.log('Function getJpgImg')
// 按需写入获取 jpg 的 大小 和质量
- const width = 640;
- const height = 480;
- const quality = 90;
+ const width = 640
+ const height = 480
+ const quality = 90
// 获取 VKFrame
const frame = this.session.getVKFrame(width, height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
console.log('getCameraJpgBuffer: ', width, height, quality)
const t1 = new Date().getTime()
- const jpgBuffer = frame.getCameraJpgBuffer(width, height, quality);
+ const jpgBuffer = frame.getCameraJpgBuffer(width, height, quality)
const t2 = new Date().getTime()
console.log(`getCameraJpgBuffer cost ${t2 - t1}ms`)
// console.log('jpgBuffer', jpgBuffer);
- const jpgUrl = this.saveLocalJPG(jpgBuffer, 'cameraJPG');
+ const jpgUrl = this.saveLocalJPG(jpgBuffer, 'cameraJPG')
console.log('jpgUrl', jpgUrl)
this.setData({
- 'jpgUrl': jpgUrl
+ jpgUrl
})
-
-
},
saveLocalJPG(bufferContent, name) {
- var url = `${wx.env.USER_DATA_PATH}/${name + this.imgIndex + '.jpg'}`
+ const url = `${wx.env.USER_DATA_PATH}/${name + this.imgIndex + '.jpg'}`
const fs = wx.getFileSystemManager()
try {
@@ -184,8 +176,8 @@ Component({
const unlinkRes = fs.unlinkSync(url)
// console.log('unlinkSync', unlinkRes)
- this.imgIndex++;
- const newUrl = `${wx.env.USER_DATA_PATH}/${name + this.imgIndex + '.jpg'}`;
+ this.imgIndex++
+ const newUrl = `${wx.env.USER_DATA_PATH}/${name + this.imgIndex + '.jpg'}`
// console.log('write newUrl', newUrl)
// 写入,新图片
@@ -196,8 +188,7 @@ Component({
)
return newUrl
-
- } catch(e) {
+ } catch (e) {
// 利用catch实现,此时,为新写入
try {
// console.log('write url', url)
@@ -208,18 +199,18 @@ Component({
bufferContent,
'utf8'
)
- }catch(e) {
- console.error(e);
+ } catch (e) {
+ console.error(e)
}
}
return url
},
getLog() {
- console.log('Function getLog');
+ console.log('Function getLog')
- this.useLoopLog = !this.useLoopLog;
+ this.useLoopLog = !this.useLoopLog
},
-
+
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js b/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js
index eec16962..79e843e8 100644
--- a/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js
+++ b/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js
@@ -9,14 +9,14 @@ Component({
},
lifetimes: {},
methods: {
- handleReady({detail}) {
- const xrScene = this.scene = detail.value;
- console.log('xr-scene', xrScene);
+ handleReady({ detail }) {
+ const xrScene = this.scene = detail.value
+ console.log('xr-scene', xrScene)
- const camera = this.scene.getElementById("camera").getComponent("camera");
+ const camera = this.scene.getElementById('camera').getComponent('camera')
// 暴露scene对象到外部进行定制
- this.triggerEvent('sceneReady', {scene: xrScene, camera: camera});
+ this.triggerEvent('sceneReady', { scene: xrScene, camera })
},
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js b/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js
index 9d4f20b8..1d224043 100644
--- a/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js
+++ b/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js
@@ -9,23 +9,23 @@ Component({
},
lifetimes: {},
methods: {
- handleReady({detail}) {
- const xrScene = this.scene = detail.value;
- console.log('xr-scene', xrScene);
+ handleReady({ detail }) {
+ const xrScene = this.scene = detail.value
+ console.log('xr-scene', xrScene)
// 获取屏幕比例,用作后处理rt比例
const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio;
+ const pixelRatio = info.pixelRatio
this.setData({
pixelRatioReady: true,
renderTargetWidth: info.windowWidth * pixelRatio,
renderTargetHeight: info.windowHeight * pixelRatio,
- });
+ })
- const camera = this.scene.getElementById("camera").getComponent("camera");
+ const camera = this.scene.getElementById('camera').getComponent('camera')
// 暴露scene对象到外部进行定制
- this.triggerEvent('sceneReady', {scene: xrScene, camera: camera});
+ this.triggerEvent('sceneReady', { scene: xrScene, camera })
},
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/depth-detect/behavior.js b/miniprogram/packageAPI/pages/ar/depth-detect/behavior.js
index 4a24a696..18600958 100644
--- a/miniprogram/packageAPI/pages/ar/depth-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/depth-detect/behavior.js
@@ -1,173 +1,172 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- depth: {
- mode: 1
- }
- },
- cameraPosition: 0,
- gl: this.gl,
- version: 'v1'
- })
-
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- this.setData({
- buttonDisable:false
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ depth: {
+ mode: 1
+ }
+ },
+ cameraPosition: 0,
+ gl: this.gl,
+ version: 'v1'
+ })
+
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ this.setData({
+ buttonDisable: false
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/depth-detect/depth-detect.js b/miniprogram/packageAPI/pages/ar/depth-detect/depth-detect.js
index d4294063..002a5cf0 100644
--- a/miniprogram/packageAPI/pages/ar/depth-detect/depth-detect.js
+++ b/miniprogram/packageAPI/pages/ar/depth-detect/depth-detect.js
@@ -5,7 +5,7 @@ import depthBehavior from './depthBehavior'
const NEAR = 0.001
const FAR = 1000
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
Component({
@@ -21,15 +21,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -50,9 +50,8 @@ Component({
initShadersDone = true
},
render(frame) {
- if(!initShadersDone)
- return;
- var gl = this.gl
+ if (!initShadersDone) return
+ const gl = this.gl
this.renderGL(frame)
this.renderDepthGL(frame)
@@ -75,4 +74,4 @@ Component({
this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/depth-detect/depthBehavior.js b/miniprogram/packageAPI/pages/ar/depth-detect/depthBehavior.js
index ec5c2ef3..0bde2dbb 100644
--- a/miniprogram/packageAPI/pages/ar/depth-detect/depthBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/depth-detect/depthBehavior.js
@@ -2,9 +2,8 @@ const depthBehavior = Behavior({
methods: {
initDepthShader() {
const gl = this.gl = this.renderer.getContext()
- const ext = gl.getExtension("OES_texture_float");
- if (!ext)
- console.warn('OES_texture_float not support');
+ const ext = gl.getExtension('OES_texture_float')
+ if (!ext) console.warn('OES_texture_float not support')
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const vs = `
precision highp float;
@@ -116,34 +115,31 @@ const depthBehavior = Behavior({
// }
// DepthBuffer
- const depthBufferRes = frame.getDepthBuffer();
- const depthBuffer = new Float32Array(depthBufferRes.DepthAddress);
+ const depthBufferRes = frame.getDepthBuffer()
+ const depthBuffer = new Float32Array(depthBufferRes.DepthAddress)
- const texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ const texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- const width = depthBufferRes.width;
- const height = depthBufferRes.height;
+ const width = depthBufferRes.width
+ const height = depthBufferRes.height
- const ext = gl.getExtension("OES_texture_float");
+ const ext = gl.getExtension('OES_texture_float')
if (ext) {
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, depthBuffer);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, depthBuffer)
} else {
- const data = new Uint8Array(width * height * 4);
+ const data = new Uint8Array(width * height * 4)
for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i] = num;
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i] = num
}
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
}
-
-
-
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
@@ -165,9 +161,8 @@ const depthBehavior = Behavior({
gl.useProgram(currentProgram)
gl.activeTexture(currentActiveTexture)
this.ext.bindVertexArrayOES(currentVAO)
-
},
},
})
-export default depthBehavior
\ No newline at end of file
+export default depthBehavior
diff --git a/miniprogram/packageAPI/pages/ar/depth-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/depth-detect/yuvBehavior.js
index 5b63e876..147d1f65 100644
--- a/miniprogram/packageAPI/pages/ar/depth-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/depth-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
-
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/face-detect-3d-glasses/face-detect-3d-glasses.js b/miniprogram/packageAPI/pages/ar/face-detect-3d-glasses/face-detect-3d-glasses.js
index 1246f100..48ac5ed3 100644
--- a/miniprogram/packageAPI/pages/ar/face-detect-3d-glasses/face-detect-3d-glasses.js
+++ b/miniprogram/packageAPI/pages/ar/face-detect-3d-glasses/face-detect-3d-glasses.js
@@ -5,41 +5,41 @@ import xrFrameBehavior from '../behavior/behavior-xrframe'
const NEAR = 0.01
const FAR = 1000
-let loggerOnce = false;
+const loggerOnce = false
Component({
behaviors: [arBehavior, xrFrameBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.8, // canvas高度缩放值
- hintBoxList: [], // 显示提示盒子列表,
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.8, // canvas高度缩放值
+ hintBoxList: [], // 显示提示盒子列表,
cameraPosition: 1 // 默认前置
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
@@ -47,7 +47,7 @@ Component({
init() {
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -60,7 +60,7 @@ Component({
cameraPosition: 1,
version: 'v1',
gl: this.gl
- });
+ })
try {
session.start(err => {
@@ -70,119 +70,113 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// 开启三维识别
- session.update3DMode({open3d: true})
+ session.update3DMode({ open3d: true })
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
- console.log("addAnchor", anchors)
+ console.log('addAnchor', anchors)
})
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// console.log("updateAnchors", anchors);
- const anchor = anchors[0];
+ const anchor = anchors[0]
// 目前只处理一个返回的结果
if (anchor) {
-
- this.wrapTransform = anchor.transform;
- this.position3D = anchor.points3d;
+ this.wrapTransform = anchor.transform
+ this.position3D = anchor.points3d
if (this.faceGLTFTrs && this.faceGLTFTrs.visible !== true) {
- this.faceGLTFTrs.visible = true;
+ this.faceGLTFTrs.visible = true
}
if (this.glassesGLTFTrs && this.glassesGLTFTrs.visible !== true) {
- this.glassesGLTFTrs.visible = true;
+ this.glassesGLTFTrs.visible = true
}
}
})
-
+
// VKSession removeAnchors
// 识别目标丢失时不断触发
session.on('removeAnchors', anchors => {
// console.log("removeAnchors");
if (this.faceGLTFTrs && this.faceGLTFTrs.visible !== false) {
- this.faceGLTFTrs.visible = false;
+ this.faceGLTFTrs.visible = false
}
if (this.glassesGLTFTrs && this.glassesGLTFTrs.visible !== false) {
- this.glassesGLTFTrs.visible = false;
+ this.glassesGLTFTrs.visible = false
}
-
- });
-
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
- } catch(e) {
- console.error(e);
+ this.initLoop()
+ })
+ } catch (e) {
+ console.error(e)
}
-
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
// 缓存主相机
this.xrCameraMain = this.xrCamera
- this.xrCameraMainTrs = this.xrCameraTrs;
-
+ this.xrCameraMainTrs = this.xrCameraTrs
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// === 初始挂载点 ===
- this.faceWrap = scene.createElement(xrFrameSystem.XRNode);
- this.faceWrapTrs = this.faceWrap.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( this.faceWrap );
+ this.faceWrap = scene.createElement(xrFrameSystem.XRNode)
+ this.faceWrapTrs = this.faceWrap.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(this.faceWrap)
// 加载脸模
const face = await scene.assets.loadAsset({
type: 'gltf',
- assetId: `gltf-face`,
+ assetId: 'gltf-face',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/face.glb',
})
const faceElem = scene.createElement(xrFrameSystem.XRGLTF, {
- model: "gltf-face",
- position: `0 0 0`,
- scale: `1 1 1`,
- });
- const faceGLTF = faceElem.getComponent(xrFrameSystem.GLTF);
- this.faceElem = faceElem;
- this.faceGLTFTrs = faceElem.getComponent(xrFrameSystem.Transform);
- this.faceWrap.addChild(faceElem);
-
- for(const mesh of faceGLTF.meshes) {
+ model: 'gltf-face',
+ position: '0 0 0',
+ scale: '1 1 1',
+ })
+ const faceGLTF = faceElem.getComponent(xrFrameSystem.GLTF)
+ this.faceElem = faceElem
+ this.faceGLTFTrs = faceElem.getComponent(xrFrameSystem.Transform)
+ this.faceWrap.addChild(faceElem)
+
+ for (const mesh of faceGLTF.meshes) {
// 通过alphaMode 的 Setter 设置,或者写入renderState,但需要手动控制宏
- mesh.material.alphaMode = "BLEND";
- mesh.material.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 1, 1, 0.0));
+ mesh.material.alphaMode = 'BLEND'
+ mesh.material.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 1, 1, 0.0))
}
// 加载眼镜
const glasses = await scene.assets.loadAsset({
type: 'gltf',
- assetId: `gltf-glasses`,
+ assetId: 'gltf-glasses',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/glasses.glb',
})
const glassesElem = scene.createElement(xrFrameSystem.XRGLTF, {
- model: "gltf-glasses",
- position: `0 0 0`,
- scale: `1 1 1`,
- });
- const glassesGLTF = glassesElem.getComponent(xrFrameSystem.GLTF);
- this.glassesElem = glassesElem;
- this.glassesGLTFTrs = glassesElem.getComponent(xrFrameSystem.Transform);
- this.faceWrap.addChild(glassesElem);
-
+ model: 'gltf-glasses',
+ position: '0 0 0',
+ scale: '1 1 1',
+ })
+ const glassesGLTF = glassesElem.getComponent(xrFrameSystem.GLTF)
+ this.glassesElem = glassesElem
+ this.glassesGLTFTrs = glassesElem.getComponent(xrFrameSystem.Transform)
+ this.faceWrap.addChild(glassesElem)
},
loop() {
// console.log('loop')
@@ -191,31 +185,30 @@ Component({
const frame = this.session.getVKFrame(this.data.width, this.data.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
// 存在faceWrap,执行信息同步逻辑
if (this.faceWrap && this.wrapTransform) {
- const xrFrameSystem = wx.getXrFrameSystem();
-
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ const xrFrameSystem = wx.getXrFrameSystem()
+
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(this.wrapTransform);
- this.DT.transpose(this.DT2);
- this.faceWrapTrs.setLocalMatrix(this.DT2);
-
+ this.DT.setArray(this.wrapTransform)
+ this.DT.transpose(this.DT2)
+ this.faceWrapTrs.setLocalMatrix(this.DT2)
}
}
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/face-detect-3d/face-detect-3d.js b/miniprogram/packageAPI/pages/ar/face-detect-3d/face-detect-3d.js
index fbfa0d47..83f3c2e4 100644
--- a/miniprogram/packageAPI/pages/ar/face-detect-3d/face-detect-3d.js
+++ b/miniprogram/packageAPI/pages/ar/face-detect-3d/face-detect-3d.js
@@ -5,40 +5,40 @@ import xrFrameBehavior from '../behavior/behavior-xrframe'
const NEAR = 0.01
const FAR = 1000
-let loggerOnce = false;
+const loggerOnce = false
Component({
behaviors: [arBehavior, xrFrameBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.8, // canvas高度缩放值
- hintBoxList: [], // 显示提示盒子列表,
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.8, // canvas高度缩放值
+ hintBoxList: [], // 显示提示盒子列表,
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
@@ -46,7 +46,7 @@ Component({
init() {
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -58,7 +58,7 @@ Component({
},
version: 'v1',
gl: this.gl
- });
+ })
try {
session.start(err => {
@@ -68,164 +68,158 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// 开启三维识别
- session.update3DMode({open3d: true})
+ session.update3DMode({ open3d: true })
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
- console.log("addAnchor", anchors)
+ console.log('addAnchor', anchors)
})
- let preAnchorNumber = 0;
+ let preAnchorNumber = 0
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// console.log("updateAnchors", anchors);
// 遍历不同的识别目标
- for (let i = 0; i < anchors.length; i++ ) {
- const anchor = anchors[i];
+ for (let i = 0; i < anchors.length; i++) {
+ const anchor = anchors[i]
- let faceWrap = this.faceWrapMap[i];
+ let faceWrap = this.faceWrapMap[i]
if (!faceWrap) {
- this.initBindingNode(i);
+ this.initBindingNode(i)
- faceWrap = this.faceWrapMap[i];
+ faceWrap = this.faceWrapMap[i]
}
- const xrFrameSystem = wx.getXrFrameSystem();
+ const xrFrameSystem = wx.getXrFrameSystem()
// 更新显示状态
- this.updateHintBoxVisble(faceWrap.hintBoxList, true);
+ this.updateHintBoxVisble(faceWrap.hintBoxList, true)
if (faceWrap.faceGLTFTrs.visible !== true) {
- faceWrap.faceGLTFTrs.visible = true;
+ faceWrap.faceGLTFTrs.visible = true
}
// 执行信息同步逻辑
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(anchor.transform);
- this.DT.transpose(this.DT2);
- faceWrap.wrapTrs.setLocalMatrix(this.DT2);
+ this.DT.setArray(anchor.transform)
+ this.DT.transpose(this.DT2)
+ faceWrap.wrapTrs.setLocalMatrix(this.DT2)
// 更新提示点位置
- this.updateHintBoxPosition(faceWrap.hintBoxList, anchor.points3d);
+ this.updateHintBoxPosition(faceWrap.hintBoxList, anchor.points3d)
}
// 由于目前,减少识别目标不会触发remove事件,所以先通过数量判断处理隐藏
if (preAnchorNumber > anchors.length) {
// 遍历被隐藏的目标
- for (let i = preAnchorNumber - 1; i >= anchors.length; i-- ) {
- let faceWrap = this.faceWrapMap[i];
+ for (let i = preAnchorNumber - 1; i >= anchors.length; i--) {
+ const faceWrap = this.faceWrapMap[i]
if (faceWrap) {
- this.updateHintBoxVisble(faceWrap.hintBoxList, false);
+ this.updateHintBoxVisble(faceWrap.hintBoxList, false)
if (faceWrap.faceGLTFTrs.visible !== false) {
- faceWrap.faceGLTFTrs.visible = false;
+ faceWrap.faceGLTFTrs.visible = false
}
}
}
}
- preAnchorNumber = anchors.length;
+ preAnchorNumber = anchors.length
})
-
// VKSession removeAnchors
// 识别目标丢失时不断触发
session.on('removeAnchors', anchors => {
// console.log("removeAnchors");
-
+
if (preAnchorNumber !== 0) {
- for (let i = 0; i < preAnchorNumber; i++ ) {
- let faceWrap = this.faceWrapMap[i];
- if (faceWrap) {
- this.updateHintBoxVisble(faceWrap.hintBoxList, false);
- if (faceWrap.faceGLTFTrs.visible !== false) {
- faceWrap.faceGLTFTrs.visible = false;
- }
+ for (let i = 0; i < preAnchorNumber; i++) {
+ const faceWrap = this.faceWrapMap[i]
+ if (faceWrap) {
+ this.updateHintBoxVisble(faceWrap.hintBoxList, false)
+ if (faceWrap.faceGLTFTrs.visible !== false) {
+ faceWrap.faceGLTFTrs.visible = false
}
+ }
}
}
- preAnchorNumber = 0;
-
- });
-
+ preAnchorNumber = 0
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
- } catch(e) {
- console.error(e);
+ this.initLoop()
+ })
+ } catch (e) {
+ console.error(e)
}
-
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const scene = this.xrScene;
+ const scene = this.xrScene
// 缓存主相机
this.xrCameraMain = this.xrCamera
- this.xrCameraMainTrs = this.xrCameraTrs;
-
+ this.xrCameraMainTrs = this.xrCameraTrs
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// 加载脸模
this.faceGLTF = await scene.assets.loadAsset({
type: 'gltf',
- assetId: `gltf-face`,
+ assetId: 'gltf-face',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/face.glb',
})
// 初始化识别挂载点容器
- this.faceWrapMap = {};
-
+ this.faceWrapMap = {}
},
initBindingNode(index) {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
// 用于管理每一个挂载元素
- const wrapInfo = {};
+ const wrapInfo = {}
// === 初始挂载点 ===
- const faceWrap = scene.createElement(xrFrameSystem.XRNode);
- const faceWrapTrs = faceWrap.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( faceWrap );
+ const faceWrap = scene.createElement(xrFrameSystem.XRNode)
+ const faceWrapTrs = faceWrap.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(faceWrap)
- wrapInfo.wrapElem = faceWrap;
- wrapInfo.wrapTrs = faceWrapTrs;
+ wrapInfo.wrapElem = faceWrap
+ wrapInfo.wrapTrs = faceWrapTrs
const faceElem = scene.createElement(xrFrameSystem.XRGLTF, {
- model: "gltf-face",
- position: `0 0 0`,
- scale: `1 1 1`,
- });
- const faceGLTF = faceElem.getComponent(xrFrameSystem.GLTF);
- const faceGLTFTrs = faceElem.getComponent(xrFrameSystem.Transform);
- faceWrap.addChild(faceElem);
+ model: 'gltf-face',
+ position: '0 0 0',
+ scale: '1 1 1',
+ })
+ const faceGLTF = faceElem.getComponent(xrFrameSystem.GLTF)
+ const faceGLTFTrs = faceElem.getComponent(xrFrameSystem.Transform)
+ faceWrap.addChild(faceElem)
- wrapInfo.faceGLTFTrs = faceGLTFTrs;
+ wrapInfo.faceGLTFTrs = faceGLTFTrs
- for(const mesh of faceGLTF.meshes) {
+ for (const mesh of faceGLTF.meshes) {
// 通过alphaMode 的 Setter 设置,或者写入renderState,但需要手动控制宏
- mesh.material.alphaMode = "BLEND";
- mesh.material.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 1, 1, 0.4));
+ mesh.material.alphaMode = 'BLEND'
+ mesh.material.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1, 1, 1, 0.4))
}
// 加载提示点
- wrapInfo.hintBoxList = this.getHintBox(xrFrameSystem, scene, faceWrap);
+ wrapInfo.hintBoxList = this.getHintBox(xrFrameSystem, scene, faceWrap)
- this.faceWrapMap[index] = wrapInfo;
+ this.faceWrapMap[index] = wrapInfo
},
loop() {
// console.log('loop')
@@ -234,58 +228,57 @@ Component({
const frame = this.session.getVKFrame(this.data.width, this.data.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
-
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
},
getHintBox(xrFrameSystem, scene, wrap) {
// 初始化提示点
- const geometryHint = scene.assets.getAsset('geometry', 'sphere');
- const effectCube = scene.assets.getAsset('effect', 'standard');
- const boxScale = 0.03;
- const hintBoxList = [];
+ const geometryHint = scene.assets.getAsset('geometry', 'sphere')
+ const effectCube = scene.assets.getAsset('effect', 'standard')
+ const boxScale = 0.03
+ const hintBoxList = []
for (let i = 0; i < 106; i++) {
- const colorFloat = i / 106;
+ const colorFloat = i / 106
const el = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
+ position: '0 0 0',
scale: `${boxScale} ${boxScale} ${boxScale}`,
- });
- const elTrs = el.getComponent(xrFrameSystem.Transform);
- const mat = scene.createMaterial(effectCube);
-
- const colorR = 1.0 - colorFloat;
- mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0));
+ })
+ const elTrs = el.getComponent(xrFrameSystem.Transform)
+ const mat = scene.createMaterial(effectCube)
+
+ const colorR = 1.0 - colorFloat
+ mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0))
const mesh = el.addComponent(xrFrameSystem.Mesh, {
geometry: geometryHint,
material: mat,
- });
+ })
- wrap.addChild( el );
+ wrap.addChild(el)
// elTrs.visible = false;
-
- hintBoxList.push( elTrs );
+
+ hintBoxList.push(elTrs)
}
- return hintBoxList;
+ return hintBoxList
},
updateHintBoxPosition(hintBoxList, points3d) {
if (hintBoxList && hintBoxList.length > 0) {
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
- hintBox.position.x = points3d[i].x;
- hintBox.position.y = points3d[i].y;
- hintBox.position.z = points3d[i].z;
+ const hintBox = hintBoxList[i]
+ hintBox.position.x = points3d[i].x
+ hintBox.position.y = points3d[i].y
+ hintBox.position.z = points3d[i].z
}
}
},
@@ -294,12 +287,12 @@ Component({
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
+ const hintBox = hintBoxList[i]
if (hintBox.visible !== visible) {
- hintBox.visible = visible;
+ hintBox.visible = visible
}
}
}
}
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/face-detect/behavior.js b/miniprogram/packageAPI/pages/ar/face-detect/behavior.js
index 8b66a6cb..071f621e 100644
--- a/miniprogram/packageAPI/pages/ar/face-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/face-detect/behavior.js
@@ -1,202 +1,201 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- cameraPosition: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- face: {
- mode: 1
- }
- },
- cameraPosition: 1,
- version: 'v1',
- gl: this.gl
- })
-
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- this.data.anchor2DList = anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- }))
- })
- session.on('updateAnchors', anchors => {
- this.data.anchor2DList = []
- // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
- this.data.anchor2DList = this.data.anchor2DList.concat(anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })))
- })
- session.on('removeAnchors', anchors => {
- this.data.anchor2DList = []
- })
-
- this.setData({
- buttonDisable:false
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ cameraPosition: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ face: {
+ mode: 1
+ }
+ },
+ cameraPosition: 1,
+ version: 'v1',
+ gl: this.gl
+ })
+
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ this.data.anchor2DList = anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ }))
+ })
+ session.on('updateAnchors', anchors => {
+ this.data.anchor2DList = []
+ // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
+ this.data.anchor2DList = this.data.anchor2DList.concat(anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })))
+ })
+ session.on('removeAnchors', anchors => {
+ this.data.anchor2DList = []
+ })
+
+ this.setData({
+ buttonDisable: false
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/face-detect/face-detect.js b/miniprogram/packageAPI/pages/ar/face-detect/face-detect.js
index 4c11bedd..ebcd9a0f 100644
--- a/miniprogram/packageAPI/pages/ar/face-detect/face-detect.js
+++ b/miniprogram/packageAPI/pages/ar/face-detect/face-detect.js
@@ -4,70 +4,69 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-//顶点着色器
-var VSHADER_SOURCE = '' +
- 'attribute vec4 a_Position;\n' + //声明attribute变量a_Position,用来存放顶点位置信息
+// 顶点着色器
+const VSHADER_SOURCE = '' +
+ 'attribute vec4 a_Position;\n' + // 声明attribute变量a_Position,用来存放顶点位置信息
'void main(){\n' +
- ' gl_Position = a_Position;\n' + //将顶点坐标赋值给顶点着色器内置变量gl_Position
- ' gl_PointSize = 4.0;\n' + //设置顶点大小
+ ' gl_Position = a_Position;\n' + // 将顶点坐标赋值给顶点着色器内置变量gl_Position
+ ' gl_PointSize = 4.0;\n' + // 设置顶点大小
'}\n'
-//片元着色器
-var FSHADER_SOURCE = '' +
+// 片元着色器
+const FSHADER_SOURCE = '' +
'#ifdef GL_ES\n' +
' precision mediump float;\n' + // 设置精度
'#endif\n' +
- 'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
+ 'varying vec4 v_Color;\n' + // 声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
'void main(){\n' +
- ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + //计算像素距离中心点的距离
- ' if(d < 0.5) {\n' + //距离大于0.5放弃片元,小于0.5保留片元
+ ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + // 计算像素距离中心点的距离
+ ' if(d < 0.5) {\n' + // 距离大于0.5放弃片元,小于0.5保留片元
' gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n' +
' } else { discard; }\n' +
'}\n'
-
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
- //创建顶点着色器对象
- var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
- //创建片元着色器对象
- var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
+ // 创建顶点着色器对象
+ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
+ // 创建片元着色器对象
+ const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
if (!vertexShader || !fragmentShader) {
return null
}
- //创建程序对象program
- var program = gl.createProgram()
+ // 创建程序对象program
+ const program = gl.createProgram()
if (!gl.createProgram()) {
return null
}
- //分配顶点着色器和片元着色器到program
+ // 分配顶点着色器和片元着色器到program
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
- //链接program
+ // 链接program
gl.linkProgram(program)
- //检查程序对象是否连接成功
- var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
+ // 检查程序对象是否连接成功
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS)
if (!linked) {
- var error = gl.getProgramInfoLog(program)
+ const error = gl.getProgramInfoLog(program)
console.log('程序对象连接失败: ' + error)
gl.deleteProgram(program)
gl.deleteShader(fragmentShader)
gl.deleteShader(vertexShader)
return null
}
- //返回程序program对象
+ // 返回程序program对象
initShadersDone = true
return program
}
function loadShader(gl, type, source) {
// 创建顶点着色器对象
- var shader = gl.createShader(type)
+ const shader = gl.createShader(type)
if (shader == null) {
console.log('创建着色器失败')
return null
@@ -80,9 +79,9 @@ function loadShader(gl, type, source) {
gl.compileShader(shader)
// 检查顶是否编译成功
- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!compiled) {
- var error = gl.getShaderInfoLog(shader)
+ const error = gl.getShaderInfoLog(shader)
console.log('编译着色器失败: ' + error)
gl.deleteShader(shader)
return null
@@ -91,9 +90,8 @@ function loadShader(gl, type, source) {
return shader
}
-//初始化顶点坐标和顶点颜色
+// 初始化顶点坐标和顶点颜色
function initVertexBuffers(gl, anchor2DList) {
-
const flattenPoints = []
anchor2DList.forEach(anchor => {
anchor.points.forEach(point => {
@@ -105,23 +103,23 @@ function initVertexBuffers(gl, anchor2DList) {
})
})
- var vertices = new Float32Array(flattenPoints)
- var n = flattenPoints.length / 2
+ const vertices = new Float32Array(flattenPoints)
+ const n = flattenPoints.length / 2
- //创建缓冲区对象
- var buffer = gl.createBuffer()
- //将顶点坐标和顶点颜色信息写入缓冲区对象
+ // 创建缓冲区对象
+ const buffer = gl.createBuffer()
+ // 将顶点坐标和顶点颜色信息写入缓冲区对象
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
- //获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
- var a_Position = gl.getAttribLocation(gl.program, 'a_Position')
+ // 获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
+ const a_Position = gl.getAttribLocation(gl.program, 'a_Position')
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)
return n
}
-var EDGE_VSHADER_SOURCE =
+const EDGE_VSHADER_SOURCE =
`
attribute vec2 aPosition;
varying vec2 posJudge;
@@ -132,7 +130,7 @@ var EDGE_VSHADER_SOURCE =
}
`
-var EDGE_FSHADER_SOURCE =
+const EDGE_FSHADER_SOURCE =
`
precision highp float;
uniform vec2 rightTopPoint;
@@ -162,48 +160,47 @@ var EDGE_FSHADER_SOURCE =
`
function initRectEdgeBuffer(gl, x, y, width, height) {
- let shaderProgram = gl.program;
- let centerX = x * 2 - 1 + width;
- let centerY = -1 * (y * 2 - 1) - height;
- let right = width;
- let top = height;
- var vertices = [
+ const shaderProgram = gl.program
+ const centerX = x * 2 - 1 + width
+ const centerY = -1 * (y * 2 - 1) - height
+ const right = width
+ const top = height
+ const vertices = [
-1.0, 1.0,
-1.0, -1.0,
1.0, 1.0,
1.0, -1.0
- ];
+ ]
- var vertexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
- var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');
- gl.enableVertexAttribArray(aPosition);
- gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
+ const vertexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
+ const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition')
+ gl.enableVertexAttribArray(aPosition)
+ gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
-
- var rightTop = [
+ const rightTop = [
right, top
- ];
- var rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint');
- gl.uniform2fv(rightTopLoc, rightTop);
+ ]
+ const rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint')
+ gl.uniform2fv(rightTopLoc, rightTop)
- var centerPoint = [
+ const centerPoint = [
centerX, centerY
- ];
- var centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint');
- gl.uniform2fv(centerPointLoc, centerPoint);
+ ]
+ const centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint')
+ gl.uniform2fv(centerPointLoc, centerPoint)
- var length = vertices.length / 2;
+ const length = vertices.length / 2
- return length;
+ return length
}
function onDrawRectEdge(gl, x, y, width, height) {
width = Math.round(width * 100) / 100
height = Math.round(height * 100) / 100
- var n = initRectEdgeBuffer(gl, x, y, width, height);
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
+ const n = initRectEdgeBuffer(gl, x, y, width, height)
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, n)
}
Component({
@@ -219,15 +216,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -245,19 +242,19 @@ Component({
init() {
this.initGL()
},
- switchCamera(event){
- if(this.session.config){
+ switchCamera(event) {
+ if (this.session.config) {
const config = this.session.config
- let pos = Number(event.currentTarget.dataset.value)
+ const pos = Number(event.currentTarget.dataset.value)
config.cameraPosition = pos
this.session.config = config
this.setData({
- cameraPosition:event.currentTarget.dataset.value
+ cameraPosition: event.currentTarget.dataset.value
})
}
},
render(frame) {
- var gl = this.gl
+ const gl = this.gl
this.renderGL(frame)
@@ -281,7 +278,7 @@ Component({
const anchor2DList = this.data.anchor2DList
if (!anchor2DList || anchor2DList.length <= 0) {
- return
+
} else {
if (!initShadersDone) {
this.vertexProgram = initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)
@@ -295,19 +292,19 @@ Component({
gl.useProgram(this.vertexProgram)
gl.program = this.vertexProgram
- //初始化顶点坐标和顶点颜色
- var n = initVertexBuffers(gl, anchor2DList)
+ // 初始化顶点坐标和顶点颜色
+ const n = initVertexBuffers(gl, anchor2DList)
- //绘制点
+ // 绘制点
gl.drawArrays(gl.POINTS, 0, n)
gl.useProgram(this.rectEdgeProgram)
gl.program = this.rectEdgeProgram
- for (var i = 0; i < anchor2DList.length; i++) {
+ for (let i = 0; i < anchor2DList.length; i++) {
onDrawRectEdge(gl, anchor2DList[i].origin.x, anchor2DList[i].origin.y, anchor2DList[i].size.width, anchor2DList[i].size.height)
}
}
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/face-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/face-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/face-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/face-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js
index e30f7bf0..f5ac2062 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js
@@ -2,24 +2,25 @@ import { loadPly } from './loaders/ply/ply-loader'
import { loadSplat } from './loaders/splat/splat-loader'
import CameraWebGL from './webgl2/camera-webGL'
import CubeInstanceWebGL from './webgl2/cubeInstance-webGL'
-import SplatWebGL, { SplatRenderTexture} from './webgl2/splat-webGL'
+import SplatWebGL, { SplatRenderTexture } from './webgl2/splat-webGL'
import YUVRenderWebGL from './webgl2/yuv-webGL'
import * as glMatrix from './util/gl-matrix-min'
+
const { mat4 } = glMatrix
// VK 投影矩阵参数定义
const NEAR = 0.01
const FAR = 1000
-const renderScale = 1;
+const renderScale = 1
Component({
behaviors: [],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 1, // canvas高度缩放值
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 1, // canvas高度缩放值
renderByXRFrame: false, // 是否使用 xr-frame渲染
renderByWebGL2: true, // 是否使用WebGL2渲染
workerOn: true,
@@ -30,51 +31,50 @@ Component({
* 生命周期函数--监听页面加载
*/
attached() {
- console.log("页面attached")
+ console.log('页面attached')
console.log('[worker] 排序 worker 的创建')
- this.worker = wx.createWorker('workers/gaussianSplatting/index.js');
- console.log('[worker] 具体 worker', this.worker);
-
+ this.worker = wx.createWorker('workers/gaussianSplatting/index.js')
+ console.log('[worker] 具体 worker', this.worker)
},
detached() {
- console.log("页面detached")
+ console.log('页面detached')
if (this.worker) this.worker.terminate()
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
},
},
methods: {
onReady() {
// 获取canvas
wx.createSelectorQuery()
- .select('#canvas')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio;
- const width = info.windowWidth * this.data.widthScale * pixelRatio * renderScale;
- const height = info.windowHeight * this.data.heightScale * pixelRatio * renderScale;
- // 存在 webgl Canvas的情况下,写入大小
- if (this.canvas) {
- this.canvas.width = width;
- this.canvas.height = height;
- }
- console.log(`canvas size: width = ${width} , height = ${height}`)
- console.log(`window size: width = ${info.windowWidth} , height = ${info.windowHeight}`)
-
- this.setData({
- width: width,
- height: height,
- });
-
- // 页面自定义初始化
- if (this.init) this.init()
+ .select('#canvas')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const width = info.windowWidth * this.data.widthScale * pixelRatio * renderScale
+ const height = info.windowHeight * this.data.heightScale * pixelRatio * renderScale
+ // 存在 webgl Canvas的情况下,写入大小
+ if (this.canvas) {
+ this.canvas.width = width
+ this.canvas.height = height
+ }
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ console.log(`window size: width = ${info.windowWidth} , height = ${info.windowHeight}`)
+
+ this.setData({
+ width,
+ height,
})
+
+ // 页面自定义初始化
+ if (this.init) this.init()
+ })
},
// 对应案例的初始化逻辑,由统一的 arBehavior 触发
init() {
@@ -82,12 +82,12 @@ Component({
// 注册 各类渲染器
if (this.data.renderByWebGL2) {
- this.initWebGL2();
+ this.initWebGL2()
} else if (this.data.renderByXRFrame) {
- this.initXRFrame();
+ this.initXRFrame()
}
-
- this.initVK();
+
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -99,7 +99,7 @@ Component({
},
version: 'v2',
gl: this.gl
- });
+ })
session.start(err => {
if (err) return console.error('VK error: ', err)
@@ -116,54 +116,54 @@ Component({
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
})
-
+
// VKSession removeAnchors
session.on('removeAnchors', anchors => {
// console.log('removeAnchors', anchors)
- });
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
+ this.initLoop()
+ })
},
initLoop() {
// 限制调用帧率,暂时去掉
- let fps = 30
- let fpsInterval = 1000 / fps
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
- const session = this.session;
+ const session = this.session
// 逐帧渲染
const onFrame = timestamp => {
- try {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- this.requestRender();
- }
- } catch(e) {
- console.error(e);
+ try {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ this.requestRender()
}
- session.requestAnimationFrame(onFrame)
+ } catch (e) {
+ console.error(e)
+ }
+ session.requestAnimationFrame(onFrame)
}
session.requestAnimationFrame(onFrame)
},
- initPLY(id){
+ initPLY(id) {
console.log('== PLY Init start ==')
- const host = 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo';
+ const host = 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo'
// const host = 'http://127.0.0.1:8030'
// const host = 'http://10.9.169.133:8030'
- let type;
+ let type
// 加载 splat
- type = 'splat';
- const pcSrc = `${host}/splat/${id}.splat`;
+ type = 'splat'
+ const pcSrc = `${host}/splat/${id}.splat`
console.log('splat src', pcSrc)
@@ -171,66 +171,66 @@ Component({
url: pcSrc,
timeout: 200000,
success: (res) => {
- console.log("downloadFile 下载回调", res);
+ console.log('downloadFile 下载回调', res)
- const filePath = res.tempFilePath;
+ const filePath = res.tempFilePath
const fs = wx.getFileSystemManager()
/**
* 因为微信读文件,最大只能读100MB的,所以需要分块读取。
*/
- const fd = fs.openSync({ filePath: filePath })
- const stats = fs.fstatSync({fd: fd})
- console.log('fd stats', stats);
- let size = stats.size;
+ const fd = fs.openSync({ filePath })
+ const stats = fs.fstatSync({ fd })
+ console.log('fd stats', stats)
+ let size = stats.size
if (size > 0) {
- const buffer = new ArrayBuffer(size);
- const viewU8 = new Uint8Array(buffer);
- let offset = 0;
- let uindex = 0;
+ const buffer = new ArrayBuffer(size)
+ const viewU8 = new Uint8Array(buffer)
+ let offset = 0
+ let uindex = 0
while (size > 0) {
- const chunkSize = Math.min(size, 100 * 1024 * 1024/* 100MB */);
+ const chunkSize = Math.min(size, 100 * 1024 * 1024/* 100MB */)
- const res = fs.readFileSync(
+ const res = fs.readFileSync(
filePath,
undefined,
offset,
chunkSize,
- );
- const resU8 = new Uint8Array(res);
- viewU8.set(new Uint8Array(res), uindex);
- uindex += resU8.length;
+ )
+ const resU8 = new Uint8Array(res)
+ viewU8.set(new Uint8Array(res), uindex)
+ uindex += resU8.length
// console.log('res', res)
// console.log('uindex', uindex);
// console.log('offset', offset);
// console.log('chunkSize', chunkSize)
- offset += chunkSize;
- size -= chunkSize;
+ offset += chunkSize
+ size -= chunkSize
}
- fs.close({ fd });
+ fs.close({ fd })
// console.log('buffer', buffer)
- let info;
+ let info
- const maxGaussians = this.data.maxGaussians;
+ const maxGaussians = this.data.maxGaussians
switch (type) {
case 'ply':
- info = loadPly(buffer, maxGaussians);
- console.log("plyLoader return", info);
- break;
+ info = loadPly(buffer, maxGaussians)
+ console.log('plyLoader return', info)
+ break
case 'splat':
- info = loadSplat(buffer, maxGaussians);
- console.log("splatLoader return", info);
- break;
+ info = loadSplat(buffer, maxGaussians)
+ console.log('splatLoader return', info)
+ break
}
// 提供渲染的高斯球数
- const renderCount = this.renderCount = info.count;
+ const renderCount = this.renderCount = info.count
// 全部用 f32 存储
// this.sabPositions = wx.createSharedArrayBuffer(renderCount * 4 * 3)
@@ -248,10 +248,9 @@ Component({
// sabCov3Da: this.sabCov3Da,
// sabCov3Db: this.sabCov3Db,
// sabcolors: this.sabcolors,
- });
-
+ })
} else {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
@@ -261,7 +260,7 @@ Component({
}
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
@@ -269,7 +268,7 @@ Component({
})
console.error(res)
}
- });
+ })
},
initWorker(plyInfo, config) {
console.log('== Worker Init start ==')
@@ -280,15 +279,13 @@ Component({
// worker 初始化 回调
console.log('[Worker callback] gaussianSplatting init callBack', res)
- this.camera.isWorkerInit = true;
- this.camera.updateByVK();
-
-
+ this.camera.isWorkerInit = true
+ this.camera.updateByVK()
} else if (res.type === 'execFunc_sort') {
// worker 排序 回调
// console.log(res)
- this.camera.isWorkerSorting = false;
+ this.camera.isWorkerSorting = false
const data = res.result.data
@@ -306,13 +303,12 @@ Component({
// const cov3Da = new Float32Array(this.sabCov3Da.buffer);
// const cov3Db = new Float32Array(this.sabCov3Db.buffer);
// const colors = new Float32Array(this.sabcolors.buffer);
-
- const positions = new Float32Array(data.positions);
- const opacities = new Float32Array(data.opacities);
- const cov3Da = new Float32Array(data.cov3Da);
- const cov3Db = new Float32Array(data.cov3Db);
- const colors = new Float32Array(data.colors);
+ const positions = new Float32Array(data.positions)
+ const opacities = new Float32Array(data.opacities)
+ const cov3Da = new Float32Array(data.cov3Da)
+ const cov3Db = new Float32Array(data.cov3Db)
+ const colors = new Float32Array(data.colors)
updateBuffer(this.splat.buffers.center, positions)
updateBuffer(this.splat.buffers.opacity, opacities)
@@ -321,7 +317,7 @@ Component({
updateBuffer(this.splat.buffers.color, colors)
// 设定绘制的高斯球数量
- this.gaussiansCount = data.gaussiansCount;
+ this.gaussiansCount = data.gaussiansCount
const end = new Date().getTime()
// const sortTime = `${((end - start)/1000).toFixed(3)}s`
@@ -342,14 +338,14 @@ Component({
// 后续为 webGL2 相关,为了方便开发,先放在一起
initWebGL2() {
console.log('== InitWebGL2 start ==')
- const gl = this.gl = this.canvas.getContext('webgl2');
- console.log('webgl2 context', gl);
+ const gl = this.gl = this.canvas.getContext('webgl2')
+ console.log('webgl2 context', gl)
// Setup Camera
const cameraParameters = {
up: [0, 1.0, 0.0],
target: [0, 0, 0],
- camera: [Math.PI/2, Math.PI/2, 10], // theta phi radius
+ camera: [Math.PI / 2, Math.PI / 2, 10], // theta phi radius
}
this.camera = new CameraWebGL(gl, this.worker, cameraParameters)
@@ -357,44 +353,43 @@ Component({
this.cubeInstance = new CubeInstanceWebGL(gl)
// Setup Splat
- this.initSplat(gl);
+ this.initSplat(gl)
// Setup YUV
- this.initYUV(gl);
-
+ this.initYUV(gl)
},
// Gaussian Splat数据
initSplat(gl) {
// 初始化 splat 绘制到的 renderTexture
- this.splatRT = new SplatRenderTexture(gl);
+ this.splatRT = new SplatRenderTexture(gl)
// 初始化 splat 渲染器
- this.splat = new SplatWebGL(gl);
+ this.splat = new SplatWebGL(gl)
},
// VK 摄像机数据渲染
- initYUV(gl){
- this.YUVRender = new YUVRenderWebGL(gl);
+ initYUV(gl) {
+ this.YUVRender = new YUVRenderWebGL(gl)
},
requestRender() {
// console.log('request render')
// 限帧
- let now = Date.now()
- const last = this.lastRenderTime || 0;
+ const now = Date.now()
+ const last = this.lastRenderTime || 0
const mill = now - last
if (mill < 30) {
return
}
this.lastRenderTime = now
-
- const gl = this.gl;
+
+ const gl = this.gl
// Clear State
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.clearColor(0.8, 0.8, 0.8, 1.0);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+ gl.clearColor(0.8, 0.8, 0.8, 1.0)
// Clear
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
// 先关掉深度测试
gl.disable(gl.DEPTH_TEST)
@@ -403,47 +398,47 @@ Component({
const frame = this.session.getVKFrame(this.canvas.width, this.canvas.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 获取 VKCamera
const VKCamera = frame.camera
// 相机
if (VKCamera) {
- const viewMatrix = VKCamera.viewMatrix;
- const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR);
+ const viewMatrix = VKCamera.viewMatrix
+ const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR)
// 视图矩阵
- this.camera.viewMatrix = viewMatrix;
+ this.camera.viewMatrix = viewMatrix
// 投影矩阵
- this.camera.projMatrix = projectionMatrix;
- this.camera.updateByVK();
+ this.camera.projMatrix = projectionMatrix
+ this.camera.updateByVK()
}
// Draw YUV
- this.drawYUV(gl, frame);
+ this.drawYUV(gl, frame)
// Draw Splat
- this.drawSplat(gl);
+ this.drawSplat(gl)
// 恢复渲染状态
// cullFace
// gl.enable(gl.CULL_FACE);
// gl.cullFace(gl.BACK);
- gl.disable(gl.CULL_FACE);
+ gl.disable(gl.CULL_FACE)
// gl.cullFace(gl.BACK);
// 深度测试
gl.enable(gl.DEPTH_TEST)
// drawCubeMesh
- const projMatrix = this.camera.projMatrix;
- const viewMatrix = this.camera.viewMatrix;
- let modelMatrix = mat4.create();
+ const projMatrix = this.camera.projMatrix
+ const viewMatrix = this.camera.viewMatrix
+ let modelMatrix = mat4.create()
// hintTest Info
if (!this.isPlaced) {
const hitTestRes = this.session.hitTest(0.5, 0.5)
if (hitTestRes.length) {
// hitTestRes 返回 transform 为列主序矩阵
- const hintScale = 0.01;
+ const hintScale = 0.01
mat4.scale(modelMatrix, hitTestRes[0].transform, [hintScale * 3, hintScale, hintScale * 3])
} else {
// 放在很远,相当于移除屏幕
@@ -455,11 +450,10 @@ Component({
]
}
} else {
- modelMatrix = this.hintModelMatrix;
+ modelMatrix = this.hintModelMatrix
}
this.drawCubeMesh(gl, projMatrix, viewMatrix, modelMatrix)
-
},
drawYUV(gl, frame) {
// 获取 VKFrame 信息
@@ -470,42 +464,41 @@ Component({
const displayTransform = frame.getDisplayTransform()
if (!yTexture || !uvTexture) {
- return;
+ return
}
// 进行 YUV 准备
const yuvRender = this.YUVRender
-
+
// YUV 需要绘制背面
- gl.disable(gl.CULL_FACE);
+ gl.disable(gl.CULL_FACE)
// 先将YUV绘制到主屏
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
- gl.useProgram(yuvRender.programInfo.program);
+ gl.useProgram(yuvRender.programInfo.program)
// VAO
- gl.bindVertexArray(yuvRender.vao);
+ gl.bindVertexArray(yuvRender.vao)
// position
- gl.bindBuffer(gl.ARRAY_BUFFER, yuvRender.buffers.position);
- gl.vertexAttribPointer(yuvRender.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(yuvRender.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, yuvRender.buffers.position)
+ gl.vertexAttribPointer(yuvRender.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(yuvRender.programInfo.attribLocations.vertexPosition)
// texCoord
- gl.bindBuffer(gl.ARRAY_BUFFER, yuvRender.buffers.texCoord);
- gl.vertexAttribPointer(yuvRender.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(yuvRender.programInfo.attribLocations.vertexTexcoord);
+ gl.bindBuffer(gl.ARRAY_BUFFER, yuvRender.buffers.texCoord)
+ gl.vertexAttribPointer(yuvRender.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(yuvRender.programInfo.attribLocations.vertexTexcoord)
// indices
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, yuvRender.buffers.indices);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, yuvRender.buffers.indices)
// displayTransform
gl.uniformMatrix3fv(yuvRender.programInfo.uniformLocations.displayTransform, false, displayTransform)
-
- // 设置使用的纹理单元
- gl.uniform1i(yuvRender.programInfo.uniformLocations.yTexture, 1); // 纹理单元 1
- gl.uniform1i(yuvRender.programInfo.uniformLocations.uvTexture, 2); // 纹理单元 2
+ // 设置使用的纹理单元
+ gl.uniform1i(yuvRender.programInfo.uniformLocations.yTexture, 1) // 纹理单元 1
+ gl.uniform1i(yuvRender.programInfo.uniformLocations.uvTexture, 2) // 纹理单元 2
// UNPACK_FLIP_Y_WEBGL
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
// 设定 Y、UV 纹理到纹理单元
gl.activeTexture(gl.TEXTURE1)
@@ -514,56 +507,54 @@ Component({
gl.bindTexture(gl.TEXTURE_2D, uvTexture)
// draw RenderTexture
- gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
+ gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
// 恢复 Cull_face
- gl.enable(gl.CULL_FACE);
-
+ gl.enable(gl.CULL_FACE)
},
drawCubeMesh(gl, projMatrix, viewMatrix, modelMatrix) {
// mesh
const meshCube = this.cubeInstance
// Tell WebGL to use our program when drawing
- gl.useProgram(meshCube.programInfo.program);
+ gl.useProgram(meshCube.programInfo.program)
// VAO
- gl.bindVertexArray(meshCube.vao);
+ gl.bindVertexArray(meshCube.vao)
// mesh position
- gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.positionBuffer);
- gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.positionBuffer)
+ gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexPosition)
// mesh color
- gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.colorBuffer);
- gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexColor, 4, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexColor);
+ gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.colorBuffer)
+ gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexColor, 4, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexColor)
// Tell WebGL which indices to use to index the vertices
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, meshCube.indices);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, meshCube.indices)
// Set the shader uniforms
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.projectionMatrix,
false,
projMatrix
- );
+ )
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.viewMatrix,
false,
viewMatrix
- );
+ )
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.modelMatrix,
false,
modelMatrix
- );
+ )
// draw
- const vertexCount = 36;
- const type = gl.UNSIGNED_SHORT;
- const offset = 0;
- gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
+ const vertexCount = 36
+ const type = gl.UNSIGNED_SHORT
+ const offset = 0
+ gl.drawElements(gl.TRIANGLES, vertexCount, type, offset)
},
drawSplat(gl) {
-
// 通用准备
const cam = this.camera
@@ -572,10 +563,10 @@ Component({
const splatRTFrameBuffer = this.splatRT.frameBuffer
- gl.bindFramebuffer(gl.FRAMEBUFFER, splatRTFrameBuffer);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, splatRTFrameBuffer)
- gl.clearColor(0, 0, 0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.clearColor(0, 0, 0, 0.0)
+ gl.clear(gl.COLOR_BUFFER_BIT)
// Set Splat state
gl.disable(gl.DEPTH_TEST)
@@ -586,11 +577,11 @@ Component({
// 开启 Splat 绘制流程
const splat = this.splat
- const program = splat.program;
+ const program = splat.program
// Use Program
- gl.useProgram(program);
+ gl.useProgram(program)
// VAO
- gl.bindVertexArray(splat.vao);
+ gl.bindVertexArray(splat.vao)
// Original implementation parameters
const canvasWidth = gl.canvas.width
@@ -611,24 +602,24 @@ Component({
gl.uniformMatrix4fv(gl.getUniformLocation(program, 'modelViewProjectMatrix'), false, cam.mvpm)
// Draw Splat
- gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, this.gaussiansCount);
+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, this.gaussiansCount)
// 最后将RT绘制 到 主屏
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
- gl.useProgram(splatRT.programInfo.program);
+ gl.useProgram(splatRT.programInfo.program)
// VAO
- gl.bindVertexArray(splatRT.vao);
+ gl.bindVertexArray(splatRT.vao)
// position
- gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.position);
- gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.position)
+ gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexPosition)
// texCoord
- gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.texCoord);
- gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexTexcoord);
+ gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.texCoord)
+ gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexTexcoord)
// indices
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, splatRT.buffers.indices);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, splatRT.buffers.indices)
gl.uniform1i(splatRT.programInfo.attribLocations.uSplat, 0) // 纹理单元0
@@ -641,13 +632,12 @@ Component({
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
// draw RenderTexture
- gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
-
+ gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
},
onTapControl(e) {
- const dataSet = e.target.dataset;
-
- const id = dataSet.id;
+ const dataSet = e.target.dataset
+
+ const id = dataSet.id
// hintTest Info
const hitTestRes = this.session.hitTest(0.5, 0.5)
@@ -655,81 +645,81 @@ Component({
// 命中才进行后续的具体加载
// hitTestRes 返回 transform 为列主序矩阵
- let splatModelMatrix = mat4.create();
- let modelMatrixLocal = mat4.create();
- let modelMatrixT = mat4.create();
- let modelMatrixR = mat4.create();
- let modelMatrixS = mat4.create();
- let splatScale = 0.2;
- let splatRotationAngle = 0;
- let splatRotationFlag = [0, 1, 0];
- let splatTranslate = [0, 0, 0];
+ const splatModelMatrix = mat4.create()
+ const modelMatrixLocal = mat4.create()
+ const modelMatrixT = mat4.create()
+ const modelMatrixR = mat4.create()
+ const modelMatrixS = mat4.create()
+ let splatScale = 0.2
+ let splatRotationAngle = 0
+ let splatRotationFlag = [0, 1, 0]
+ let splatTranslate = [0, 0, 0]
// 针对不同场景设置不同的 世界矩阵
- switch(id) {
+ switch (id) {
case 'room':
- splatScale = 0.6;
- splatTranslate = [0, -1, 0];
- splatRotationAngle = - Math.PI / 180 * 26;
- splatRotationFlag = [1, 0, 0];
- break;
+ splatScale = 0.6
+ splatTranslate = [0, -1, 0]
+ splatRotationAngle = -Math.PI / 180 * 26
+ splatRotationFlag = [1, 0, 0]
+ break
case 'garden':
- splatScale = 0.6;
- splatTranslate = [0, -2, 0];
- splatRotationAngle = - Math.PI / 180 * 20;
- splatRotationFlag = [1, 0, 0];
- break;
+ splatScale = 0.6
+ splatTranslate = [0, -2, 0]
+ splatRotationAngle = -Math.PI / 180 * 20
+ splatRotationFlag = [1, 0, 0]
+ break
case 'stump':
- splatScale = 0.6;
- splatTranslate = [0, 0, 0];
- break;
+ splatScale = 0.6
+ splatTranslate = [0, 0, 0]
+ break
case 'oneflower':
- splatScale = 0.2;
- splatTranslate = [-0.5, -2, -4];
- splatRotationAngle = - Math.PI / 180 * 40;
- splatRotationFlag = [1, 0, 0];
- break;
+ splatScale = 0.2
+ splatTranslate = [-0.5, -2, -4]
+ splatRotationAngle = -Math.PI / 180 * 40
+ splatRotationFlag = [1, 0, 0]
+ break
case 'usj':
- splatTranslate = [0, 1, 0];
- break;
+ splatTranslate = [0, 1, 0]
+ break
case 'sakura':
- splatTranslate = [-1.6, 0, -1];
- break;
+ splatTranslate = [-1.6, 0, -1]
+ break
case '0517cruch':
- splatScale = 0.5;
- splatTranslate = [0, 0, 0];
- break;
+ splatScale = 0.5
+ splatTranslate = [0, 0, 0]
+ break
default:
- break;
+ break
}
mat4.scale(modelMatrixS, mat4.create(), [splatScale, splatScale, splatScale])
mat4.rotate(modelMatrixR, modelMatrixS, splatRotationAngle, splatRotationFlag)
mat4.translate(modelMatrixT, modelMatrixR, splatTranslate)
- mat4.copy(modelMatrixLocal, modelMatrixT);
+ mat4.copy(modelMatrixLocal, modelMatrixT)
// Y轴反转矩阵
- const fixMatrix = mat4.create();
+ const fixMatrix = mat4.create()
mat4.rotate(fixMatrix, mat4.create(), Math.PI, [0, 0, 1])
// 本地矩阵
- const modelMatrixLocalFix = mat4.create();
- mat4.multiply(modelMatrixLocalFix, fixMatrix, modelMatrixLocal);
+ const modelMatrixLocalFix = mat4.create()
+ mat4.multiply(modelMatrixLocalFix, fixMatrix, modelMatrixLocal)
// 世界矩阵
- mat4.multiply(splatModelMatrix, hitTestRes[0].transform, modelMatrixLocalFix);
+ mat4.multiply(splatModelMatrix, hitTestRes[0].transform, modelMatrixLocalFix)
- this.camera.modelMatrix = splatModelMatrix;
+ this.camera.modelMatrix = splatModelMatrix
// locak Hint
- const hintModelMatrix = mat4.create();
- const hintScale = 0.01;
+ const hintModelMatrix = mat4.create()
+ const hintScale = 0.01
mat4.scale(hintModelMatrix, hitTestRes[0].transform, [hintScale * 3, hintScale, hintScale * 3])
- this.hintModelMatrix = hintModelMatrix;
- this.isPlaced = true;
+ this.hintModelMatrix = hintModelMatrix
+ this.isPlaced = true
// 开始处理 ply 资源
- this.initPLY(id);
+ this.initPLY(id)
}
},
changeMaxGaussianCount(e) {
@@ -737,18 +727,16 @@ Component({
maxGaussians: e.detail.value
})
- console.log('slider maxGaussians:', this.data.maxGaussians);
+ console.log('slider maxGaussians:', this.data.maxGaussians)
},
switchWorker(e) {
this.setData({
workerOn: e.detail.value
})
- this.camera.setWorkerOn(this.data.workerOn);
+ this.camera.setWorkerOn(this.data.workerOn)
- console.log('switch WorkerOn:', this.data.workerOn);
+ console.log('switch WorkerOn:', this.data.workerOn)
}
},
})
-
-
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js
index 7e8ed754..3d5a1e31 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js
@@ -2,21 +2,22 @@ import { loadPly } from './loaders/ply/ply-loader'
import { loadSplat } from './loaders/splat/splat-loader'
import CameraWebGL from './webgl2/camera-webGL'
import CubeInstanceWebGL from './webgl2/cubeInstance-webGL'
-import SplatWebGL, { SplatRenderTexture} from './webgl2/splat-webGL'
+import SplatWebGL, { SplatRenderTexture } from './webgl2/splat-webGL'
import * as glMatrix from './util/gl-matrix-min'
+
const { mat4 } = glMatrix
-const renderScale = 1;
+const renderScale = 1
-const baseMatrix = mat4.create();
+const baseMatrix = mat4.create()
Component({
behaviors: [],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 1, // canvas高度缩放值
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 1, // canvas高度缩放值
renderByXRFrame: false, // 是否使用 xr-frame渲染
renderByWebGL2: true, // 是否使用WebGL2渲染
workerOn: true,
@@ -27,51 +28,50 @@ Component({
* 生命周期函数--监听页面加载
*/
attached() {
- console.log("页面attached")
+ console.log('页面attached')
console.log('[worker] 排序 worker 的创建')
- this.worker = wx.createWorker('workers/gaussianSplatting/index.js');
- console.log('[worker] 具体 worker', this.worker);
-
+ this.worker = wx.createWorker('workers/gaussianSplatting/index.js')
+ console.log('[worker] 具体 worker', this.worker)
},
detached() {
- console.log("页面detached")
+ console.log('页面detached')
if (this.worker) this.worker.terminate()
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
},
},
methods: {
onReady() {
// 获取canvas
wx.createSelectorQuery()
- .select('#canvas')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio;
- const width = info.windowWidth * this.data.widthScale * pixelRatio * renderScale;
- const height = info.windowHeight * this.data.heightScale * pixelRatio * renderScale;
- // 存在 webgl Canvas的情况下,写入大小
- if (this.canvas) {
- this.canvas.width = width;
- this.canvas.height = height;
- }
- console.log(`canvas size: width = ${width} , height = ${height}`)
- console.log(`window size: width = ${info.windowWidth} , height = ${info.windowHeight}`)
-
- this.setData({
- width: width,
- height: height,
- });
-
- // 页面自定义初始化
- if (this.init) this.init()
+ .select('#canvas')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const width = info.windowWidth * this.data.widthScale * pixelRatio * renderScale
+ const height = info.windowHeight * this.data.heightScale * pixelRatio * renderScale
+ // 存在 webgl Canvas的情况下,写入大小
+ if (this.canvas) {
+ this.canvas.width = width
+ this.canvas.height = height
+ }
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ console.log(`window size: width = ${info.windowWidth} , height = ${info.windowHeight}`)
+
+ this.setData({
+ width,
+ height,
})
+
+ // 页面自定义初始化
+ if (this.init) this.init()
+ })
},
// 对应案例的初始化逻辑,由统一的 arBehavior 触发
init() {
@@ -79,20 +79,19 @@ Component({
// 注册 各类渲染器
if (this.data.renderByWebGL2) {
- this.initWebGL2();
+ this.initWebGL2()
} else if (this.data.renderByXRFrame) {
- this.initXRFrame();
+ this.initXRFrame()
}
-
},
- initPLY(id){
+ initPLY(id) {
console.log('== PLY Init start ==')
- const host = 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo';
+ const host = 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo'
// const host = 'http://127.0.0.1:8030'
// const host = 'http://10.9.169.149:8030'
- let type;
+ let type
// 加载 ply
// type = 'ply';
@@ -106,57 +105,57 @@ Component({
// const pcSrc = `${host}/ply/sakura.compressed.ply`;
// 加载 splat
- type = 'splat';
- const pcSrc = `${host}/splat/${id}.splat`;
-
- let splatModelMatrix = mat4.create();
- let modelMatrixLocal = mat4.create();
- let modelMatrixT = mat4.create();
- let modelMatrixR = mat4.create();
- let modelMatrixS = mat4.create();
- let splatScale = 1;
- let splatRotationAngle = 0;
- let splatRotationFlag = [0, 1, 0];
- let splatTranslate = [0, 0, 0];
+ type = 'splat'
+ const pcSrc = `${host}/splat/${id}.splat`
+
+ const splatModelMatrix = mat4.create()
+ const modelMatrixLocal = mat4.create()
+ const modelMatrixT = mat4.create()
+ const modelMatrixR = mat4.create()
+ const modelMatrixS = mat4.create()
+ let splatScale = 1
+ let splatRotationAngle = 0
+ let splatRotationFlag = [0, 1, 0]
+ let splatTranslate = [0, 0, 0]
// 针对不同场景设置不同的 本地矩阵
// Setup Camera
- switch(id) {
+ switch (id) {
case 'room':
- splatScale = 0.6;
- splatTranslate = [0, -3, 0];
- splatRotationAngle = - Math.PI / 180 * 26;
- splatRotationFlag = [1, 0, 0];
+ splatScale = 0.6
+ splatTranslate = [0, -3, 0]
+ splatRotationAngle = -Math.PI / 180 * 26
+ splatRotationFlag = [1, 0, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
// theta
- -Math.PI/2,
+ -Math.PI / 2,
// phi
- Math.PI/2,
+ Math.PI / 2,
// raidus
1
)
- break;
+ break
case 'garden':
- splatScale = 0.6;
- splatTranslate = [0, -2, 0];
- splatRotationAngle = - Math.PI / 180 * 20;
- splatRotationFlag = [1, 0, 0];
+ splatScale = 0.6
+ splatTranslate = [0, -2, 0]
+ splatRotationAngle = -Math.PI / 180 * 20
+ splatRotationFlag = [1, 0, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
// theta
- -Math.PI/2,
+ -Math.PI / 2,
// phi
- Math.PI/2,
+ Math.PI / 2,
// raidus
2
)
- break;
+ break
case 'stump':
- splatScale = 0.5;
- splatTranslate = [0, 0, 0];
+ splatScale = 0.5
+ splatTranslate = [0, 0, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
@@ -167,25 +166,25 @@ Component({
// raidus
2
)
- break;
+ break
case 'oneflower':
- splatScale = 0.1;
- splatTranslate = [-0.5, -2, -4];
- splatRotationAngle = - Math.PI / 180 * 40;
- splatRotationFlag = [1, 0, 0];
+ splatScale = 0.1
+ splatTranslate = [-0.5, -2, -4]
+ splatRotationAngle = -Math.PI / 180 * 40
+ splatRotationFlag = [1, 0, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
// theta
0,
// phi
- Math.PI/2,
+ Math.PI / 2,
// raidus
1
)
- break;
+ break
case 'usj':
- splatTranslate = [0, 1, 0];
+ splatTranslate = [0, 1, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
@@ -196,9 +195,9 @@ Component({
// raidus
1
)
- break;
+ break
case 'sakura':
- splatTranslate = [-1.6, 0, -1];
+ splatTranslate = [-1.6, 0, -1]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
@@ -209,40 +208,40 @@ Component({
// raidus
1
)
- break;
- case '0517cruch':
- splatTranslate = [0, 0, 0];
+ break
+ case '0517cruch':
+ splatTranslate = [0, 0, 0]
this.camera.updateCameraInfo(
// target
[0, 0, 0],
// theta
-Math.PI / 2,
// phi
- Math.PI/2,
+ Math.PI / 2,
// raidus
1
)
- break;
+ break
}
mat4.scale(modelMatrixS, mat4.create(), [splatScale, splatScale, splatScale])
mat4.rotate(modelMatrixR, modelMatrixS, splatRotationAngle, splatRotationFlag)
mat4.translate(modelMatrixT, modelMatrixR, splatTranslate)
- mat4.copy(modelMatrixLocal, modelMatrixT);
+ mat4.copy(modelMatrixLocal, modelMatrixT)
// Y轴反转矩阵
- const fixMatrix = mat4.create();
+ const fixMatrix = mat4.create()
mat4.rotate(fixMatrix, mat4.create(), Math.PI, [0, 0, 1])
// 本地矩阵
- const modelMatrixLocalFix = mat4.create();
- mat4.multiply(modelMatrixLocalFix, fixMatrix, modelMatrixLocal);
+ const modelMatrixLocalFix = mat4.create()
+ mat4.multiply(modelMatrixLocalFix, fixMatrix, modelMatrixLocal)
// 世界矩阵
- const modelWorld = mat4.create();
+ const modelWorld = mat4.create()
// mat4.translate(modelWorld, mat4.create(), [0, 1, 0])
- mat4.multiply(splatModelMatrix, modelWorld, modelMatrixLocalFix);
- this.camera.modelMatrix = splatModelMatrix;
+ mat4.multiply(splatModelMatrix, modelWorld, modelMatrixLocalFix)
+ this.camera.modelMatrix = splatModelMatrix
console.log('splat src', pcSrc)
@@ -250,66 +249,66 @@ Component({
url: pcSrc,
timeout: 200000,
success: (res) => {
- console.log("downloadFile 下载回调", res);
+ console.log('downloadFile 下载回调', res)
- const filePath = res.tempFilePath;
+ const filePath = res.tempFilePath
const fs = wx.getFileSystemManager()
/**
* 因为微信读文件,最大只能读100MB的,所以需要分块读取。
*/
- const fd = fs.openSync({ filePath: filePath })
- const stats = fs.fstatSync({fd: fd})
- console.log('fd stats', stats);
- let size = stats.size;
+ const fd = fs.openSync({ filePath })
+ const stats = fs.fstatSync({ fd })
+ console.log('fd stats', stats)
+ let size = stats.size
if (size > 0) {
- const buffer = new ArrayBuffer(size);
- const viewU8 = new Uint8Array(buffer);
- let offset = 0;
- let uindex = 0;
+ const buffer = new ArrayBuffer(size)
+ const viewU8 = new Uint8Array(buffer)
+ let offset = 0
+ let uindex = 0
while (size > 0) {
- const chunkSize = Math.min(size, 100 * 1024 * 1024 /* 100MB */);
+ const chunkSize = Math.min(size, 100 * 1024 * 1024 /* 100MB */)
- const res = fs.readFileSync(
+ const res = fs.readFileSync(
filePath,
undefined,
offset,
chunkSize,
- );
- const resU8 = new Uint8Array(res);
- viewU8.set(new Uint8Array(res), uindex);
- uindex += resU8.length;
+ )
+ const resU8 = new Uint8Array(res)
+ viewU8.set(new Uint8Array(res), uindex)
+ uindex += resU8.length
// console.log('res', res)
// console.log('uindex', uindex);
// console.log('offset', offset);
// console.log('chunkSize', chunkSize)
- offset += chunkSize;
- size -= chunkSize;
+ offset += chunkSize
+ size -= chunkSize
}
- fs.close({ fd });
+ fs.close({ fd })
// console.log('buffer', buffer)
- let info;
+ let info
- const maxGaussians = this.data.maxGaussians;
+ const maxGaussians = this.data.maxGaussians
switch (type) {
case 'ply':
- info = loadPly(buffer, maxGaussians);
- console.log("plyLoader return", info);
- break;
+ info = loadPly(buffer, maxGaussians)
+ console.log('plyLoader return', info)
+ break
case 'splat':
- info = loadSplat(buffer, maxGaussians);
- console.log("splatLoader return", info);
- break;
+ info = loadSplat(buffer, maxGaussians)
+ console.log('splatLoader return', info)
+ break
}
// 提供渲染的高斯球数
- const renderCount = this.renderCount = info.count;
+ const renderCount = this.renderCount = info.count
// 全部用 f32 存储
// this.sabPositions = wx.createSharedArrayBuffer(renderCount * 4 * 3)
@@ -327,10 +326,9 @@ Component({
// sabCov3Da: this.sabCov3Da,
// sabCov3Db: this.sabCov3Db,
// sabcolors: this.sabcolors,
- });
-
+ })
} else {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
@@ -340,7 +338,7 @@ Component({
}
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
@@ -348,7 +346,7 @@ Component({
})
console.error(res)
}
- });
+ })
},
initWorker(plyInfo, config) {
@@ -360,15 +358,13 @@ Component({
// worker 初始化 回调
console.log('[Worker callback] gaussianSplatting init callBack', res)
- this.camera.isWorkerInit = true;
- this.camera.update();
-
-
+ this.camera.isWorkerInit = true
+ this.camera.update()
} else if (res.type === 'execFunc_sort') {
// worker 排序 回调
// console.log(res)
- this.camera.isWorkerSorting = false;
+ this.camera.isWorkerSorting = false
const data = res.result.data
@@ -381,11 +377,11 @@ Component({
gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW)
}
- const positions = new Float32Array(data.positions);
- const opacities = new Float32Array(data.opacities);
- const cov3Da = new Float32Array(data.cov3Da);
- const cov3Db = new Float32Array(data.cov3Db);
- const colors = new Float32Array(data.colors);
+ const positions = new Float32Array(data.positions)
+ const opacities = new Float32Array(data.opacities)
+ const cov3Da = new Float32Array(data.cov3Da)
+ const cov3Db = new Float32Array(data.cov3Db)
+ const colors = new Float32Array(data.colors)
// const positions = new Float32Array(this.sabPositions.buffer);
// const opacities = new Float32Array(this.sabOpacities.buffer);
@@ -400,13 +396,13 @@ Component({
updateBuffer(this.splat.buffers.color, colors)
// 设定绘制的高斯球数量
- this.gaussiansCount = data.gaussiansCount;
+ this.gaussiansCount = data.gaussiansCount
const end = new Date().getTime()
// const sortTime = `${((end - start)/1000).toFixed(3)}s`
// console.log(`updateBuffer ${sortTime}`)
- this.canvas.requestAnimationFrame(this.requestRender.bind(this));
+ this.canvas.requestAnimationFrame(this.requestRender.bind(this))
// console.log('execFunc_sort end')
}
@@ -421,14 +417,14 @@ Component({
// 后续为 webGL2 相关,为了方便开发,先放在一起
initWebGL2() {
console.log('== InitWebGL2 start ==')
- const gl = this.gl = this.canvas.getContext('webgl2');
- console.log('webgl2 context', gl);
+ const gl = this.gl = this.canvas.getContext('webgl2')
+ console.log('webgl2 context', gl)
// Setup Camera
const cameraParameters = {
up: [0, 1.0, 0.0],
target: [0, 0, 0],
- camera: [Math.PI/2, Math.PI/2, 1], // theta phi radius
+ camera: [Math.PI / 2, Math.PI / 2, 1], // theta phi radius
}
this.camera = new CameraWebGL(gl, this.worker, cameraParameters)
@@ -436,102 +432,98 @@ Component({
this.cubeInstance = new CubeInstanceWebGL(gl)
// Setup Splat
- this.initSplat(gl);
-
-
+ this.initSplat(gl)
},
initSplat(gl) {
// 初始化 splat 绘制到的 renderTexture
- this.splatRT = new SplatRenderTexture(gl);
+ this.splatRT = new SplatRenderTexture(gl)
// 初始化 splat 渲染器
- this.splat = new SplatWebGL(gl);
+ this.splat = new SplatWebGL(gl)
},
requestRender() {
// console.log('requestRender')
// 限帧
- let now = Date.now()
- const last = this.lastRenderTime || 0;
+ const now = Date.now()
+ const last = this.lastRenderTime || 0
const mill = now - last
if (mill < 30) {
return
}
this.lastRenderTime = now
-
- const gl = this.gl;
+
+ const gl = this.gl
// Clear State
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
- gl.clearColor(0.8, 0.8, 0.8, 1.0);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+ gl.clearColor(0.8, 0.8, 0.8, 1.0)
// clear
- gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
// 先关掉深度测试
gl.disable(gl.DEPTH_TEST)
- this.drawSplat(gl);
+ this.drawSplat(gl)
// resetState
- gl.disable(gl.CULL_FACE);
+ gl.disable(gl.CULL_FACE)
// 深度测试
gl.enable(gl.DEPTH_TEST)
// drawCubeMesh
- const projMatrix = this.camera.projMatrix;
- const viewMatrix = this.camera.viewMatrix;
- let modelMatrix = mat4.create();
- const cubeScale = 0.02;
+ const projMatrix = this.camera.projMatrix
+ const viewMatrix = this.camera.viewMatrix
+ const modelMatrix = mat4.create()
+ const cubeScale = 0.02
mat4.scale(modelMatrix, mat4.create(), [cubeScale, cubeScale, cubeScale])
this.drawCubeMesh(gl, projMatrix, viewMatrix, modelMatrix)
-
},
drawCubeMesh(gl, projMatrix, viewMatrix, modelMatrix) {
// mesh
const meshCube = this.cubeInstance
// Tell WebGL to use our program when drawing
- gl.useProgram(meshCube.programInfo.program);
+ gl.useProgram(meshCube.programInfo.program)
// VAO
- gl.bindVertexArray(meshCube.vao);
+ gl.bindVertexArray(meshCube.vao)
// mesh position
- gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.positionBuffer);
- gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.positionBuffer)
+ gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexPosition)
// mesh color
- gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.colorBuffer);
- gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexColor, 4, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexColor);
+ gl.bindBuffer(gl.ARRAY_BUFFER, meshCube.colorBuffer)
+ gl.vertexAttribPointer(meshCube.programInfo.attribLocations.vertexColor, 4, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(meshCube.programInfo.attribLocations.vertexColor)
// Tell WebGL which indices to use to index the vertices
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, meshCube.indices);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, meshCube.indices)
// Set the shader uniforms
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.projectionMatrix,
false,
projMatrix
- );
+ )
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.viewMatrix,
false,
viewMatrix
- );
+ )
gl.uniformMatrix4fv(
meshCube.programInfo.uniformLocations.modelMatrix,
false,
modelMatrix
- );
+ )
// draw
- const vertexCount = 36;
- const type = gl.UNSIGNED_SHORT;
- const offset = 0;
- gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
+ const vertexCount = 36
+ const type = gl.UNSIGNED_SHORT
+ const offset = 0
+ gl.drawElements(gl.TRIANGLES, vertexCount, type, offset)
},
drawSplat(gl) {
-
// 通用准备
const cam = this.camera
@@ -541,10 +533,10 @@ Component({
const splatRTFrameBuffer = this.splatRT.frameBuffer
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
- gl.bindFramebuffer(gl.FRAMEBUFFER, splatRTFrameBuffer);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, splatRTFrameBuffer)
- gl.clearColor(0, 0, 0, 0.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.clearColor(0, 0, 0, 0.0)
+ gl.clear(gl.COLOR_BUFFER_BIT)
// Set Splat state
gl.disable(gl.DEPTH_TEST)
@@ -556,11 +548,11 @@ Component({
// 开启 Splat 绘制流程
const splat = this.splat
- const program = splat.program;
+ const program = splat.program
// Use Program
- gl.useProgram(program);
+ gl.useProgram(program)
// VAO
- gl.bindVertexArray(splat.vao);
+ gl.bindVertexArray(splat.vao)
// Original implementation parameters
const canvasWidth = gl.canvas.width
@@ -583,32 +575,31 @@ Component({
// gl.uniformMatrix4fv(gl.getUniformLocation(program, 'viewmatrix'), false, cam.vm)
// Draw Splat
- gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, this.gaussiansCount);
+ gl.drawArraysInstanced(gl.TRIANGLE_STRIP, 0, 4, this.gaussiansCount)
// resetState
gl.enable(gl.BLEND)
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA)
// 最后将RT绘制 到 主屏
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)
- gl.useProgram(splatRT.programInfo.program);
+ gl.useProgram(splatRT.programInfo.program)
// VAO
- gl.bindVertexArray(splatRT.vao);
+ gl.bindVertexArray(splatRT.vao)
// position
- gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.position);
- gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexPosition);
+ gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.position)
+ gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexPosition, 3, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexPosition)
// texCoord
- gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.texCoord);
- gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0);
- gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexTexcoord);
+ gl.bindBuffer(gl.ARRAY_BUFFER, splatRT.buffers.texCoord)
+ gl.vertexAttribPointer(splatRT.programInfo.attribLocations.vertexTexcoord, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(splatRT.programInfo.attribLocations.vertexTexcoord)
// indices
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, splatRT.buffers.indices);
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, splatRT.buffers.indices)
// draw RenderTexture
- gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
-
+ gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
},
// webGL触摸相关逻辑
onTouchStartWebGL(e) {
@@ -617,31 +608,30 @@ Component({
if (e.touches.length === 1) {
this.camera.lastTouch.x1 = e.touches[0].clientX
this.camera.lastTouch.y1 = e.touches[0].clientY
- this.camera.lastTouch.x2 = null;
- this.camera.lastTouch.y2 = null;
- this.camera.lastTouch.distance = 0;
+ this.camera.lastTouch.x2 = null
+ this.camera.lastTouch.y2 = null
+ this.camera.lastTouch.distance = 0
} else if (e.touches.length === 2) {
- const touch1 = e.touches[0];
- const touch2 = e.touches[1];
+ const touch1 = e.touches[0]
+ const touch2 = e.touches[1]
this.camera.lastTouch.x1 = touch1.clientX
this.camera.lastTouch.y1 = touch1.clientY
this.camera.lastTouch.x2 = touch2.clientX
this.camera.lastTouch.y2 = touch2.clientY
- const distanceX = touch1.clientX - touch2.clientX;
- const distanceY = touch1.clientY - touch2.clientY;
- this.camera.lastTouch.distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
+ const distanceX = touch1.clientX - touch2.clientX
+ const distanceY = touch1.clientY - touch2.clientY
+ this.camera.lastTouch.distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY)
}
-
},
onTouchMoveWebGL(e) {
// console.log(e);
- const moveScale = 1;
+ const moveScale = 1
if (e.touches.length === 1) {
- const touch = e.touches[0];
+ const touch = e.touches[0]
// 单指移动镜头
const movementX = touch.clientX - this.camera.lastTouch.x1
const movementY = touch.clientY - this.camera.lastTouch.y1
@@ -650,18 +640,17 @@ Component({
if (Math.abs(movementX) < 50 && Math.abs(movementY) < 50) {
// 只处理小移动
- this.camera.theta += movementX * 0.01 * .3 * moveScale
- this.camera.phi = Math.max(1e-6, Math.min(Math.PI - 1e-6, this.camera.phi - movementY * 0.01 * moveScale))
+ this.camera.theta += movementX * 0.01 * 0.3 * moveScale
+ this.camera.phi = Math.max(1e-6, Math.min(Math.PI - 1e-6, this.camera.phi - movementY * 0.01 * moveScale))
}
-
} else if (e.touches.length === 2) {
// 支持单指变双指,兼容双指操作但是两根手指触屏时间不一致的情况
- const touch1 = e.touches[0];
- const touch2 = e.touches[1];
+ const touch1 = e.touches[0]
+ const touch2 = e.touches[1]
- const distanceX = touch1.clientX - touch2.clientX;
- const distanceY = touch1.clientY - touch2.clientY;
- const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
+ const distanceX = touch1.clientX - touch2.clientX
+ const distanceY = touch1.clientY - touch2.clientY
+ const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY)
if (this.camera.lastTouch.x2 === null && this.camera.lastTouch.y2 === null) {
this.camera.lastTouch.x1 = touch1.clientX
@@ -669,52 +658,50 @@ Component({
this.camera.lastTouch.x2 = touch2.clientX
this.camera.lastTouch.y2 = touch2.clientY
- this.camera.lastTouch.distance = distance;
+ this.camera.lastTouch.distance = distance
} else {
// 双指开始滑动
- let deltaScale = distance - this.camera.lastTouch.distance;
- this.camera.lastTouch.distance = distance;
+ let deltaScale = distance - this.camera.lastTouch.distance
+ this.camera.lastTouch.distance = distance
if (deltaScale < -2) {
- deltaScale = -2;
+ deltaScale = -2
} else if (deltaScale > 2) {
- deltaScale = 2;
+ deltaScale = 2
}
- const newRaidus = this.camera.radius - deltaScale * 0.2;
- this.camera.radius = newRaidus > 0 ? newRaidus: this.camera.radius;
+ const newRaidus = this.camera.radius - deltaScale * 0.2
+ this.camera.radius = newRaidus > 0 ? newRaidus : this.camera.radius
}
-
}
-
- this.camera.update();
- this.canvas.requestAnimationFrame(this.requestRender.bind(this));
+ this.camera.update()
+
+ this.canvas.requestAnimationFrame(this.requestRender.bind(this))
},
onTapControl(e) {
- const dataSet = e.target.dataset;
-
- const id = dataSet.id;
-
+ const dataSet = e.target.dataset
+
+ const id = dataSet.id
+
// 开始处理 ply 资源
- this.initPLY(id);
+ this.initPLY(id)
},
changeMaxGaussianCount(e) {
this.setData({
maxGaussians: e.detail.value
})
- console.log('slider maxGaussians:', this.data.maxGaussians);
+ console.log('slider maxGaussians:', this.data.maxGaussians)
},
switchWorker(e) {
this.setData({
workerOn: e.detail.value
})
- this.camera.setWorkerOn(this.data.workerOn);
+ this.camera.setWorkerOn(this.data.workerOn)
- console.log('switch WorkerOn:', this.data.workerOn);
+ console.log('switch WorkerOn:', this.data.workerOn)
}
},
})
-
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/ply/ply-loader.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/ply/ply-loader.js
index fa0cee0e..7668bd31 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/ply/ply-loader.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/ply/ply-loader.js
@@ -2,119 +2,122 @@ import { wxDecodeAdapter, computeCov3D } from '../util-loader.js'
// implementation from https://github.com/kishimisu/Gaussian-Splatting-WebGL
export function loadPly(content, maxGaussians) {
- // Read header
- console.log('loadPly', content)
- const contentStart = wxDecodeAdapter(content.slice(0, 2000), true);
- // const contentStart = new TextDecoder('utf-8').decode(content.slice(0, 2000))
- const headerEnd = contentStart.indexOf('end_header') + 'end_header'.length + 1
- const [ header ] = contentStart.split('end_header')
+ // Read header
+ console.log('loadPly', content)
+ const contentStart = wxDecodeAdapter(content.slice(0, 2000), true)
+ // const contentStart = new TextDecoder('utf-8').decode(content.slice(0, 2000))
+ const headerEnd = contentStart.indexOf('end_header') + 'end_header'.length + 1
+ const [header] = contentStart.split('end_header')
- console.log('header', header)
+ console.log('header', header)
- // Get number of gaussians
- const regex = /element vertex (\d+)/
- const match = header.match(regex)
- let gaussianCount = parseInt(match[1])
+ // Get number of gaussians
+ const regex = /element vertex (\d+)/
+ const match = header.match(regex)
+ let gaussianCount = parseInt(match[1])
- console.log(`load splatCount: ${gaussianCount}`)
+ console.log(`load splatCount: ${gaussianCount}`)
- gaussianCount = Math.min(gaussianCount, maxGaussians);
+ gaussianCount = Math.min(gaussianCount, maxGaussians)
- // Create arrays for gaussian properties
- const positions = []
- const opacities = []
- const colors = []
- const cov3Ds = []
+ // Create arrays for gaussian properties
+ const positions = []
+ const opacities = []
+ const colors = []
+ const cov3Ds = []
- // Helpers
- const sigmoid = (m1) => 1 / (1 + Math.exp(-m1))
- const NUM_PROPS = 62
+ // Helpers
+ const sigmoid = (m1) => 1 / (1 + Math.exp(-m1))
+ const NUM_PROPS = 62
- // Create a dataview to access the buffer's content on a byte levele
- const view = new DataView(content)
+ // Create a dataview to access the buffer's content on a byte levele
+ const view = new DataView(content)
- // Get a slice of the dataview relative to a splat index
- const fromDataView = (splatID, start, end) => {
- const startOffset = headerEnd + splatID * NUM_PROPS * 4 + start * 4
+ // Get a slice of the dataview relative to a splat index
+ const fromDataView = (splatID, start, end) => {
+ const startOffset = headerEnd + splatID * NUM_PROPS * 4 + start * 4
- if (end == null)
- return view.getFloat32(startOffset, true)
+ if (end == null) return view.getFloat32(startOffset, true)
- return new Float32Array(end - start).map((_, i) => view.getFloat32(startOffset + i * 4, true))
- }
+ return new Float32Array(end - start).map((_, i) => view.getFloat32(startOffset + i * 4, true))
+ }
- // Extract all properties for a gaussian splat using the dataview
- const extractSplatData = (splatID) => {
- const position = fromDataView(splatID, 0, 3)
- // const n = fromDataView(splatID, 3, 6) // Not used
- const harmonic = fromDataView(splatID, 6, 9)
-
- const H_END = 6 + 48 // Offset of the last harmonic coefficient
- const opacity = fromDataView(splatID, H_END)
- const scale = fromDataView(splatID, H_END + 1, H_END + 4)
- const rotation = fromDataView(splatID, H_END + 4, H_END + 8)
-
- return { position, harmonic, opacity, scale, rotation }
- }
+ // Extract all properties for a gaussian splat using the dataview
+ const extractSplatData = (splatID) => {
+ const position = fromDataView(splatID, 0, 3)
+ // const n = fromDataView(splatID, 3, 6) // Not used
+ const harmonic = fromDataView(splatID, 6, 9)
- // gaussianCount = 10;
-
- for (let i = 0; i < gaussianCount; i++) {
- // Extract data for current gaussian
- let { position, harmonic, opacity, scale, rotation } = extractSplatData(i)
-
- // Normalize quaternion
- let length2 = 0
-
- for (let j = 0; j < 4; j++)
- length2 += rotation[j] * rotation[j]
-
- const length = Math.sqrt(length2)
-
- // console.log('scale', scale[0], scale[1], scale[2]);
- // console.log('rotation', rotation[0], rotation[1], rotation[2], rotation[3]);
-
- rotation = rotation.map(v => v / length)
-
- // Exponentiate scale
- scale = scale.map(v => Math.exp(v))
-
- // console.log('scalee', scale[0], scale[1], scale[2]);
- // console.log('rotatione', rotation[0], rotation[1], rotation[2], rotation[3]);
-
- // Activate alpha
- opacity = sigmoid(opacity)
- opacities.push(opacity)
-
- // (Webgl-specific) Equivalent to computeColorFromSH() with degree 0:
- // Use the first spherical harmonic to pre-compute the color.
- // This allow to avoid sending harmonics to the web worker or GPU,
- // but removes view-dependent lighting effects like reflections.
- // If we were to use a degree > 0, we would need to recompute the color
- // each time the camera moves, and send many more harmonics to the worker:
- // Degree 1: 4 harmonics needed (12 floats) per gaussian
- // Degree 2: 9 harmonics needed (27 floats) per gaussian
- // Degree 3: 16 harmonics needed (48 floats) per gaussian
- const SH_C0 = 0.28209479177387814
- const color = [
- 0.5 + SH_C0 * harmonic[0],
- 0.5 + SH_C0 * harmonic[1],
- 0.5 + SH_C0 * harmonic[2]
- ]
- colors.push(...color)
- // harmonics.push(...harmonic)
-
- // (Webgl-specific) Pre-compute the 3D covariance matrix from
- // the rotation and scale in order to avoid recomputing it at each frame.
- // This also allow to avoid sending rotations and scales to the web worker or GPU.
- const cov3D = computeCov3D(scale, 1, rotation)
- cov3Ds.push(...cov3D)
- // rotations.push(...rotation)
- // scales.push(...scale)
-
- positions.push(...position)
- }
+ const H_END = 6 + 48 // Offset of the last harmonic coefficient
+ const opacity = fromDataView(splatID, H_END)
+ const scale = fromDataView(splatID, H_END + 1, H_END + 4)
+ const rotation = fromDataView(splatID, H_END + 4, H_END + 8)
-
- return { positions, opacities, colors, cov3Ds, count: gaussianCount }
-}
\ No newline at end of file
+ return {
+ position, harmonic, opacity, scale, rotation
+ }
+ }
+
+ // gaussianCount = 10;
+
+ for (let i = 0; i < gaussianCount; i++) {
+ // Extract data for current gaussian
+ let {
+ position, harmonic, opacity, scale, rotation
+ } = extractSplatData(i)
+
+ // Normalize quaternion
+ let length2 = 0
+
+ for (let j = 0; j < 4; j++) length2 += rotation[j] * rotation[j]
+
+ const length = Math.sqrt(length2)
+
+ // console.log('scale', scale[0], scale[1], scale[2]);
+ // console.log('rotation', rotation[0], rotation[1], rotation[2], rotation[3]);
+
+ rotation = rotation.map(v => v / length)
+
+ // Exponentiate scale
+ scale = scale.map(v => Math.exp(v))
+
+ // console.log('scalee', scale[0], scale[1], scale[2]);
+ // console.log('rotatione', rotation[0], rotation[1], rotation[2], rotation[3]);
+
+ // Activate alpha
+ opacity = sigmoid(opacity)
+ opacities.push(opacity)
+
+ // (Webgl-specific) Equivalent to computeColorFromSH() with degree 0:
+ // Use the first spherical harmonic to pre-compute the color.
+ // This allow to avoid sending harmonics to the web worker or GPU,
+ // but removes view-dependent lighting effects like reflections.
+ // If we were to use a degree > 0, we would need to recompute the color
+ // each time the camera moves, and send many more harmonics to the worker:
+ // Degree 1: 4 harmonics needed (12 floats) per gaussian
+ // Degree 2: 9 harmonics needed (27 floats) per gaussian
+ // Degree 3: 16 harmonics needed (48 floats) per gaussian
+ const SH_C0 = 0.28209479177387814
+ const color = [
+ 0.5 + SH_C0 * harmonic[0],
+ 0.5 + SH_C0 * harmonic[1],
+ 0.5 + SH_C0 * harmonic[2]
+ ]
+ colors.push(...color)
+ // harmonics.push(...harmonic)
+
+ // (Webgl-specific) Pre-compute the 3D covariance matrix from
+ // the rotation and scale in order to avoid recomputing it at each frame.
+ // This also allow to avoid sending rotations and scales to the web worker or GPU.
+ const cov3D = computeCov3D(scale, 1, rotation)
+ cov3Ds.push(...cov3D)
+ // rotations.push(...rotation)
+ // scales.push(...scale)
+
+ positions.push(...position)
+ }
+
+ return {
+ positions, opacities, colors, cov3Ds, count: gaussianCount
+ }
+}
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/splat/splat-loader.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/splat/splat-loader.js
index ec4e87de..22fb9747 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/splat/splat-loader.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/splat/splat-loader.js
@@ -1,15 +1,15 @@
import { wxDecodeAdapter, computeCov3D } from '../util-loader.js'
-const RowSizeBytes = 32;
-const CenterSizeBytes = 12;
-const ScaleSizeBytes = 12;
-const RotationSizeBytes = 4;
-const ColorSizeBytes = 4;
+const RowSizeBytes = 32
+const CenterSizeBytes = 12
+const ScaleSizeBytes = 12
+const RotationSizeBytes = 4
+const ColorSizeBytes = 4
-const perPI = Math.PI / 180;
+const perPI = Math.PI / 180
export function loadSplat(content, maxGaussians) {
- console.log('loadSplat', content);
+ console.log('loadSplat', content)
const start = new Date().getTime()
@@ -19,12 +19,12 @@ export function loadSplat(content, maxGaussians) {
const colors = []
const cov3Ds = []
- const inBuffer = content;
+ const inBuffer = content
- let splatCount = inBuffer.byteLength / RowSizeBytes;
+ let splatCount = inBuffer.byteLength / RowSizeBytes
console.log(`load splatCount: ${splatCount}`)
- splatCount = Math.min(splatCount, maxGaussians);
+ splatCount = Math.min(splatCount, maxGaussians)
// splatCount = 10;
@@ -34,32 +34,30 @@ export function loadSplat(content, maxGaussians) {
// XYZ - Scale (Float32)
// RGBA - colors (uint8)
// IJKL - quaternion/rot (uint8)
- const inBase = i * RowSizeBytes;
+ const inBase = i * RowSizeBytes
- const inCenter = new Float32Array(inBuffer, inBase, 3);
- const inScale = new Float32Array(inBuffer, inBase + CenterSizeBytes, 3);
- const inColor = new Uint8Array(inBuffer, inBase + CenterSizeBytes + ScaleSizeBytes, 4);
- let inRotation = new Uint8Array(inBuffer, inBase + CenterSizeBytes +
- ScaleSizeBytes + ColorSizeBytes, 4);
+ const inCenter = new Float32Array(inBuffer, inBase, 3)
+ const inScale = new Float32Array(inBuffer, inBase + CenterSizeBytes, 3)
+ const inColor = new Uint8Array(inBuffer, inBase + CenterSizeBytes + ScaleSizeBytes, 4)
+ const inRotation = new Uint8Array(inBuffer, inBase + CenterSizeBytes +
+ ScaleSizeBytes + ColorSizeBytes, 4)
- let rotation = [(inRotation[0] - 128) / 128, (inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128];
+ let rotation = [(inRotation[0] - 128) / 128, (inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128]
// Normalize quaternion
let length2 = 0
- for (let j = 0; j < 4; j++)
- length2 += rotation[j] * rotation[j]
+ for (let j = 0; j < 4; j++) length2 += rotation[j] * rotation[j]
const length = Math.sqrt(length2)
- rotation = rotation.map(v => v / length)
+ rotation = rotation.map(v => v / length)
// console.log('scale', inScale[0], inScale[1], inScale[2]);
// console.log('rotation', rotation[0], rotation[1], rotation[2], rotation[3]);
-
// Activate alpha
const opacity = inColor[3] / 255
- opacities.push(opacity);
- colors.push(inColor[0] / 255, inColor[1]/ 255, inColor[2] / 255);
+ opacities.push(opacity)
+ colors.push(inColor[0] / 255, inColor[1] / 255, inColor[2] / 255)
const cov3D = computeCov3D(inScale, 1, rotation)
cov3Ds.push(...cov3D)
@@ -67,11 +65,12 @@ export function loadSplat(content, maxGaussians) {
positions.push(...inCenter)
}
- const end = new Date().getTime();
+ const end = new Date().getTime()
- const sortTime = `${((end - start)/1000).toFixed(3)}s`
+ const sortTime = `${((end - start) / 1000).toFixed(3)}s`
console.log(`parse ${splatCount} gaussians in ${sortTime}.`)
- return { positions, opacities, colors, cov3Ds, count: splatCount };
-
-}
\ No newline at end of file
+ return {
+ positions, opacities, colors, cov3Ds, count: splatCount
+ }
+}
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js
index be44e540..e92726ab 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js
@@ -8,57 +8,70 @@ const M = mat3.create()
const Sigma = mat3.create()
function computeCov3D(scale, mod, rot) {
- // Create scaling matrix
- mat3.set(S,
- mod * scale[0], 0, 0,
- 0, mod * scale[1], 0,
- 0, 0, mod * scale[2]
- )
+ // Create scaling matrix
+ mat3.set(
+ S,
+ mod * scale[0],
+ 0,
+ 0,
+ 0,
+ mod * scale[1],
+ 0,
+ 0,
+ 0,
+ mod * scale[2]
+ )
- const r = rot[0]
- const x = rot[1]
- const y = rot[2]
- const z = rot[3]
+ const r = rot[0]
+ const x = rot[1]
+ const y = rot[2]
+ const z = rot[3]
- // Compute rotation matrix from quaternion
- mat3.set(R,
- 1. - 2. * (y * y + z * z), 2. * (x * y - r * z), 2. * (x * z + r * y),
- 2. * (x * y + r * z), 1. - 2. * (x * x + z * z), 2. * (y * z - r * x),
- 2. * (x * z - r * y), 2. * (y * z + r * x), 1. - 2. * (x * x + y * y)
- )
+ // Compute rotation matrix from quaternion
+ mat3.set(
+ R,
+ 1.0 - 2.0 * (y * y + z * z),
+ 2.0 * (x * y - r * z),
+ 2.0 * (x * z + r * y),
+ 2.0 * (x * y + r * z),
+ 1.0 - 2.0 * (x * x + z * z),
+ 2.0 * (y * z - r * x),
+ 2.0 * (x * z - r * y),
+ 2.0 * (y * z + r * x),
+ 1.0 - 2.0 * (x * x + y * y)
+ )
- mat3.multiply(M, S, R) // M = S * R
+ mat3.multiply(M, S, R) // M = S * R
- // Compute 3D world covariance matrix Sigma
- mat3.multiply(Sigma, mat3.transpose(tmp, M), M) // Sigma = transpose(M) * M
+ // Compute 3D world covariance matrix Sigma
+ mat3.multiply(Sigma, mat3.transpose(tmp, M), M) // Sigma = transpose(M) * M
- // Covariance is symmetric, only store upper right
- const cov3D = [
- Sigma[0], Sigma[1], Sigma[2],
- Sigma[4], Sigma[5], Sigma[8]
- ]
- return cov3D
+ // Covariance is symmetric, only store upper right
+ const cov3D = [
+ Sigma[0], Sigma[1], Sigma[2],
+ Sigma[4], Sigma[5], Sigma[8]
+ ]
+ return cov3D
}
function wxDecodeAdapter(buffer, isUTF8) {
- const array = new Uint8Array(buffer);
- let str = '';
+ const array = new Uint8Array(buffer)
+ let str = ''
for (let i = 0; i < array.length; i++) {
- str += String.fromCharCode(array[i]);
+ str += String.fromCharCode(array[i])
}
if (isUTF8) {
// utf8 str fix
// https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/btoa
- str = decodeURIComponent(encodeURIComponent(str));
+ str = decodeURIComponent(encodeURIComponent(str))
}
- return str;
+ return str
}
-
export {
- wxDecodeAdapter,
- computeCov3D
-}
\ No newline at end of file
+ wxDecodeAdapter,
+ computeCov3D
+}
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/render-xrframe.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/render-xrframe.js
index 2c0a88c9..1567db70 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/render-xrframe.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/render-xrframe.js
@@ -1,52 +1,40 @@
-import splat_vs from "./shader/splat_xrframe_vs.glsl";
-import splat_fs from "./shader/splat_xrframe_fs.glsl";
+import splat_vs from './shader/splat_xrframe_vs.glsl'
+import splat_fs from './shader/splat_xrframe_fs.glsl'
const xrFrameRender = {
- // 对应案例的初始化逻辑,由统一的 behavior 触发
- init() {
- console.log('start init ply');
-
- const plySrc = 'http://10.9.233.66:8000/ply/point_cloud.ply';
-
- const filePath = wx.env.USER_DATA_PATH + '/point.ply';
- wx.downloadFile({
- filePath: filePath,
- url: plySrc,
- success: (res) => {
- console.log("下载回调", res);
- const fs = wx.getFileSystemManager()
- fs.readFile({
- filePath: res.filePath,
- position: 0,
- success: async (res) => {
- console.log("读文件回调,结果返回为", res)
-
- // const plyInfo = plyLoader.parsePLYBuffer(res.data);
-
- const plyInfo = loadPly(res.data);
-
- console.log("plyLoader return", plyInfo);
-
- // 初始化 worker 相关
- this._worker.postMessage({
- type: 'execFunc_init',
- params: [plyInfo]
- })
-
- },
- fail(res) {
- wx.hideLoading();
- wx.showToast({
- title: res.errMsg,
- icon: 'none',
- duration: 2000
- })
- console.error(res)
- }
- });
+ // 对应案例的初始化逻辑,由统一的 behavior 触发
+ init() {
+ console.log('start init ply')
+
+ const plySrc = 'http://10.9.233.66:8000/ply/point_cloud.ply'
+
+ const filePath = wx.env.USER_DATA_PATH + '/point.ply'
+ wx.downloadFile({
+ filePath,
+ url: plySrc,
+ success: (res) => {
+ console.log('下载回调', res)
+ const fs = wx.getFileSystemManager()
+ fs.readFile({
+ filePath: res.filePath,
+ position: 0,
+ success: async (res) => {
+ console.log('读文件回调,结果返回为', res)
+
+ // const plyInfo = plyLoader.parsePLYBuffer(res.data);
+
+ const plyInfo = loadPly(res.data)
+
+ console.log('plyLoader return', plyInfo)
+
+ // 初始化 worker 相关
+ this._worker.postMessage({
+ type: 'execFunc_init',
+ params: [plyInfo]
+ })
},
fail(res) {
- wx.hideLoading();
+ wx.hideLoading()
wx.showToast({
title: res.errMsg,
icon: 'none',
@@ -54,259 +42,255 @@ const xrFrameRender = {
})
console.error(res)
}
- });
-
-
- // 监听worker回调
- this._worker.onMessage((res) => {
- if (res.type === 'execFunc_init') {
- // 初始化 worker 回调
- console.log('gaussianSplatting init callBack')
- console.log('res', res);
-
- this.initGSGeometry(res.result.count, res.result.vertexSize);
-
- } else if (res.type === 'execFunc_sort') {
- // worker 排序 回调
- // console.log('gaussianSplatting sort callBack', res.result)
-
- // const vb = getVertexBuffer(this.vertexData);
-
- this.geometryGeo.uploadVertexBuffer(0, res.result.vertexBuffer);
-
- // console.log('sort callback', this.geometryGeo, res.result.vertexBuffer)
- }
})
-
- },
- initGSGeometry(gaussianCount, vertexSize){
- console.log('initGSGeometry start');
-
- const xrFrameSystem = wx.getXrFrameSystem()
- const createGSEffect = (scene) => {
- return scene.createEffect({
- name: 'gaussianSplatting',
- defaultRenderQueue: 3000,
- properties: [
- {
- key: 'screen_width',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- },
- {
- key: 'screen_height',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- },
- {
- key: 'focal_x',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- },
- {
- key: 'focal_y',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- },
- {
- key: 'tan_fovx',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- },
- {
- key: 'tan_fovy',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 0
- }
- ,{
- key: 'scale_modifier',
- type: xrFrameSystem.EUniformType.FLOAT,
- default: 1
- },
- ],
- images: [],
- passes: [
- {
- renderStates: {
- blendOn: true,
- depthWrite: false,
- cullOn: false,
- },
- lightMode: 'ForwardBase',
- useMaterialRenderStates: true,
- shaders: [0, 1]
- }
- ],
- shaders: [
- // Vertex Shader
- splat_vs,
- // Fragement Shader
- splat_fs
- ],
- });
- }
-
- this.geometryRoot = this.xrScene.getElementById('geometryRoot');
-
- console.log('geometryRoot', this.geometryRoot);
-
-
- // 注册 Geometry 信息
- xrFrameSystem.registerGeometry('gaussian-splatting', scene => {
- console.log('registerGeometry')
- const vl = scene.createVertexLayout({
- attributes: [
- {
- name: "a_center",
- format: xrFrameSystem.EVertexFormat.FLOAT3,
- offset: 0,
- },
- {
- name: "a_opacity",
- format: xrFrameSystem.EVertexFormat.FLOAT,
- offset: 12,
- },
- {
- name: "a_cov3Da",
- format: xrFrameSystem.EVertexFormat.FLOAT3,
- offset: 16,
- },
- {
- name: "a_cov3Db",
- format: xrFrameSystem.EVertexFormat.FLOAT3,
- offset: 28,
- },
- {
- name: "a_color",
- format: xrFrameSystem.EVertexFormat.FLOAT3,
- offset: 40,
- },
- {
- name: "a_corner",
- format: xrFrameSystem.EVertexFormat.FLOAT2,
- offset: 52,
- },
- ],
- stride: 60
- });
-
- console.log('createVertexLayout');
-
- const indices = [];
- const verticesPerInstance = 4;
- const instanceCount = gaussianCount / verticesPerInstance;
- for (let i = 0; i < instanceCount; i++) {
- // 对于每个实例,添加6个索引以形成2个三角形
- const base = i * 4; // 每个实例的基础顶点索引
- // 第一个三角形
- indices.push(base, base + 1, base + 2);
- // 第二个三角形
- indices.push(base + 2, base + 1, base + 3);
- }
-
- console.log('indices', indices);
-
- // VertexBuffer IndexBuffer 不能动态更改长度,需要一开始设定较大的长度。
- const vb = new Float32Array(gaussianCount * vertexSize);
- const ib = new Uint16Array(indices);
-
- console.log('vb', vb);
- console.log('ib', ib);
-
- const geo = scene.createGeometry(vl, vb, ib);
-
- geo.setBoundBall(new xrFrameSystem.Vector3(), 1);
- geo.addSubMesh(ib.length, 0, 0);
-
- return geo;
- });
-
-
- console.log('gaussianSplatting geo');
-
- xrFrameSystem.registerEffect('gaussianSplatting', createGSEffect);
-
- console.log('gaussianSplatting effect');
-
-
- this.geoElem = this.xrScene.createElement(xrFrameSystem.XRMesh, {
- geometry: "gaussian-splatting",
- position: "0 0 0",
- scale: "0.2 0.2 0.2"
- });
- this.geometryRoot.addChild(this.geoElem);
-
-
- console.log('init geo end');
-
-
- // 延时保证挂载与初始化完毕
- setTimeout(()=>{
- this.meshGeo = this.geoElem.getComponent(xrFrameSystem.Mesh);
- this.geometryGeo = this.meshGeo.geometry;
-
- this.matGeo = this.meshGeo.material;
-
- const gsMaterial = this.xrScene.createMaterial(
- // 使用定制的效果
- this.xrScene.assets.getAsset('effect', 'gaussianSplatting')
- );
- console.log('gsMaterial', gsMaterial)
-
- // 设定 绘制双面
- // gsMaterial.setRenderState("cullOn", false);
-
- const frameWidth = this.xrScene.frameWidth;
- const frameHeight = this.xrScene.frameHeight;
- const tan_fovy = Math.tan(60 / 180 * Math.PI * 0.5)
- const tan_fovx = tan_fovy * frameWidth / frameHeight
- const focal_y = frameHeight / (2 * tan_fovy)
- const focal_x = frameWidth / (2 * tan_fovx)
-
- console.log('gsMaterial', gsMaterial);
-
- console.log('frameWidth', frameWidth);
- console.log('frameHeight', frameHeight);
- console.log('tan_fovy', tan_fovy);
- console.log('tan_fovx', tan_fovx);
- console.log('focal_y', focal_y);
- console.log('focal_x', focal_x);
-
- // 设定屏幕相关uniform
- gsMaterial.setFloat('screen_width', frameWidth);
- gsMaterial.setFloat('screen_height', frameHeight);
- gsMaterial.setFloat('tan_fovy', tan_fovy);
- gsMaterial.setFloat('tan_fovx', tan_fovx);
- gsMaterial.setFloat('focal_y', focal_y);
- gsMaterial.setFloat('focal_x', focal_x);
-
-
- this.meshGeo.material = gsMaterial;
-
- console.log('meshGeo');
-
- // 初始化循环
- console.log('initRenderLoop');
- this.initRenderLoop();
-
- }, 200);
-
},
- initRenderLoop() {
- // this.loopTimer = setInterval(this.loop.bind(this), 2000);
- this.loopTimer = setTimeout(this.loop.bind(this), 2000);
-
- },
- loop() {
- // console.log(this.xrCamera._viewMatrix)
- this._worker.postMessage({
- type: 'execFunc_sort',
- params: [
- {
- viewMatrix: this.xrCamera._viewMatrix
- }
- ]
+ fail(res) {
+ wx.hideLoading()
+ wx.showToast({
+ title: res.errMsg,
+ icon: 'none',
+ duration: 2000
})
-
+ console.error(res)
+ }
+ })
+
+ // 监听worker回调
+ this._worker.onMessage((res) => {
+ if (res.type === 'execFunc_init') {
+ // 初始化 worker 回调
+ console.log('gaussianSplatting init callBack')
+ console.log('res', res)
+
+ this.initGSGeometry(res.result.count, res.result.vertexSize)
+ } else if (res.type === 'execFunc_sort') {
+ // worker 排序 回调
+ // console.log('gaussianSplatting sort callBack', res.result)
+
+ // const vb = getVertexBuffer(this.vertexData);
+
+ this.geometryGeo.uploadVertexBuffer(0, res.result.vertexBuffer)
+
+ // console.log('sort callback', this.geometryGeo, res.result.vertexBuffer)
+ }
+ })
+ },
+ initGSGeometry(gaussianCount, vertexSize) {
+ console.log('initGSGeometry start')
+
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const createGSEffect = (scene) => scene.createEffect({
+ name: 'gaussianSplatting',
+ defaultRenderQueue: 3000,
+ properties: [
+ {
+ key: 'screen_width',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'screen_height',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'focal_x',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'focal_y',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'tan_fovx',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'tan_fovy',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 0
+ },
+ {
+ key: 'scale_modifier',
+ type: xrFrameSystem.EUniformType.FLOAT,
+ default: 1
+ },
+ ],
+ images: [],
+ passes: [
+ {
+ renderStates: {
+ blendOn: true,
+ depthWrite: false,
+ cullOn: false,
+ },
+ lightMode: 'ForwardBase',
+ useMaterialRenderStates: true,
+ shaders: [0, 1]
+ }
+ ],
+ shaders: [
+ // Vertex Shader
+ splat_vs,
+ // Fragement Shader
+ splat_fs
+ ],
+ })
+
+ this.geometryRoot = this.xrScene.getElementById('geometryRoot')
+
+ console.log('geometryRoot', this.geometryRoot)
+
+ // 注册 Geometry 信息
+ xrFrameSystem.registerGeometry('gaussian-splatting', scene => {
+ console.log('registerGeometry')
+ const vl = scene.createVertexLayout({
+ attributes: [
+ {
+ name: 'a_center',
+ format: xrFrameSystem.EVertexFormat.FLOAT3,
+ offset: 0,
+ },
+ {
+ name: 'a_opacity',
+ format: xrFrameSystem.EVertexFormat.FLOAT,
+ offset: 12,
+ },
+ {
+ name: 'a_cov3Da',
+ format: xrFrameSystem.EVertexFormat.FLOAT3,
+ offset: 16,
+ },
+ {
+ name: 'a_cov3Db',
+ format: xrFrameSystem.EVertexFormat.FLOAT3,
+ offset: 28,
+ },
+ {
+ name: 'a_color',
+ format: xrFrameSystem.EVertexFormat.FLOAT3,
+ offset: 40,
+ },
+ {
+ name: 'a_corner',
+ format: xrFrameSystem.EVertexFormat.FLOAT2,
+ offset: 52,
+ },
+ ],
+ stride: 60
+ })
+
+ console.log('createVertexLayout')
+
+ const indices = []
+ const verticesPerInstance = 4
+ const instanceCount = gaussianCount / verticesPerInstance
+ for (let i = 0; i < instanceCount; i++) {
+ // 对于每个实例,添加6个索引以形成2个三角形
+ const base = i * 4 // 每个实例的基础顶点索引
+ // 第一个三角形
+ indices.push(base, base + 1, base + 2)
+ // 第二个三角形
+ indices.push(base + 2, base + 1, base + 3)
}
-}
\ No newline at end of file
+
+ console.log('indices', indices)
+
+ // VertexBuffer IndexBuffer 不能动态更改长度,需要一开始设定较大的长度。
+ const vb = new Float32Array(gaussianCount * vertexSize)
+ const ib = new Uint16Array(indices)
+
+ console.log('vb', vb)
+ console.log('ib', ib)
+
+ const geo = scene.createGeometry(vl, vb, ib)
+
+ geo.setBoundBall(new xrFrameSystem.Vector3(), 1)
+ geo.addSubMesh(ib.length, 0, 0)
+
+ return geo
+ })
+
+ console.log('gaussianSplatting geo')
+
+ xrFrameSystem.registerEffect('gaussianSplatting', createGSEffect)
+
+ console.log('gaussianSplatting effect')
+
+ this.geoElem = this.xrScene.createElement(xrFrameSystem.XRMesh, {
+ geometry: 'gaussian-splatting',
+ position: '0 0 0',
+ scale: '0.2 0.2 0.2'
+ })
+ this.geometryRoot.addChild(this.geoElem)
+
+ console.log('init geo end')
+
+ // 延时保证挂载与初始化完毕
+ setTimeout(() => {
+ this.meshGeo = this.geoElem.getComponent(xrFrameSystem.Mesh)
+ this.geometryGeo = this.meshGeo.geometry
+
+ this.matGeo = this.meshGeo.material
+
+ const gsMaterial = this.xrScene.createMaterial(
+ // 使用定制的效果
+ this.xrScene.assets.getAsset('effect', 'gaussianSplatting')
+ )
+ console.log('gsMaterial', gsMaterial)
+
+ // 设定 绘制双面
+ // gsMaterial.setRenderState("cullOn", false);
+
+ const frameWidth = this.xrScene.frameWidth
+ const frameHeight = this.xrScene.frameHeight
+ const tan_fovy = Math.tan(60 / 180 * Math.PI * 0.5)
+ const tan_fovx = tan_fovy * frameWidth / frameHeight
+ const focal_y = frameHeight / (2 * tan_fovy)
+ const focal_x = frameWidth / (2 * tan_fovx)
+
+ console.log('gsMaterial', gsMaterial)
+
+ console.log('frameWidth', frameWidth)
+ console.log('frameHeight', frameHeight)
+ console.log('tan_fovy', tan_fovy)
+ console.log('tan_fovx', tan_fovx)
+ console.log('focal_y', focal_y)
+ console.log('focal_x', focal_x)
+
+ // 设定屏幕相关uniform
+ gsMaterial.setFloat('screen_width', frameWidth)
+ gsMaterial.setFloat('screen_height', frameHeight)
+ gsMaterial.setFloat('tan_fovy', tan_fovy)
+ gsMaterial.setFloat('tan_fovx', tan_fovx)
+ gsMaterial.setFloat('focal_y', focal_y)
+ gsMaterial.setFloat('focal_x', focal_x)
+
+ this.meshGeo.material = gsMaterial
+
+ console.log('meshGeo')
+
+ // 初始化循环
+ console.log('initRenderLoop')
+ this.initRenderLoop()
+ }, 200)
+ },
+ initRenderLoop() {
+ // this.loopTimer = setInterval(this.loop.bind(this), 2000);
+ this.loopTimer = setTimeout(this.loop.bind(this), 2000)
+ },
+ loop() {
+ // console.log(this.xrCamera._viewMatrix)
+ this._worker.postMessage({
+ type: 'execFunc_sort',
+ params: [
+ {
+ viewMatrix: this.xrCamera._viewMatrix
+ }
+ ]
+ })
+ }
+}
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/cubeInstance-webGL.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/cubeInstance-webGL.js
index e6dc34d0..56aa5d0a 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/cubeInstance-webGL.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/cubeInstance-webGL.js
@@ -1,5 +1,4 @@
-
-const cubeVertexShader =
+const cubeVertexShader =
`
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
@@ -15,225 +14,221 @@ void main(void) {
vColor = aVertexColor;
}
-`;
+`
-const cubeFragmentShader =
+const cubeFragmentShader =
`
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
-`;
-
+`
class CubeInstanceWebGL {
-
- constructor(gl) {
-
- // -- Init Program
- const shaderProgram = initShaderProgram(gl, cubeVertexShader, cubeFragmentShader)
-
- this.vao = gl.createVertexArray();
- gl.bindVertexArray(this.vao);
- this.positionBuffer = this.initVertexBuffer(gl);
- this.colorBuffer = this.initColorBuffer(gl);
- this.indices = this.initIndexBuffer(gl);
-
- this.programInfo = {
- program: shaderProgram,
- attribLocations: {
- vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
- vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
- },
- uniformLocations: {
- projectionMatrix: gl.getUniformLocation( shaderProgram, "uProjectionMatrix"),
- viewMatrix: gl.getUniformLocation(shaderProgram, "uViewMatrix"),
- modelMatrix: gl.getUniformLocation(shaderProgram, "uModelMatrix"),
- },
- };
-
- // console.log('aVertexPosition', gl.getAttribLocation(shaderProgram, "aVertexPosition"))
- // console.log('aVertexColor', gl.getAttribLocation(shaderProgram, "aVertexColor"))
+ constructor(gl) {
+ // -- Init Program
+ const shaderProgram = initShaderProgram(gl, cubeVertexShader, cubeFragmentShader)
+
+ this.vao = gl.createVertexArray()
+ gl.bindVertexArray(this.vao)
+ this.positionBuffer = this.initVertexBuffer(gl)
+ this.colorBuffer = this.initColorBuffer(gl)
+ this.indices = this.initIndexBuffer(gl)
+
+ this.programInfo = {
+ program: shaderProgram,
+ attribLocations: {
+ vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
+ vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),
+ },
+ uniformLocations: {
+ projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
+ viewMatrix: gl.getUniformLocation(shaderProgram, 'uViewMatrix'),
+ modelMatrix: gl.getUniformLocation(shaderProgram, 'uModelMatrix'),
+ },
}
- initVertexBuffer(gl) {
- // Create a buffer for the square's positions.
- const positionBuffer = gl.createBuffer();
+ // console.log('aVertexPosition', gl.getAttribLocation(shaderProgram, "aVertexPosition"))
+ // console.log('aVertexColor', gl.getAttribLocation(shaderProgram, "aVertexColor"))
+ }
+
+ initVertexBuffer(gl) {
+ // Create a buffer for the square's positions.
+ const positionBuffer = gl.createBuffer()
- // Select the positionBuffer as the one to apply buffer
- // operations to from here out.
- gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
+ // Select the positionBuffer as the one to apply buffer
+ // operations to from here out.
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
- const positions = [
- // Front face
- -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
+ const positions = [
+ // Front face
+ -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
- // Back face
- -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
+ // Back face
+ -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
- // Top face
- -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
+ // Top face
+ -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
- // Bottom face
- -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
+ // Bottom face
+ -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
- // Right face
- 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
+ // Right face
+ 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
- // Left face
- -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
- ];
+ // Left face
+ -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
+ ]
- // Now pass the list of positions into WebGL to build the
- // shape. We do this by creating a Float32Array from the
- // JavaScript array, then use it to fill the current buffer.
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
+ // Now pass the list of positions into WebGL to build the
+ // shape. We do this by creating a Float32Array from the
+ // JavaScript array, then use it to fill the current buffer.
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW)
- return positionBuffer;
- }
+ return positionBuffer
+ }
- initColorBuffer(gl) {
- const faceColors = [
- [1.0, 1.0, 1.0, 1.0], // Front face: white
- [1.0, 0.0, 0.0, 1.0], // Back face: red
- [0.0, 1.0, 0.0, 1.0], // Top face: green
- [0.0, 0.0, 1.0, 1.0], // Bottom face: blue
- [1.0, 1.0, 0.0, 1.0], // Right face: yellow
- [1.0, 0.0, 1.0, 1.0], // Left face: purple
- ];
-
- // Convert the array of colors into a table for all the vertices.
-
- var colors = [];
-
- for (var j = 0; j < faceColors.length; ++j) {
- const c = faceColors[j];
- // Repeat each color four times for the four vertices of the face
- colors = colors.concat(c, c, c, c);
- }
-
- const colorBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
-
- return colorBuffer;
- }
+ initColorBuffer(gl) {
+ const faceColors = [
+ [1.0, 1.0, 1.0, 1.0], // Front face: white
+ [1.0, 0.0, 0.0, 1.0], // Back face: red
+ [0.0, 1.0, 0.0, 1.0], // Top face: green
+ [0.0, 0.0, 1.0, 1.0], // Bottom face: blue
+ [1.0, 1.0, 0.0, 1.0], // Right face: yellow
+ [1.0, 0.0, 1.0, 1.0], // Left face: purple
+ ]
+
+ // Convert the array of colors into a table for all the vertices.
+
+ let colors = []
- initIndexBuffer(gl) {
- const indexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
-
- // This array defines each face as two triangles, using the
- // indices into the vertex array to specify each triangle's
- // position.
-
- const indices = [
- 0,
- 1,
- 2,
- 0,
- 2,
- 3, // front
- 4,
- 5,
- 6,
- 4,
- 6,
- 7, // back
- 8,
- 9,
- 10,
- 8,
- 10,
- 11, // top
- 12,
- 13,
- 14,
- 12,
- 14,
- 15, // bottom
- 16,
- 17,
- 18,
- 16,
- 18,
- 19, // right
- 20,
- 21,
- 22,
- 20,
- 22,
- 23, // left
- ];
-
- // Now send the element array to GL
-
- gl.bufferData(
- gl.ELEMENT_ARRAY_BUFFER,
- new Uint16Array(indices),
- gl.STATIC_DRAW
- );
-
- return indexBuffer;
+ for (let j = 0; j < faceColors.length; ++j) {
+ const c = faceColors[j]
+ // Repeat each color four times for the four vertices of the face
+ colors = colors.concat(c, c, c, c)
}
+ const colorBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW)
+
+ return colorBuffer
+ }
+
+ initIndexBuffer(gl) {
+ const indexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
+
+ // This array defines each face as two triangles, using the
+ // indices into the vertex array to specify each triangle's
+ // position.
+
+ const indices = [
+ 0,
+ 1,
+ 2,
+ 0,
+ 2,
+ 3, // front
+ 4,
+ 5,
+ 6,
+ 4,
+ 6,
+ 7, // back
+ 8,
+ 9,
+ 10,
+ 8,
+ 10,
+ 11, // top
+ 12,
+ 13,
+ 14,
+ 12,
+ 14,
+ 15, // bottom
+ 16,
+ 17,
+ 18,
+ 16,
+ 18,
+ 19, // right
+ 20,
+ 21,
+ 22,
+ 20,
+ 22,
+ 23, // left
+ ]
+
+ // Now send the element array to GL
+
+ gl.bufferData(
+ gl.ELEMENT_ARRAY_BUFFER,
+ new Uint16Array(indices),
+ gl.STATIC_DRAW
+ )
+
+ return indexBuffer
+ }
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
- const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
- const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
-
- // Create the shader program
-
- const shaderProgram = gl.createProgram();
- gl.attachShader(shaderProgram, vertexShader);
- gl.attachShader(shaderProgram, fragmentShader);
- gl.linkProgram(shaderProgram);
-
- // If creating the shader program failed, alert
-
- if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
- console.error(
- `Unable to initialize the shader program: ${gl.getProgramInfoLog(
- shaderProgram
- )}`
- );
- return null;
- }
-
- return shaderProgram;
+ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource)
+ const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource)
+
+ // Create the shader program
+
+ const shaderProgram = gl.createProgram()
+ gl.attachShader(shaderProgram, vertexShader)
+ gl.attachShader(shaderProgram, fragmentShader)
+ gl.linkProgram(shaderProgram)
+
+ // If creating the shader program failed, alert
+
+ if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+ console.error(
+ `Unable to initialize the shader program: ${gl.getProgramInfoLog(
+ shaderProgram
+ )}`
+ )
+ return null
}
+ return shaderProgram
+}
+
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
- const shader = gl.createShader(type);
+ const shader = gl.createShader(type)
// Send the source to the shader object
- gl.shaderSource(shader, source);
+ gl.shaderSource(shader, source)
// Compile the shader program
- gl.compileShader(shader);
+ gl.compileShader(shader)
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
- );
- gl.deleteShader(shader);
- return null;
+ )
+ gl.deleteShader(shader)
+ return null
}
- return shader;
+ return shader
}
-export default CubeInstanceWebGL;
\ No newline at end of file
+export default CubeInstanceWebGL
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_fragment.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_fragment.glsl.js
index 8dbadcc6..d121649d 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_fragment.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_fragment.glsl.js
@@ -1,4 +1,4 @@
-export const splatFragmentShader =
+export const splatFragmentShader =
/* glsl */
`#version 300 es
precision mediump float;
@@ -46,4 +46,4 @@ void main() {
// fragColor = vec4(0.0, 0.0, 1.0, 1.0);
}
-`;
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_fragment.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_fragment.glsl.js
index 7082d9b7..167dde76 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_fragment.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_fragment.glsl.js
@@ -1,4 +1,4 @@
-export const splatRTFragmentShader =
+export const splatRTFragmentShader =
/* glsl */
`#version 300 es
precision mediump float;
@@ -12,4 +12,4 @@ out vec4 fragColor;
void main(void) {
fragColor = texture(u_splat, v_uv);
}
-`;
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_vertex.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_vertex.glsl.js
index d1617eab..f811b35e 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_vertex.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_rt_vertex.glsl.js
@@ -1,5 +1,4 @@
-
-export const splatRTVertexShader =
+export const splatRTVertexShader =
/* glsl */
`#version 300 es
in vec3 a_pos;
@@ -12,4 +11,4 @@ void main(void) {
v_uv = a_texCoord;
}
-`;
\ No newline at end of file
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_vertex.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_vertex.glsl.js
index f4d2d373..78ea5cda 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_vertex.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/splat_vertex.glsl.js
@@ -1,5 +1,4 @@
-
-export const splatVertexShader =
+export const splatVertexShader =
/* glsl */
`#version 300 es
in vec3 a_center;
@@ -140,4 +139,4 @@ void main() {
}
-`;
\ No newline at end of file
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_fragment.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_fragment.glsl.js
index 2388db30..81c00605 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_fragment.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_fragment.glsl.js
@@ -1,4 +1,4 @@
-export const YUVFragmentShader =
+export const YUVFragmentShader =
/* glsl */
`#version 300 es
precision mediump float;
@@ -26,4 +26,4 @@ void main(void) {
fragColor = vec4(R, G, B, 1.0);
}
-`;
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_vertex.glsl.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_vertex.glsl.js
index 73dc3bdb..04778b98 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_vertex.glsl.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/shaders/yuv_vertex.glsl.js
@@ -1,5 +1,4 @@
-
-export const YUVVertexShader =
+export const YUVVertexShader =
/* glsl */
`#version 300 es
in vec3 a_pos;
@@ -16,4 +15,4 @@ void main(void) {
v_uv = a_texCoord;
}
-`;
\ No newline at end of file
+`
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/splat-webGL.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/splat-webGL.js
index 40b5b666..7bda6a5b 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/splat-webGL.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/splat-webGL.js
@@ -1,184 +1,188 @@
-import { splatVertexShader } from './shaders/splat_vertex.glsl';
-import { splatFragmentShader } from './shaders/splat_fragment.glsl';
-import { splatRTVertexShader } from './shaders/splat_rt_vertex.glsl';
-import { splatRTFragmentShader } from './shaders/splat_rt_fragment.glsl';
+import { splatVertexShader } from './shaders/splat_vertex.glsl'
+import { splatFragmentShader } from './shaders/splat_fragment.glsl'
+import { splatRTVertexShader } from './shaders/splat_rt_vertex.glsl'
+import { splatRTFragmentShader } from './shaders/splat_rt_fragment.glsl'
class SplatWebGL {
+ constructor(gl) {
+ // Create shader program
+ const program = createProgram(gl, splatVertexShader, splatFragmentShader)
+
+ this.vao = gl.createVertexArray()
+ gl.bindVertexArray(this.vao)
+
+ const setupAttributeBuffer = (name, components) => {
+ const location = gl.getAttribLocation(program, name)
+ const buffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
+ gl.enableVertexAttribArray(location)
+ gl.vertexAttribPointer(location, components, gl.FLOAT, false, 0, 0)
+ gl.vertexAttribDivisor(location, 1)
+ return buffer
+ }
- constructor(gl) {
-
- // Create shader program
- const program = createProgram(gl, splatVertexShader, splatFragmentShader)
-
- this.vao = gl.createVertexArray();
- gl.bindVertexArray(this.vao);
-
- const setupAttributeBuffer = (name, components) => {
- const location = gl.getAttribLocation(program, name)
- const buffer = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
- gl.enableVertexAttribArray(location)
- gl.vertexAttribPointer(location, components, gl.FLOAT, false, 0, 0)
- gl.vertexAttribDivisor(location, 1)
- return buffer
- }
-
- // Create attribute buffers
- const buffers = {
- color: setupAttributeBuffer('a_col', 3),
- center: setupAttributeBuffer('a_center', 3),
- opacity: setupAttributeBuffer('a_opacity', 1),
- covA: setupAttributeBuffer('a_covA', 3),
- covB: setupAttributeBuffer('a_covB', 3),
- }
-
- this.program = program;
- this.buffers = buffers;
+ // Create attribute buffers
+ const buffers = {
+ color: setupAttributeBuffer('a_col', 3),
+ center: setupAttributeBuffer('a_center', 3),
+ opacity: setupAttributeBuffer('a_opacity', 1),
+ covA: setupAttributeBuffer('a_covA', 3),
+ covB: setupAttributeBuffer('a_covB', 3),
}
+
+ this.program = program
+ this.buffers = buffers
+ }
}
export class SplatRenderTexture {
-
- constructor(gl) {
- // 准备 RenderTexutre
- this.initRenderTexture(gl);
-
- // Create shader program
- const shaderProgram = createProgram(gl, splatRTVertexShader, splatRTFragmentShader);
-
- this.programInfo = {
- program: shaderProgram,
- attribLocations: {
- vertexPosition: gl.getAttribLocation(shaderProgram, "a_pos"),
- vertexTexcoord: gl.getAttribLocation(shaderProgram, "a_texCoord"),
- },
- uniformLocations: {
- uSplat: gl.getAttribLocation(shaderProgram, "u_splat"),
- },
- };
-
- // init VAO
- this.initVAO(gl);
+ constructor(gl) {
+ // 准备 RenderTexutre
+ this.initRenderTexture(gl)
+
+ // Create shader program
+ const shaderProgram = createProgram(gl, splatRTVertexShader, splatRTFragmentShader)
+
+ this.programInfo = {
+ program: shaderProgram,
+ attribLocations: {
+ vertexPosition: gl.getAttribLocation(shaderProgram, 'a_pos'),
+ vertexTexcoord: gl.getAttribLocation(shaderProgram, 'a_texCoord'),
+ },
+ uniformLocations: {
+ uSplat: gl.getAttribLocation(shaderProgram, 'u_splat'),
+ },
}
- initRenderTexture(gl) {
- const targetTextureWidth = gl.canvas.width;
- const targetTextureHeight = gl.canvas.height;
- const targetTexture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, targetTexture);
-
- this.renderTexture = targetTexture;
-
- // 定义0级的大小和格式
- const level = 0;
- const internalFormat = gl.RGBA;
- const border = 0;
- const format = gl.RGBA;
- const type = gl.UNSIGNED_BYTE;
- const data = null;
- gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
- targetTextureWidth, targetTextureHeight, border,
- format, type, data);
-
- // 设置过滤,这样我们就不需要 mips
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
-
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
-
- // 创建并绑定帧缓冲区
- const fb = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
-
- // 将纹理附加为第一个颜色附件
- const attachmentPoint = gl.COLOR_ATTACHMENT0;
- gl.framebufferTexture2D(
- gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, targetTexture, level);
-
- this.frameBuffer = fb;
- this.rt = targetTexture;
+ // init VAO
+ this.initVAO(gl)
+ }
+
+ initRenderTexture(gl) {
+ const targetTextureWidth = gl.canvas.width
+ const targetTextureHeight = gl.canvas.height
+ const targetTexture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, targetTexture)
+
+ this.renderTexture = targetTexture
+
+ // 定义0级的大小和格式
+ const level = 0
+ const internalFormat = gl.RGBA
+ const border = 0
+ const format = gl.RGBA
+ const type = gl.UNSIGNED_BYTE
+ const data = null
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ level,
+ internalFormat,
+ targetTextureWidth,
+ targetTextureHeight,
+ border,
+ format,
+ type,
+ data
+ )
+
+ // 设置过滤,这样我们就不需要 mips
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+
+ // 创建并绑定帧缓冲区
+ const fb = gl.createFramebuffer()
+ gl.bindFramebuffer(gl.FRAMEBUFFER, fb)
+
+ // 将纹理附加为第一个颜色附件
+ const attachmentPoint = gl.COLOR_ATTACHMENT0
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, targetTexture, level)
+
+ this.frameBuffer = fb
+ this.rt = targetTexture
+ }
+
+ initVAO(gl) {
+ this.vao = gl.createVertexArray()
+ gl.bindVertexArray(this.vao)
+
+ // positionBuffer
+ const positionBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
+ const positions = [
+ -1.0, -1.0, 0.0,
+ 1.0, -1.0, 0.0,
+ 1.0, 1.0, 0.0,
+ -1.0, 1.0, 0.0,
+ ]
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW)
+
+ // texCoordBuffer
+ const texCoordBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer)
+ // filpY
+ const texCoord = [
+ 0, 0,
+ 1, 0,
+ 1, 1,
+ 0, 1
+ ]
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoord), gl.STATIC_DRAW)
+
+ // indexBuffer
+ const indexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
+ const indices = [
+ 0,
+ 1,
+ 2,
+ 0,
+ 2,
+ 3
+ ]
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW)
+
+ // Create attribute buffers
+ const buffers = {
+ position: positionBuffer,
+ texCoord: texCoordBuffer,
+ indices: indexBuffer
}
- initVAO(gl) {
- this.vao = gl.createVertexArray();
- gl.bindVertexArray(this.vao);
-
- // positionBuffer
- const positionBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
- const positions = [
- -1.0, -1.0, 0.0,
- 1.0, -1.0, 0.0,
- 1.0, 1.0, 0.0,
- -1.0, 1.0, 0.0,
- ];
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
-
- // texCoordBuffer
- const texCoordBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
- // filpY
- const texCoord = [
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- ];
- gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(texCoord), gl.STATIC_DRAW );
-
- // indexBuffer
- const indexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- const indices = [
- 0,
- 1,
- 2,
- 0,
- 2,
- 3
- ];
- gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW );
-
- // Create attribute buffers
- const buffers = {
- position: positionBuffer,
- texCoord: texCoordBuffer,
- indices: indexBuffer
- }
-
- this.buffers = buffers;
- }
+ this.buffers = buffers
+ }
}
// Create a program from a vertex and fragment shader
function createProgram(gl, vertexShaderSource, fragmentShaderSource) {
- const program = gl.createProgram()
+ const program = gl.createProgram()
- const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
- const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)
- gl.attachShader(program, vertexShader)
- gl.attachShader(program, fragmentShader)
- gl.linkProgram(program)
+ const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
+ const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)
+ gl.attachShader(program, vertexShader)
+ gl.attachShader(program, fragmentShader)
+ gl.linkProgram(program)
- const success = gl.getProgramParameter(program, gl.LINK_STATUS)
- if (success) return program
+ const success = gl.getProgramParameter(program, gl.LINK_STATUS)
+ if (success) return program
- console.log(gl.getProgramInfoLog(program))
- gl.deleteProgram(program)
+ console.log(gl.getProgramInfoLog(program))
+ gl.deleteProgram(program)
}
// Create and compile a shader from source
function createShader(gl, type, source) {
- const shader = gl.createShader(type)
- gl.shaderSource(shader, source)
- gl.compileShader(shader)
+ const shader = gl.createShader(type)
+ gl.shaderSource(shader, source)
+ gl.compileShader(shader)
- const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
- if (success) return shader
+ if (success) return shader
- console.log(gl.getShaderInfoLog(shader))
- gl.deleteShader(shader)
+ console.log(gl.getShaderInfoLog(shader))
+ gl.deleteShader(shader)
}
-export default SplatWebGL;
\ No newline at end of file
+export default SplatWebGL
diff --git a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/yuv-webGL.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/yuv-webGL.js
index 9e356752..0475df34 100644
--- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/yuv-webGL.js
+++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/webgl2/yuv-webGL.js
@@ -1,112 +1,108 @@
-
-import { YUVVertexShader } from './shaders/yuv_vertex.glsl';
-import { YUVFragmentShader } from './shaders/yuv_fragment.glsl';
-
+import { YUVVertexShader } from './shaders/yuv_vertex.glsl'
+import { YUVFragmentShader } from './shaders/yuv_fragment.glsl'
export class YUVRenderWebGL {
-
- constructor(gl) {
-
- // Create shader program
- const shaderProgram = createProgram(gl, YUVVertexShader, YUVFragmentShader);
-
- this.programInfo = {
- program: shaderProgram,
- attribLocations: {
- vertexPosition: gl.getAttribLocation(shaderProgram, "a_pos"),
- vertexTexcoord: gl.getAttribLocation(shaderProgram, "a_texCoord"),
- },
- uniformLocations: {
- displayTransform: gl.getUniformLocation(shaderProgram, "u_displayTransform"),
- yTexture: gl.getUniformLocation(shaderProgram, "u_y_texture"),
- uvTexture: gl.getUniformLocation(shaderProgram, "u_uv_texture"),
- },
- };
-
- // init VAO
- this.initVAO(gl);
+ constructor(gl) {
+ // Create shader program
+ const shaderProgram = createProgram(gl, YUVVertexShader, YUVFragmentShader)
+
+ this.programInfo = {
+ program: shaderProgram,
+ attribLocations: {
+ vertexPosition: gl.getAttribLocation(shaderProgram, 'a_pos'),
+ vertexTexcoord: gl.getAttribLocation(shaderProgram, 'a_texCoord'),
+ },
+ uniformLocations: {
+ displayTransform: gl.getUniformLocation(shaderProgram, 'u_displayTransform'),
+ yTexture: gl.getUniformLocation(shaderProgram, 'u_y_texture'),
+ uvTexture: gl.getUniformLocation(shaderProgram, 'u_uv_texture'),
+ },
}
- initVAO(gl) {
- this.vao = gl.createVertexArray();
- gl.bindVertexArray(this.vao);
-
- // positionBuffer
- const positionBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
- const positions = [
- -1.0, -1.0, 0.0,
- 1.0, -1.0, 0.0,
- 1.0, 1.0, 0.0,
- -1.0, 1.0, 0.0,
- ];
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
-
- // texCoordBuffer
- const texCoordBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer);
- // filpY
- const texCoord = [
- 0, 0,
- 1, 0,
- 1, 1,
- 0, 1
- ];
- gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(texCoord), gl.STATIC_DRAW );
-
- // indexBuffer
- const indexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
- const indices = [
- 0,
- 1,
- 2,
- 0,
- 2,
- 3
- ];
- gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW );
-
- // Create attribute buffers
- const buffers = {
- position: positionBuffer,
- texCoord: texCoordBuffer,
- indices: indexBuffer
- }
-
- this.buffers = buffers;
+ // init VAO
+ this.initVAO(gl)
+ }
+
+ initVAO(gl) {
+ this.vao = gl.createVertexArray()
+ gl.bindVertexArray(this.vao)
+
+ // positionBuffer
+ const positionBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
+ const positions = [
+ -1.0, -1.0, 0.0,
+ 1.0, -1.0, 0.0,
+ 1.0, 1.0, 0.0,
+ -1.0, 1.0, 0.0,
+ ]
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW)
+
+ // texCoordBuffer
+ const texCoordBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer)
+ // filpY
+ const texCoord = [
+ 0, 0,
+ 1, 0,
+ 1, 1,
+ 0, 1
+ ]
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoord), gl.STATIC_DRAW)
+
+ // indexBuffer
+ const indexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
+ const indices = [
+ 0,
+ 1,
+ 2,
+ 0,
+ 2,
+ 3
+ ]
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW)
+
+ // Create attribute buffers
+ const buffers = {
+ position: positionBuffer,
+ texCoord: texCoordBuffer,
+ indices: indexBuffer
}
+
+ this.buffers = buffers
+ }
}
// Create a program from a vertex and fragment shader
function createProgram(gl, vertexShaderSource, fragmentShaderSource) {
- const program = gl.createProgram()
+ const program = gl.createProgram()
- const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
- const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)
- gl.attachShader(program, vertexShader)
- gl.attachShader(program, fragmentShader)
- gl.linkProgram(program)
+ const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource)
+ const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource)
+ gl.attachShader(program, vertexShader)
+ gl.attachShader(program, fragmentShader)
+ gl.linkProgram(program)
- const success = gl.getProgramParameter(program, gl.LINK_STATUS)
- if (success) return program
+ const success = gl.getProgramParameter(program, gl.LINK_STATUS)
+ if (success) return program
- console.log(gl.getProgramInfoLog(program))
- gl.deleteProgram(program)
+ console.log(gl.getProgramInfoLog(program))
+ gl.deleteProgram(program)
}
// Create and compile a shader from source
function createShader(gl, type, source) {
- const shader = gl.createShader(type)
- gl.shaderSource(shader, source)
- gl.compileShader(shader)
+ const shader = gl.createShader(type)
+ gl.shaderSource(shader, source)
+ gl.compileShader(shader)
- const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
- if (success) return shader
+ if (success) return shader
- console.log(gl.getShaderInfoLog(shader))
- gl.deleteShader(shader)
+ console.log(gl.getShaderInfoLog(shader))
+ gl.deleteShader(shader)
}
-export default YUVRenderWebGL;
\ No newline at end of file
+export default YUVRenderWebGL
diff --git a/miniprogram/packageAPI/pages/ar/hand-detect-3d/hand-detect-3d.js b/miniprogram/packageAPI/pages/ar/hand-detect-3d/hand-detect-3d.js
index c1162f5c..a3ef4110 100644
--- a/miniprogram/packageAPI/pages/ar/hand-detect-3d/hand-detect-3d.js
+++ b/miniprogram/packageAPI/pages/ar/hand-detect-3d/hand-detect-3d.js
@@ -5,40 +5,40 @@ import xrFrameBehavior from '../behavior/behavior-xrframe'
const NEAR = 0.01
const FAR = 1000
-let loggerOnce = false;
+const loggerOnce = false
Component({
behaviors: [arBehavior, xrFrameBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.8, // canvas高度缩放值
- hintBoxList: [], // 显示提示盒子列表
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.8, // canvas高度缩放值
+ hintBoxList: [], // 显示提示盒子列表
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
hintInfo: undefined, // 提示框信息
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ }
+ },
},
methods: {
@@ -46,7 +46,7 @@ Component({
init() {
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
@@ -58,7 +58,7 @@ Component({
},
version: 'v1',
gl: this.gl
- });
+ })
try {
session.start(err => {
@@ -68,22 +68,22 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// 开启三维识别
- session.update3DMode({open3d: true})
+ session.update3DMode({ open3d: true })
// VKSession EVENT addAnchors
session.on('addAnchors', anchors => {
- console.log("addAnchor", anchors)
+ console.log('addAnchor', anchors)
})
// VKSession EVENT updateAnchors
session.on('updateAnchors', anchors => {
// console.log("updateAnchors", anchors);
- const anchor = anchors[0];
+ const anchor = anchors[0]
// 目前只处理一个返回的手
if (anchor) {
// console.log('id', anchor.id);
@@ -94,56 +94,51 @@ Component({
// console.log('size', anchor.size);
// console.log('detectId', anchor.detectId);
// console.log('confidence', anchor.confidence);
- // console.log('points3d', anchor.points3d);
+ // console.log('points3d', anchor.points3d);
- this.wrapTransform = anchor.transform;
- this.position3D = anchor.points3d;
-
- this.updateHintBoxVisble(this.hintBoxList, true);
+ this.wrapTransform = anchor.transform
+ this.position3D = anchor.points3d
+ this.updateHintBoxVisble(this.hintBoxList, true)
}
})
-
+
// VKSession removeAnchors
// 识别目标丢失时不断触发
session.on('removeAnchors', anchors => {
// console.log("removeAnchors");
- this.updateHintBoxVisble(this.hintBoxList, false);
- });
-
+ this.updateHintBoxVisble(this.hintBoxList, false)
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
- } catch(e) {
- console.error(e);
+ this.initLoop()
+ })
+ } catch (e) {
+ console.error(e)
}
-
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
// 缓存主相机
this.xrCameraMain = this.xrCamera
- this.xrCameraMainTrs = this.xrCameraTrs;
-
+ this.xrCameraMainTrs = this.xrCameraTrs
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// === 初始s手挂载点 ===
- this.handWrap = scene.createElement(xrFrameSystem.XRNode);
- this.handWrapTrs = this.handWrap.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( this.handWrap );
+ this.handWrap = scene.createElement(xrFrameSystem.XRNode)
+ this.handWrapTrs = this.handWrap.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(this.handWrap)
// 加载提示点
- this.hintBoxList = this.getHintBox(xrFrameSystem, scene, this.handWrap);
-
+ this.hintBoxList = this.getHintBox(xrFrameSystem, scene, this.handWrap)
},
loop() {
// console.log('loop')
@@ -152,75 +147,74 @@ Component({
const frame = this.session.getVKFrame(this.data.width, this.data.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
// 存在handWrap,执行信息同步逻辑
if (this.handWrap && this.wrapTransform) {
- const xrFrameSystem = wx.getXrFrameSystem();
-
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ const xrFrameSystem = wx.getXrFrameSystem()
+
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(this.wrapTransform);
- this.DT.transpose(this.DT2);
- this.handWrapTrs.setLocalMatrix(this.DT2);
+ this.DT.setArray(this.wrapTransform)
+ this.DT.transpose(this.DT2)
+ this.handWrapTrs.setLocalMatrix(this.DT2)
// 更新提示点位置
- this.updateHintBoxPosition(this.hintBoxList, this.position3D);
-
+ this.updateHintBoxPosition(this.hintBoxList, this.position3D)
}
},
getHintBox(xrFrameSystem, scene, wrap) {
// 初始化提示点
- const geometryHint = scene.assets.getAsset('geometry', 'sphere');
- const effectCube = scene.assets.getAsset('effect', 'standard');
- const boxScale = 0.006;
- const hintBoxList = [];
+ const geometryHint = scene.assets.getAsset('geometry', 'sphere')
+ const effectCube = scene.assets.getAsset('effect', 'standard')
+ const boxScale = 0.006
+ const hintBoxList = []
for (let i = 0; i < 16; i++) {
- const colorFloat = i / 16;
+ const colorFloat = i / 16
const el = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
+ position: '0 0 0',
scale: `${boxScale} ${boxScale} ${boxScale}`,
- });
- const elTrs = el.getComponent(xrFrameSystem.Transform);
- const mat = scene.createMaterial(effectCube);
-
- const colorR = 1.0 - colorFloat;
- mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0));
+ })
+ const elTrs = el.getComponent(xrFrameSystem.Transform)
+ const mat = scene.createMaterial(effectCube)
+
+ const colorR = 1.0 - colorFloat
+ mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, colorR, colorR, 1.0))
const mesh = el.addComponent(xrFrameSystem.Mesh, {
geometry: geometryHint,
material: mat,
- });
+ })
+
+ wrap.addChild(el)
+ elTrs.visible = false
- wrap.addChild( el );
- elTrs.visible = false;
-
- hintBoxList.push( elTrs );
+ hintBoxList.push(elTrs)
}
- return hintBoxList;
+ return hintBoxList
},
updateHintBoxPosition(hintBoxList, points3d) {
if (hintBoxList && hintBoxList.length > 0) {
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
- hintBox.position.x = points3d[i].x;
- hintBox.position.y = points3d[i].y;
- hintBox.position.z = points3d[i].z;
+ const hintBox = hintBoxList[i]
+ hintBox.position.x = points3d[i].x
+ hintBox.position.y = points3d[i].y
+ hintBox.position.z = points3d[i].z
}
}
},
@@ -229,13 +223,13 @@ Component({
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
+ const hintBox = hintBoxList[i]
if (hintBox.visible !== visible) {
- hintBox.visible = visible;
+ hintBox.visible = visible
}
}
}
}
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/hand-detect/behavior.js b/miniprogram/packageAPI/pages/ar/hand-detect/behavior.js
index d5601218..b24d6cf5 100644
--- a/miniprogram/packageAPI/pages/ar/hand-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/hand-detect/behavior.js
@@ -1,202 +1,201 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- cameraPosition: 0
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ cameraPosition: 0
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- hand: {
- mode: 1
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- this.data.anchor2DList = anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- }))
- })
-
- session.on('updateAnchors', anchors => {
- this.data.anchor2DList = []
- // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
- this.data.anchor2DList = this.data.anchor2DList.concat(anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })))
- })
-
- session.on('removeAnchors', anchors => {
- this.data.anchor2DList = []
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ hand: {
+ mode: 1
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ this.data.anchor2DList = anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ }))
+ })
+
+ session.on('updateAnchors', anchors => {
+ this.data.anchor2DList = []
+ // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
+ this.data.anchor2DList = this.data.anchor2DList.concat(anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })))
+ })
+
+ session.on('removeAnchors', anchors => {
+ this.data.anchor2DList = []
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/hand-detect/hand-detect.js b/miniprogram/packageAPI/pages/ar/hand-detect/hand-detect.js
index 55cccf2a..a1671252 100644
--- a/miniprogram/packageAPI/pages/ar/hand-detect/hand-detect.js
+++ b/miniprogram/packageAPI/pages/ar/hand-detect/hand-detect.js
@@ -4,70 +4,69 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-//顶点着色器
-var VSHADER_SOURCE = '' +
- 'attribute vec4 a_Position;\n' + //声明attribute变量a_Position,用来存放顶点位置信息
+// 顶点着色器
+const VSHADER_SOURCE = '' +
+ 'attribute vec4 a_Position;\n' + // 声明attribute变量a_Position,用来存放顶点位置信息
'void main(){\n' +
- ' gl_Position = a_Position;\n' + //将顶点坐标赋值给顶点着色器内置变量gl_Position
- ' gl_PointSize = 4.0;\n' + //设置顶点大小
+ ' gl_Position = a_Position;\n' + // 将顶点坐标赋值给顶点着色器内置变量gl_Position
+ ' gl_PointSize = 4.0;\n' + // 设置顶点大小
'}\n'
-//片元着色器
-var FSHADER_SOURCE = '' +
+// 片元着色器
+const FSHADER_SOURCE = '' +
'#ifdef GL_ES\n' +
' precision mediump float;\n' + // 设置精度
'#endif\n' +
- 'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
+ 'varying vec4 v_Color;\n' + // 声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
'void main(){\n' +
- ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + //计算像素距离中心点的距离
- ' if(d < 0.5) {\n' + //距离大于0.5放弃片元,小于0.5保留片元
+ ' float d = distance(gl_PointCoord, vec2(0.5, 0.5));\n' + // 计算像素距离中心点的距离
+ ' if(d < 0.5) {\n' + // 距离大于0.5放弃片元,小于0.5保留片元
' gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n' +
' } else { discard; }\n' +
'}\n'
-
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
- //创建顶点着色器对象
- var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
- //创建片元着色器对象
- var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
+ // 创建顶点着色器对象
+ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
+ // 创建片元着色器对象
+ const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
if (!vertexShader || !fragmentShader) {
return null
}
- //创建程序对象program
- var program = gl.createProgram()
+ // 创建程序对象program
+ const program = gl.createProgram()
if (!gl.createProgram()) {
return null
}
- //分配顶点着色器和片元着色器到program
+ // 分配顶点着色器和片元着色器到program
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
- //链接program
+ // 链接program
gl.linkProgram(program)
- //检查程序对象是否连接成功
- var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
+ // 检查程序对象是否连接成功
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS)
if (!linked) {
- var error = gl.getProgramInfoLog(program)
+ const error = gl.getProgramInfoLog(program)
console.log('程序对象连接失败: ' + error)
gl.deleteProgram(program)
gl.deleteShader(fragmentShader)
gl.deleteShader(vertexShader)
return null
}
- //返回程序program对象
+ // 返回程序program对象
initShadersDone = true
return program
}
function loadShader(gl, type, source) {
// 创建顶点着色器对象
- var shader = gl.createShader(type)
+ const shader = gl.createShader(type)
if (shader == null) {
console.log('创建着色器失败')
return null
@@ -80,9 +79,9 @@ function loadShader(gl, type, source) {
gl.compileShader(shader)
// 检查顶是否编译成功
- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!compiled) {
- var error = gl.getShaderInfoLog(shader)
+ const error = gl.getShaderInfoLog(shader)
console.log('编译着色器失败: ' + error)
gl.deleteShader(shader)
return null
@@ -91,9 +90,8 @@ function loadShader(gl, type, source) {
return shader
}
-//初始化顶点坐标和顶点颜色
+// 初始化顶点坐标和顶点颜色
function initVertexBuffers(gl, anchor2DList) {
-
const flattenPoints = []
anchor2DList.forEach(anchor => {
anchor.points.forEach(point => {
@@ -105,23 +103,23 @@ function initVertexBuffers(gl, anchor2DList) {
})
})
- var vertices = new Float32Array(flattenPoints)
- var n = flattenPoints.length / 2
+ const vertices = new Float32Array(flattenPoints)
+ const n = flattenPoints.length / 2
- //创建缓冲区对象
- var buffer = gl.createBuffer()
- //将顶点坐标和顶点颜色信息写入缓冲区对象
+ // 创建缓冲区对象
+ const buffer = gl.createBuffer()
+ // 将顶点坐标和顶点颜色信息写入缓冲区对象
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
- //获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
- var a_Position = gl.getAttribLocation(gl.program, 'a_Position')
+ // 获取顶点着色器attribute变量a_Position存储地址, 分配缓存并开启
+ const a_Position = gl.getAttribLocation(gl.program, 'a_Position')
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)
gl.enableVertexAttribArray(a_Position)
return n
}
-var EDGE_VSHADER_SOURCE =
+const EDGE_VSHADER_SOURCE =
`
attribute vec2 aPosition;
varying vec2 posJudge;
@@ -132,7 +130,7 @@ var EDGE_VSHADER_SOURCE =
}
`
-var EDGE_FSHADER_SOURCE =
+const EDGE_FSHADER_SOURCE =
`
precision highp float;
uniform vec2 rightTopPoint;
@@ -162,48 +160,47 @@ var EDGE_FSHADER_SOURCE =
`
function initRectEdgeBuffer(gl, x, y, width, height) {
- let shaderProgram = gl.program;
- let centerX = x * 2 - 1 + width;
- let centerY = -1 * (y * 2 - 1) - height;
- let right = width;
- let top = height;
- var vertices = [
+ const shaderProgram = gl.program
+ const centerX = x * 2 - 1 + width
+ const centerY = -1 * (y * 2 - 1) - height
+ const right = width
+ const top = height
+ const vertices = [
-1.0, 1.0,
-1.0, -1.0,
1.0, 1.0,
1.0, -1.0
- ];
+ ]
- var vertexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
- var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');
- gl.enableVertexAttribArray(aPosition);
- gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
+ const vertexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
+ const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition')
+ gl.enableVertexAttribArray(aPosition)
+ gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
-
- var rightTop = [
+ const rightTop = [
right, top
- ];
- var rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint');
- gl.uniform2fv(rightTopLoc, rightTop);
+ ]
+ const rightTopLoc = gl.getUniformLocation(shaderProgram, 'rightTopPoint')
+ gl.uniform2fv(rightTopLoc, rightTop)
- var centerPoint = [
+ const centerPoint = [
centerX, centerY
- ];
- var centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint');
- gl.uniform2fv(centerPointLoc, centerPoint);
+ ]
+ const centerPointLoc = gl.getUniformLocation(shaderProgram, 'centerPoint')
+ gl.uniform2fv(centerPointLoc, centerPoint)
- var length = vertices.length / 2;
+ const length = vertices.length / 2
- return length;
+ return length
}
function onDrawRectEdge(gl, x, y, width, height) {
width = Math.round(width * 100) / 100
height = Math.round(height * 100) / 100
- var n = initRectEdgeBuffer(gl, x, y, width, height);
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
+ const n = initRectEdgeBuffer(gl, x, y, width, height)
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, n)
}
Component({
@@ -217,15 +214,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -243,19 +240,19 @@ Component({
init() {
this.initGL()
},
- switchCamera(event){
- if(this.session.config){
+ switchCamera(event) {
+ if (this.session.config) {
const config = this.session.config
- let pos = Number(event.currentTarget.dataset.value)
+ const pos = Number(event.currentTarget.dataset.value)
config.cameraPosition = pos
this.session.config = config
this.setData({
- cameraPosition:event.currentTarget.dataset.value
+ cameraPosition: event.currentTarget.dataset.value
})
}
},
render(frame) {
- var gl = this.gl
+ const gl = this.gl
this.renderGL(frame)
@@ -279,7 +276,7 @@ Component({
const anchor2DList = this.data.anchor2DList
if (!anchor2DList || anchor2DList.length <= 0) {
- return
+
} else {
if (!initShadersDone) {
this.vertexProgram = initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)
@@ -293,19 +290,19 @@ Component({
gl.useProgram(this.vertexProgram)
gl.program = this.vertexProgram
- //初始化顶点坐标和顶点颜色
- var n = initVertexBuffers(gl, anchor2DList)
+ // 初始化顶点坐标和顶点颜色
+ const n = initVertexBuffers(gl, anchor2DList)
- //绘制点
+ // 绘制点
gl.drawArrays(gl.POINTS, 0, n)
gl.useProgram(this.rectEdgeProgram)
gl.program = this.rectEdgeProgram
- for (var i = 0; i < anchor2DList.length; i++) {
+ for (let i = 0; i < anchor2DList.length; i++) {
onDrawRectEdge(gl, anchor2DList[i].origin.x, anchor2DList[i].origin.y, anchor2DList[i].size.width, anchor2DList[i].size.height)
}
}
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/hand-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/hand-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/hand-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/hand-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/loaders/gltf-clone.js b/miniprogram/packageAPI/pages/ar/loaders/gltf-clone.js
index f4964653..01b135e0 100644
--- a/miniprogram/packageAPI/pages/ar/loaders/gltf-clone.js
+++ b/miniprogram/packageAPI/pages/ar/loaders/gltf-clone.js
@@ -1,4 +1,4 @@
-export default function(gltf, THREE) {
+export default function (gltf, THREE) {
const clone = {
animations: gltf.animations,
scene: gltf.scene.clone(true)
@@ -25,7 +25,7 @@ export default function(gltf, THREE) {
}
})
- for (let name in skinnedMeshes) {
+ for (const name in skinnedMeshes) {
const skinnedMesh = skinnedMeshes[name]
const skeleton = skinnedMesh.skeleton
const cloneSkinnedMesh = cloneSkinnedMeshes[name]
diff --git a/miniprogram/packageAPI/pages/ar/loaders/gltf-loader.js b/miniprogram/packageAPI/pages/ar/loaders/gltf-loader.js
index aff17d89..a8b9d75b 100644
--- a/miniprogram/packageAPI/pages/ar/loaders/gltf-loader.js
+++ b/miniprogram/packageAPI/pages/ar/loaders/gltf-loader.js
@@ -1,16 +1,16 @@
export function registerGLTFLoader(THREE) {
- THREE.GLTFLoader = (function() {
+ THREE.GLTFLoader = (function () {
function GLTFLoader() {
- this.manager = THREE.DefaultLoadingManager;
- this.dracoLoader = null;
+ this.manager = THREE.DefaultLoadingManager
+ this.dracoLoader = null
this.ddsLoader = null
}
GLTFLoader.prototype = {
constructor: GLTFLoader,
crossOrigin: 'anonymous',
- load: function(url, onLoad) {
- var scope = this;
- var resourcePath;
+ load(url, onLoad) {
+ const scope = this
+ let resourcePath
if (this.resourcePath !== undefined) {
resourcePath = this.resourcePath
} else if (this.path !== undefined) {
@@ -18,42 +18,48 @@ export function registerGLTFLoader(THREE) {
} else {
resourcePath = THREE.LoaderUtils.extractUrlBase(url)
}
- scope.manager.itemStart(url);
- var _onError = function(e) {
- console.error(e);
- scope.manager.itemError(url);
+ scope.manager.itemStart(url)
+ const _onError = function (e) {
+ console.error(e)
+ scope.manager.itemError(url)
scope.manager.itemEnd(url)
- };
- var loader = new THREE.FileLoader(scope.manager);
- loader.setPath(this.path);
- loader.setResponseType('arraybuffer');
- loader.load(url,
- function(data) {
- try {
- scope.parse(data, resourcePath,
- function(gltf) {
- onLoad(gltf);
- scope.manager.itemEnd(url)
- },
- _onError)
- } catch(e) {
- _onError(e)
- }
- },
- null, _onError)
+ }
+ const loader = new THREE.FileLoader(scope.manager)
+ loader.setPath(this.path)
+ loader.setResponseType('arraybuffer')
+ loader.load(
+ url,
+ function (data) {
+ try {
+ scope.parse(
+ data,
+ resourcePath,
+ function (gltf) {
+ onLoad(gltf)
+ scope.manager.itemEnd(url)
+ },
+ _onError
+ )
+ } catch (e) {
+ _onError(e)
+ }
+ },
+ null,
+ _onError
+ )
},
- parse: function(data, path, onLoad, onError) {
- var content;
- var extensions = {};
+ parse(data, path, onLoad, onError) {
+ let content
+ const extensions = {}
if (typeof data === 'string') {
content = data
} else {
- var magic = THREE.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
+ const magic = THREE.LoaderUtils.decodeText(new Uint8Array(data, 0, 4))
if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
try {
extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data)
- } catch(error) {
- if (onError) onError(error);
+ } catch (error) {
+ if (onError) onError(error)
return
}
content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content
@@ -61,62 +67,62 @@ export function registerGLTFLoader(THREE) {
content = THREE.LoaderUtils.decodeText(new Uint8Array(data))
}
}
- var json = JSON.parse(content);
+ const json = JSON.parse(content)
if (json.asset === undefined || json.asset.version[0] < 2) {
- if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'));
+ if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.'))
return
}
if (json.extensionsUsed) {
- for (var i = 0; i < json.extensionsUsed.length; ++i) {
- var extensionName = json.extensionsUsed[i];
- var extensionsRequired = json.extensionsRequired || [];
+ for (let i = 0; i < json.extensionsUsed.length; ++i) {
+ const extensionName = json.extensionsUsed[i]
+ const extensionsRequired = json.extensionsRequired || []
switch (extensionName) {
- case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
- extensions[extensionName] = new GLTFLightsExtension(json);
- break;
- case EXTENSIONS.KHR_MATERIALS_UNLIT:
- extensions[extensionName] = new GLTFMaterialsUnlitExtension();
- break;
- case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
- extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
- break;
- case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
- extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
- break;
- case EXTENSIONS.MSFT_TEXTURE_DDS:
- extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader);
- break;
- case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
- extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension();
- break;
- default:
- if (extensionsRequired.indexOf(extensionName) >= 0) {
- console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".')
- }
+ case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
+ extensions[extensionName] = new GLTFLightsExtension(json)
+ break
+ case EXTENSIONS.KHR_MATERIALS_UNLIT:
+ extensions[extensionName] = new GLTFMaterialsUnlitExtension()
+ break
+ case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
+ extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension()
+ break
+ case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
+ extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader)
+ break
+ case EXTENSIONS.MSFT_TEXTURE_DDS:
+ extensions[EXTENSIONS.MSFT_TEXTURE_DDS] = new GLTFTextureDDSExtension(this.ddsLoader)
+ break
+ case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
+ extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] = new GLTFTextureTransformExtension()
+ break
+ default:
+ if (extensionsRequired.indexOf(extensionName) >= 0) {
+ console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".')
+ }
}
}
}
- var parser = new GLTFParser(json, extensions, {
+ const parser = new GLTFParser(json, extensions, {
path: path || this.resourcePath || '',
crossOrigin: this.crossOrigin,
manager: this.manager
- });
+ })
parser.parse(onLoad, onError)
}
- };
+ }
function GLTFRegistry() {
- var objects = {};
+ let objects = {}
return {
- get: function(key) {
+ get(key) {
return objects[key]
},
- add: function(key, object) {
+ add(key, object) {
objects[key] = object
},
- remove: function(key) {
+ remove(key) {
delete objects[key]
},
- removeAll: function() {
+ removeAll() {
objects = {}
}
}
@@ -129,70 +135,70 @@ export function registerGLTFLoader(THREE) {
KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
- };
+ }
function GLTFTextureDDSExtension(ddsLoader) {
if (!ddsLoader) {
- throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader');
+ throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader')
}
- this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
+ this.name = EXTENSIONS.MSFT_TEXTURE_DDS
this.ddsLoader = ddsLoader
}
function GLTFLightsExtension(json) {
- this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
- var extension = (json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL]) || {};
+ this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL
+ const extension = (json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL]) || {}
this.lightDefs = extension.lights || []
}
- GLTFLightsExtension.prototype.loadLight = function(lightIndex) {
- var lightDef = this.lightDefs[lightIndex];
- var lightNode;
- var color = new THREE.Color(0xffffff);
- if (lightDef.color !== undefined) color.fromArray(lightDef.color);
- var range = lightDef.range !== undefined ? lightDef.range: 0;
+ GLTFLightsExtension.prototype.loadLight = function (lightIndex) {
+ const lightDef = this.lightDefs[lightIndex]
+ let lightNode
+ const color = new THREE.Color(0xffffff)
+ if (lightDef.color !== undefined) color.fromArray(lightDef.color)
+ const range = lightDef.range !== undefined ? lightDef.range : 0
switch (lightDef.type) {
- case 'directional':
- lightNode = new THREE.DirectionalLight(color);
- lightNode.target.position.set(0, 0, -1);
- lightNode.add(lightNode.target);
- break;
- case 'point':
- lightNode = new THREE.PointLight(color);
- lightNode.distance = range;
- break;
- case 'spot':
- lightNode = new THREE.SpotLight(color);
- lightNode.distance = range;
- lightDef.spot = lightDef.spot || {};
- lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle: 0;
- lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle: Math.PI / 4.0;
- lightNode.angle = lightDef.spot.outerConeAngle;
- lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
- lightNode.target.position.set(0, 0, -1);
- lightNode.add(lightNode.target);
- break;
- default:
- throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
- }
- lightNode.position.set(0, 0, 0);
- lightNode.decay = 2;
- if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
- lightNode.name = lightDef.name || ('light_' + lightIndex);
+ case 'directional':
+ lightNode = new THREE.DirectionalLight(color)
+ lightNode.target.position.set(0, 0, -1)
+ lightNode.add(lightNode.target)
+ break
+ case 'point':
+ lightNode = new THREE.PointLight(color)
+ lightNode.distance = range
+ break
+ case 'spot':
+ lightNode = new THREE.SpotLight(color)
+ lightNode.distance = range
+ lightDef.spot = lightDef.spot || {}
+ lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0
+ lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0
+ lightNode.angle = lightDef.spot.outerConeAngle
+ lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle
+ lightNode.target.position.set(0, 0, -1)
+ lightNode.add(lightNode.target)
+ break
+ default:
+ throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".')
+ }
+ lightNode.position.set(0, 0, 0)
+ lightNode.decay = 2
+ if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity
+ lightNode.name = lightDef.name || ('light_' + lightIndex)
return Promise.resolve(lightNode)
- };
+ }
function GLTFMaterialsUnlitExtension() {
this.name = EXTENSIONS.KHR_MATERIALS_UNLIT
}
- GLTFMaterialsUnlitExtension.prototype.getMaterialType = function() {
+ GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
return THREE.MeshBasicMaterial
- };
- GLTFMaterialsUnlitExtension.prototype.extendParams = function(materialParams, materialDef, parser) {
- var pending = [];
- materialParams.color = new THREE.Color(1.0, 1.0, 1.0);
- materialParams.opacity = 1.0;
- var metallicRoughness = materialDef.pbrMetallicRoughness;
+ }
+ GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
+ const pending = []
+ materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
+ materialParams.opacity = 1.0
+ const metallicRoughness = materialDef.pbrMetallicRoughness
if (metallicRoughness) {
if (Array.isArray(metallicRoughness.baseColorFactor)) {
- var array = metallicRoughness.baseColorFactor;
- materialParams.color.fromArray(array);
+ const array = metallicRoughness.baseColorFactor
+ materialParams.color.fromArray(array)
materialParams.opacity = array[3]
}
if (metallicRoughness.baseColorTexture !== undefined) {
@@ -200,97 +206,100 @@ export function registerGLTFLoader(THREE) {
}
}
return Promise.all(pending)
- };
- var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
- var BINARY_EXTENSION_HEADER_LENGTH = 12;
- var BINARY_EXTENSION_CHUNK_TYPES = {
+ }
+ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'
+ const BINARY_EXTENSION_HEADER_LENGTH = 12
+ const BINARY_EXTENSION_CHUNK_TYPES = {
JSON: 0x4E4F534A,
BIN: 0x004E4942
- };
+ }
function GLTFBinaryExtension(data) {
- this.name = EXTENSIONS.KHR_BINARY_GLTF;
- this.content = null;
- this.body = null;
- var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
+ this.name = EXTENSIONS.KHR_BINARY_GLTF
+ this.content = null
+ this.body = null
+ const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH)
this.header = {
magic: THREE.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
version: headerView.getUint32(4, true),
length: headerView.getUint32(8, true)
- };
+ }
if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
- throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
+ throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.')
} else if (this.header.version < 2.0) {
- throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.');
+ throw new Error('THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.')
}
- var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
- var chunkIndex = 0;
+ const chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH)
+ let chunkIndex = 0
while (chunkIndex < chunkView.byteLength) {
- var chunkLength = chunkView.getUint32(chunkIndex, true);
- chunkIndex += 4;
- var chunkType = chunkView.getUint32(chunkIndex, true);
- chunkIndex += 4;
+ const chunkLength = chunkView.getUint32(chunkIndex, true)
+ chunkIndex += 4
+ const chunkType = chunkView.getUint32(chunkIndex, true)
+ chunkIndex += 4
if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
- var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
+ const contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength)
this.content = THREE.LoaderUtils.decodeText(contentArray)
} else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
- var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
+ const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex
this.body = data.slice(byteOffset, byteOffset + chunkLength)
}
chunkIndex += chunkLength
}
if (this.content === null) {
- throw new Error('THREE.GLTFLoader: JSON content not found.');
+ throw new Error('THREE.GLTFLoader: JSON content not found.')
}
}
function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
if (!dracoLoader) {
- throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
+ throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.')
}
- this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
- this.json = json;
+ this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION
+ this.json = json
this.dracoLoader = dracoLoader
}
- GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function(primitive, parser) {
- var json = this.json;
- var dracoLoader = this.dracoLoader;
- var bufferViewIndex = primitive.extensions[this.name].bufferView;
- var gltfAttributeMap = primitive.extensions[this.name].attributes;
- var threeAttributeMap = {};
- var attributeNormalizedMap = {};
- var attributeTypeMap = {};
+ GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
+ const json = this.json
+ const dracoLoader = this.dracoLoader
+ const bufferViewIndex = primitive.extensions[this.name].bufferView
+ const gltfAttributeMap = primitive.extensions[this.name].attributes
+ const threeAttributeMap = {}
+ const attributeNormalizedMap = {}
+ const attributeTypeMap = {}
for (var attributeName in gltfAttributeMap) {
- var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
+ var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase()
threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]
}
for (attributeName in primitive.attributes) {
- var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
+ var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase()
if (gltfAttributeMap[attributeName] !== undefined) {
- var accessorDef = json.accessors[primitive.attributes[attributeName]];
- var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
- attributeTypeMap[threeAttributeName] = componentType;
+ const accessorDef = json.accessors[primitive.attributes[attributeName]]
+ const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]
+ attributeTypeMap[threeAttributeName] = componentType
attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true
}
}
- return parser.getDependency('bufferView', bufferViewIndex).then(function(bufferView) {
- return new Promise(function(resolve) {
- dracoLoader.decodeDracoFile(bufferView,
- function(geometry) {
- for (var attributeName in geometry.attributes) {
- var attribute = geometry.attributes[attributeName];
- var normalized = attributeNormalizedMap[attributeName];
- if (normalized !== undefined) attribute.normalized = normalized
- }
- resolve(geometry)
- },
- threeAttributeMap, attributeTypeMap)
+ return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
+ return new Promise(function (resolve) {
+ dracoLoader.decodeDracoFile(
+ bufferView,
+ function (geometry) {
+ for (const attributeName in geometry.attributes) {
+ const attribute = geometry.attributes[attributeName]
+ const normalized = attributeNormalizedMap[attributeName]
+ if (normalized !== undefined) attribute.normalized = normalized
+ }
+ resolve(geometry)
+ },
+ threeAttributeMap,
+ attributeTypeMap
+ )
})
})
- };
+ }
function GLTFTextureTransformExtension() {
this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM
}
- GLTFTextureTransformExtension.prototype.extendTexture = function(texture, transform) {
- texture = texture.clone();
+ GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
+ texture = texture.clone()
if (transform.offset !== undefined) {
texture.offset.fromArray(transform.offset)
}
@@ -303,74 +312,77 @@ export function registerGLTFLoader(THREE) {
if (transform.texCoord !== undefined) {
console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.')
}
- texture.needsUpdate = true;
+ texture.needsUpdate = true
return texture
- };
+ }
function GLTFMaterialsPbrSpecularGlossinessExtension() {
return {
name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
- specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio', ],
- getMaterialType: function() {
+ specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
+ getMaterialType() {
return THREE.ShaderMaterial
},
- extendParams: function(materialParams, materialDef, parser) {
- var pbrSpecularGlossiness = materialDef.extensions[this.name];
- var shader = THREE.ShaderLib['standard'];
- var uniforms = THREE.UniformsUtils.clone(shader.uniforms);
- var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
- var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
- var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
- var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
- var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;', ].join('\n');
- var fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include ', specularMapParsFragmentChunk).replace('#include ', glossinessMapParsFragmentChunk).replace('#include ', specularMapFragmentChunk).replace('#include ', glossinessMapFragmentChunk).replace('#include ', lightPhysicalFragmentChunk);
- delete uniforms.roughness;
- delete uniforms.metalness;
- delete uniforms.roughnessMap;
- delete uniforms.metalnessMap;
+ extendParams(materialParams, materialDef, parser) {
+ const pbrSpecularGlossiness = materialDef.extensions[this.name]
+ const shader = THREE.ShaderLib.standard
+ const uniforms = THREE.UniformsUtils.clone(shader.uniforms)
+ const specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n')
+ const glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n')
+ const specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n')
+ const glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n')
+ const lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;'].join('\n')
+ const fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include ', specularMapParsFragmentChunk).replace('#include ', glossinessMapParsFragmentChunk)
+ .replace('#include ', specularMapFragmentChunk)
+ .replace('#include ', glossinessMapFragmentChunk)
+ .replace('#include ', lightPhysicalFragmentChunk)
+ delete uniforms.roughness
+ delete uniforms.metalness
+ delete uniforms.roughnessMap
+ delete uniforms.metalnessMap
uniforms.specular = {
value: new THREE.Color().setHex(0x111111)
- };
+ }
uniforms.glossiness = {
value: 0.5
- };
+ }
uniforms.specularMap = {
value: null
- };
+ }
uniforms.glossinessMap = {
value: null
- };
- materialParams.vertexShader = shader.vertexShader;
- materialParams.fragmentShader = fragmentShader;
- materialParams.uniforms = uniforms;
+ }
+ materialParams.vertexShader = shader.vertexShader
+ materialParams.fragmentShader = fragmentShader
+ materialParams.uniforms = uniforms
materialParams.defines = {
- 'STANDARD': ''
+ STANDARD: ''
}
- materialParams.color = new THREE.Color(1.0, 1.0, 1.0);
- materialParams.opacity = 1.0;
- var pending = [];
+ materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
+ materialParams.opacity = 1.0
+ const pending = []
if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
- var array = pbrSpecularGlossiness.diffuseFactor;
- materialParams.color.fromArray(array);
+ const array = pbrSpecularGlossiness.diffuseFactor
+ materialParams.color.fromArray(array)
materialParams.opacity = array[3]
}
if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture))
}
- materialParams.emissive = new THREE.Color(0.0, 0.0, 0.0);
- materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor: 1.0;
- materialParams.specular = new THREE.Color(1.0, 1.0, 1.0);
+ materialParams.emissive = new THREE.Color(0.0, 0.0, 0.0)
+ materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0
+ materialParams.specular = new THREE.Color(1.0, 1.0, 1.0)
if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor)
}
if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
- var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
- pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
+ const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture
+ pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef))
pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef))
}
return Promise.all(pending)
},
- createMaterial: function(params) {
- var material = new THREE.ShaderMaterial({
+ createMaterial(params) {
+ const material = new THREE.ShaderMaterial({
defines: params.defines,
vertexShader: params.vertexShader,
fragmentShader: params.fragmentShader,
@@ -379,63 +391,63 @@ export function registerGLTFLoader(THREE) {
lights: true,
opacity: params.opacity,
transparent: params.transparent
- });
- material.isGLTFSpecularGlossinessMaterial = true;
- material.color = params.color;
- material.map = params.map === undefined ? null: params.map;
- material.lightMap = null;
- material.lightMapIntensity = 1.0;
- material.aoMap = params.aoMap === undefined ? null: params.aoMap;
- material.aoMapIntensity = 1.0;
- material.emissive = params.emissive;
- material.emissiveIntensity = 1.0;
- material.emissiveMap = params.emissiveMap === undefined ? null: params.emissiveMap;
- material.bumpMap = params.bumpMap === undefined ? null: params.bumpMap;
- material.bumpScale = 1;
- material.normalMap = params.normalMap === undefined ? null: params.normalMap;
- if (params.normalScale) material.normalScale = params.normalScale;
- material.displacementMap = null;
- material.displacementScale = 1;
- material.displacementBias = 0;
- material.specularMap = params.specularMap === undefined ? null: params.specularMap;
- material.specular = params.specular;
- material.glossinessMap = params.glossinessMap === undefined ? null: params.glossinessMap;
- material.glossiness = params.glossiness;
- material.alphaMap = null;
- material.envMap = params.envMap === undefined ? null: params.envMap;
- material.envMapIntensity = 1.0;
- material.refractionRatio = 0.98;
- material.extensions.derivatives = true;
+ })
+ material.isGLTFSpecularGlossinessMaterial = true
+ material.color = params.color
+ material.map = params.map === undefined ? null : params.map
+ material.lightMap = null
+ material.lightMapIntensity = 1.0
+ material.aoMap = params.aoMap === undefined ? null : params.aoMap
+ material.aoMapIntensity = 1.0
+ material.emissive = params.emissive
+ material.emissiveIntensity = 1.0
+ material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap
+ material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap
+ material.bumpScale = 1
+ material.normalMap = params.normalMap === undefined ? null : params.normalMap
+ if (params.normalScale) material.normalScale = params.normalScale
+ material.displacementMap = null
+ material.displacementScale = 1
+ material.displacementBias = 0
+ material.specularMap = params.specularMap === undefined ? null : params.specularMap
+ material.specular = params.specular
+ material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap
+ material.glossiness = params.glossiness
+ material.alphaMap = null
+ material.envMap = params.envMap === undefined ? null : params.envMap
+ material.envMapIntensity = 1.0
+ material.refractionRatio = 0.98
+ material.extensions.derivatives = true
return material
},
- cloneMaterial: function(source) {
- var target = source.clone();
- target.isGLTFSpecularGlossinessMaterial = true;
- var params = this.specularGlossinessParams;
- for (var i = 0,
- il = params.length; i < il; i++) {
- var value = source[params[i]];
+ cloneMaterial(source) {
+ const target = source.clone()
+ target.isGLTFSpecularGlossinessMaterial = true
+ const params = this.specularGlossinessParams
+ for (let i = 0,
+ il = params.length; i < il; i++) {
+ const value = source[params[i]]
target[params[i]] = (value && value.isColor) ? value.clone() : value
}
return target
},
- refreshUniforms: function(renderer, scene, camera, geometry, material) {
+ refreshUniforms(renderer, scene, camera, geometry, material) {
if (material.isGLTFSpecularGlossinessMaterial !== true) {
return
}
- var uniforms = material.uniforms;
- var defines = material.defines;
- uniforms.opacity.value = material.opacity;
- uniforms.diffuse.value.copy(material.color);
- uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
- uniforms.map.value = material.map;
- uniforms.specularMap.value = material.specularMap;
- uniforms.alphaMap.value = material.alphaMap;
- uniforms.lightMap.value = material.lightMap;
- uniforms.lightMapIntensity.value = material.lightMapIntensity;
- uniforms.aoMap.value = material.aoMap;
- uniforms.aoMapIntensity.value = material.aoMapIntensity;
- var uvScaleMap;
+ const uniforms = material.uniforms
+ const defines = material.defines
+ uniforms.opacity.value = material.opacity
+ uniforms.diffuse.value.copy(material.color)
+ uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity)
+ uniforms.map.value = material.map
+ uniforms.specularMap.value = material.specularMap
+ uniforms.alphaMap.value = material.alphaMap
+ uniforms.lightMap.value = material.lightMap
+ uniforms.lightMapIntensity.value = material.lightMapIntensity
+ uniforms.aoMap.value = material.aoMap
+ uniforms.aoMapIntensity.value = material.aoMapIntensity
+ let uvScaleMap
if (material.map) {
uvScaleMap = material.map
} else if (material.specularMap) {
@@ -463,28 +475,28 @@ export function registerGLTFLoader(THREE) {
uniforms.uvTransform.value.copy(uvScaleMap.matrix)
}
if (material.envMap) {
- uniforms.envMap.value = material.envMap;
- uniforms.envMapIntensity.value = material.envMapIntensity;
- uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1;
- uniforms.reflectivity.value = material.reflectivity;
- uniforms.refractionRatio.value = material.refractionRatio;
+ uniforms.envMap.value = material.envMap
+ uniforms.envMapIntensity.value = material.envMapIntensity
+ uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? -1 : 1
+ uniforms.reflectivity.value = material.reflectivity
+ uniforms.refractionRatio.value = material.refractionRatio
uniforms.maxMipLevel.value = renderer.properties.get(material.envMap).__maxMipLevel
}
- uniforms.specular.value.copy(material.specular);
- uniforms.glossiness.value = material.glossiness;
- uniforms.glossinessMap.value = material.glossinessMap;
- uniforms.emissiveMap.value = material.emissiveMap;
- uniforms.bumpMap.value = material.bumpMap;
- uniforms.normalMap.value = material.normalMap;
- uniforms.displacementMap.value = material.displacementMap;
- uniforms.displacementScale.value = material.displacementScale;
- uniforms.displacementBias.value = material.displacementBias;
+ uniforms.specular.value.copy(material.specular)
+ uniforms.glossiness.value = material.glossiness
+ uniforms.glossinessMap.value = material.glossinessMap
+ uniforms.emissiveMap.value = material.emissiveMap
+ uniforms.bumpMap.value = material.bumpMap
+ uniforms.normalMap.value = material.normalMap
+ uniforms.displacementMap.value = material.displacementMap
+ uniforms.displacementScale.value = material.displacementScale
+ uniforms.displacementBias.value = material.displacementBias
if (uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined) {
- defines.USE_GLOSSINESSMAP = '';
+ defines.USE_GLOSSINESSMAP = ''
defines.USE_ROUGHNESSMAP = ''
}
if (uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined) {
- delete defines.USE_GLOSSINESSMAP;
+ delete defines.USE_GLOSSINESSMAP
delete defines.USE_ROUGHNESSMAP
}
}
@@ -493,46 +505,46 @@ export function registerGLTFLoader(THREE) {
function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
THREE.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer)
}
- GLTFCubicSplineInterpolant.prototype = Object.create(THREE.Interpolant.prototype);
- GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
- GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function(index) {
- var result = this.resultBuffer,
- values = this.sampleValues,
- valueSize = this.valueSize,
- offset = index * valueSize * 3 + valueSize;
- for (var i = 0; i !== valueSize; i++) {
+ GLTFCubicSplineInterpolant.prototype = Object.create(THREE.Interpolant.prototype)
+ GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant
+ GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
+ const result = this.resultBuffer
+ const values = this.sampleValues
+ const valueSize = this.valueSize
+ const offset = index * valueSize * 3 + valueSize
+ for (let i = 0; i !== valueSize; i++) {
result[i] = values[offset + i]
}
return result
- };
- GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
- GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
- GLTFCubicSplineInterpolant.prototype.interpolate_ = function(i1, t0, t, t1) {
- var result = this.resultBuffer;
- var values = this.sampleValues;
- var stride = this.valueSize;
- var stride2 = stride * 2;
- var stride3 = stride * 3;
- var td = t1 - t0;
- var p = (t - t0) / td;
- var pp = p * p;
- var ppp = pp * p;
- var offset1 = i1 * stride3;
- var offset0 = offset1 - stride3;
- var s2 = -2 * ppp + 3 * pp;
- var s3 = ppp - pp;
- var s0 = 1 - s2;
- var s1 = s3 - pp + p;
- for (var i = 0; i !== stride; i++) {
- var p0 = values[offset0 + i + stride];
- var m0 = values[offset0 + i + stride2] * td;
- var p1 = values[offset1 + i + stride];
- var m1 = values[offset1 + i] * td;
+ }
+ GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_
+ GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_
+ GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
+ const result = this.resultBuffer
+ const values = this.sampleValues
+ const stride = this.valueSize
+ const stride2 = stride * 2
+ const stride3 = stride * 3
+ const td = t1 - t0
+ const p = (t - t0) / td
+ const pp = p * p
+ const ppp = pp * p
+ const offset1 = i1 * stride3
+ const offset0 = offset1 - stride3
+ const s2 = -2 * ppp + 3 * pp
+ const s3 = ppp - pp
+ const s0 = 1 - s2
+ const s1 = s3 - pp + p
+ for (let i = 0; i !== stride; i++) {
+ const p0 = values[offset0 + i + stride]
+ const m0 = values[offset0 + i + stride2] * td
+ const p1 = values[offset1 + i + stride]
+ const m1 = values[offset1 + i] * td
result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1
}
return result
- };
- var WEBGL_CONSTANTS = {
+ }
+ const WEBGL_CONSTANTS = {
FLOAT: 5126,
FLOAT_MAT3: 35675,
FLOAT_MAT4: 35676,
@@ -551,37 +563,37 @@ export function registerGLTFLoader(THREE) {
TRIANGLE_FAN: 6,
UNSIGNED_BYTE: 5121,
UNSIGNED_SHORT: 5123
- };
+ }
var WEBGL_COMPONENT_TYPES = {
- 5120 : Int8Array,
- 5121 : Uint8Array,
- 5122 : Int16Array,
- 5123 : Uint16Array,
- 5125 : Uint32Array,
- 5126 : Float32Array
- };
- var WEBGL_FILTERS = {
- 9728 : THREE.NearestFilter,
- 9729 : THREE.LinearFilter,
- 9984 : THREE.NearestMipmapNearestFilter,
- 9985 : THREE.LinearMipmapNearestFilter,
- 9986 : THREE.NearestMipmapLinearFilter,
- 9987 : THREE.LinearMipmapLinearFilter
- };
- var WEBGL_WRAPPINGS = {
- 33071 : THREE.ClampToEdgeWrapping,
- 33648 : THREE.MirroredRepeatWrapping,
- 10497 : THREE.RepeatWrapping
- };
- var WEBGL_TYPE_SIZES = {
- 'SCALAR': 1,
- 'VEC2': 2,
- 'VEC3': 3,
- 'VEC4': 4,
- 'MAT2': 4,
- 'MAT3': 9,
- 'MAT4': 16
- };
+ 5120: Int8Array,
+ 5121: Uint8Array,
+ 5122: Int16Array,
+ 5123: Uint16Array,
+ 5125: Uint32Array,
+ 5126: Float32Array
+ }
+ const WEBGL_FILTERS = {
+ 9728: THREE.NearestFilter,
+ 9729: THREE.LinearFilter,
+ 9984: THREE.NearestMipmapNearestFilter,
+ 9985: THREE.LinearMipmapNearestFilter,
+ 9986: THREE.NearestMipmapLinearFilter,
+ 9987: THREE.LinearMipmapLinearFilter
+ }
+ const WEBGL_WRAPPINGS = {
+ 33071: THREE.ClampToEdgeWrapping,
+ 33648: THREE.MirroredRepeatWrapping,
+ 10497: THREE.RepeatWrapping
+ }
+ const WEBGL_TYPE_SIZES = {
+ SCALAR: 1,
+ VEC2: 2,
+ VEC3: 3,
+ VEC4: 4,
+ MAT2: 4,
+ MAT3: 9,
+ MAT4: 16
+ }
var ATTRIBUTES = {
POSITION: 'position',
NORMAL: 'normal',
@@ -591,38 +603,38 @@ export function registerGLTFLoader(THREE) {
COLOR_0: 'color',
WEIGHTS_0: 'skinWeight',
JOINTS_0: 'skinIndex',
- };
- var PATH_PROPERTIES = {
+ }
+ const PATH_PROPERTIES = {
scale: 'scale',
translation: 'position',
rotation: 'quaternion',
weights: 'morphTargetInfluences'
- };
- var INTERPOLATION = {
+ }
+ const INTERPOLATION = {
CUBICSPLINE: undefined,
LINEAR: THREE.InterpolateLinear,
STEP: THREE.InterpolateDiscrete
- };
- var ALPHA_MODES = {
+ }
+ const ALPHA_MODES = {
OPAQUE: 'OPAQUE',
MASK: 'MASK',
BLEND: 'BLEND'
- };
- var MIME_TYPE_FORMATS = {
+ }
+ const MIME_TYPE_FORMATS = {
'image/png': THREE.RGBAFormat,
'image/jpeg': THREE.RGBFormat
- };
+ }
function resolveURL(url, path) {
- if (typeof url !== 'string' || url === '') return '';
+ if (typeof url !== 'string' || url === '') return ''
if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1')
}
- if (/^(https?:)?\/\//i.test(url)) return url;
- if (/^data:.*,.*$/i.test(url)) return url;
- if (/^blob:.*$/i.test(url)) return url;
+ if (/^(https?:)?\/\//i.test(url)) return url
+ if (/^data:.*,.*$/i.test(url)) return url
+ if (/^blob:.*$/i.test(url)) return url
return path + url
}
- var defaultMaterial;
+ let defaultMaterial
function createDefaultMaterial() {
defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial({
color: 0xFFFFFF,
@@ -632,13 +644,13 @@ export function registerGLTFLoader(THREE) {
transparent: false,
depthTest: true,
side: THREE.FrontSide
- });
+ })
return defaultMaterial
}
function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
- for (var name in objectDef.extensions) {
+ for (const name in objectDef.extensions) {
if (knownExtensions[name] === undefined) {
- object.userData.gltfExtensions = object.userData.gltfExtensions || {};
+ object.userData.gltfExtensions = object.userData.gltfExtensions || {}
object.userData.gltfExtensions[name] = objectDef.extensions[name]
}
}
@@ -653,89 +665,89 @@ export function registerGLTFLoader(THREE) {
}
}
function addMorphTargets(geometry, targets, parser) {
- var hasMorphPosition = false;
- var hasMorphNormal = false;
+ let hasMorphPosition = false
+ let hasMorphNormal = false
for (var i = 0,
- il = targets.length; i < il; i++) {
- var target = targets[i];
- if (target.POSITION !== undefined) hasMorphPosition = true;
- if (target.NORMAL !== undefined) hasMorphNormal = true;
+ il = targets.length; i < il; i++) {
+ var target = targets[i]
+ if (target.POSITION !== undefined) hasMorphPosition = true
+ if (target.NORMAL !== undefined) hasMorphNormal = true
if (hasMorphPosition && hasMorphNormal) break
}
- if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
- var pendingPositionAccessors = [];
- var pendingNormalAccessors = [];
+ if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry)
+ const pendingPositionAccessors = []
+ const pendingNormalAccessors = []
for (var i = 0,
- il = targets.length; i < il; i++) {
- var target = targets[i];
+ il = targets.length; i < il; i++) {
+ var target = targets[i]
if (hasMorphPosition) {
- var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
+ var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position
pendingPositionAccessors.push(pendingAccessor)
}
if (hasMorphNormal) {
- var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
+ var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal
pendingNormalAccessors.push(pendingAccessor)
}
}
- return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function(accessors) {
- var morphPositions = accessors[0];
- var morphNormals = accessors[1];
+ return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
+ const morphPositions = accessors[0]
+ const morphNormals = accessors[1]
for (var i = 0,
- il = morphPositions.length; i < il; i++) {
- if (geometry.attributes.position === morphPositions[i]) continue;
+ il = morphPositions.length; i < il; i++) {
+ if (geometry.attributes.position === morphPositions[i]) continue
morphPositions[i] = cloneBufferAttribute(morphPositions[i])
}
for (var i = 0,
- il = morphNormals.length; i < il; i++) {
- if (geometry.attributes.normal === morphNormals[i]) continue;
+ il = morphNormals.length; i < il; i++) {
+ if (geometry.attributes.normal === morphNormals[i]) continue
morphNormals[i] = cloneBufferAttribute(morphNormals[i])
}
for (var i = 0,
- il = targets.length; i < il; i++) {
- var target = targets[i];
- var attributeName = 'morphTarget' + i;
+ il = targets.length; i < il; i++) {
+ const target = targets[i]
+ const attributeName = 'morphTarget' + i
if (hasMorphPosition) {
if (target.POSITION !== undefined) {
- var positionAttribute = morphPositions[i];
- positionAttribute.name = attributeName;
- var position = geometry.attributes.position;
+ const positionAttribute = morphPositions[i]
+ positionAttribute.name = attributeName
+ const position = geometry.attributes.position
for (var j = 0,
- jl = positionAttribute.count; j < jl; j++) {
+ jl = positionAttribute.count; j < jl; j++) {
positionAttribute.setXYZ(j, positionAttribute.getX(j) + position.getX(j), positionAttribute.getY(j) + position.getY(j), positionAttribute.getZ(j) + position.getZ(j))
}
}
}
if (hasMorphNormal) {
if (target.NORMAL !== undefined) {
- var normalAttribute = morphNormals[i];
- normalAttribute.name = attributeName;
- var normal = geometry.attributes.normal;
+ const normalAttribute = morphNormals[i]
+ normalAttribute.name = attributeName
+ const normal = geometry.attributes.normal
for (var j = 0,
- jl = normalAttribute.count; j < jl; j++) {
+ jl = normalAttribute.count; j < jl; j++) {
normalAttribute.setXYZ(j, normalAttribute.getX(j) + normal.getX(j), normalAttribute.getY(j) + normal.getY(j), normalAttribute.getZ(j) + normal.getZ(j))
}
}
}
}
- if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
- if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
+ if (hasMorphPosition) geometry.morphAttributes.position = morphPositions
+ if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals
return geometry
})
}
function updateMorphTargets(mesh, meshDef) {
- mesh.updateMorphTargets();
+ mesh.updateMorphTargets()
if (meshDef.weights !== undefined) {
for (var i = 0,
- il = meshDef.weights.length; i < il; i++) {
+ il = meshDef.weights.length; i < il; i++) {
mesh.morphTargetInfluences[i] = meshDef.weights[i]
}
}
if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
- var targetNames = meshDef.extras.targetNames;
+ const targetNames = meshDef.extras.targetNames
if (mesh.morphTargetInfluences.length === targetNames.length) {
- mesh.morphTargetDictionary = {};
+ mesh.morphTargetDictionary = {}
for (var i = 0,
- il = targetNames.length; i < il; i++) {
+ il = targetNames.length; i < il; i++) {
mesh.morphTargetDictionary[targetNames[i]] = i
}
} else {
@@ -744,8 +756,8 @@ export function registerGLTFLoader(THREE) {
}
}
function createPrimitiveKey(primitiveDef) {
- var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
- var geometryKey;
+ const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]
+ let geometryKey
if (dracoExtension) {
geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes)
} else {
@@ -754,24 +766,24 @@ export function registerGLTFLoader(THREE) {
return geometryKey
}
function createAttributesKey(attributes) {
- var attributesKey = '';
- var keys = Object.keys(attributes).sort();
- for (var i = 0,
- il = keys.length; i < il; i++) {
+ let attributesKey = ''
+ const keys = Object.keys(attributes).sort()
+ for (let i = 0,
+ il = keys.length; i < il; i++) {
attributesKey += keys[i] + ':' + attributes[keys[i]] + ';'
}
return attributesKey
}
function cloneBufferAttribute(attribute) {
if (attribute.isInterleavedBufferAttribute) {
- var count = attribute.count;
- var itemSize = attribute.itemSize;
- var array = attribute.array.slice(0, count * itemSize);
- for (var i = 0,
- j = 0; i < count; ++i) {
- array[j++] = attribute.getX(i);
- if (itemSize >= 2) array[j++] = attribute.getY(i);
- if (itemSize >= 3) array[j++] = attribute.getZ(i);
+ const count = attribute.count
+ const itemSize = attribute.itemSize
+ const array = attribute.array.slice(0, count * itemSize)
+ for (let i = 0,
+ j = 0; i < count; ++i) {
+ array[j++] = attribute.getX(i)
+ if (itemSize >= 2) array[j++] = attribute.getY(i)
+ if (itemSize >= 3) array[j++] = attribute.getZ(i)
if (itemSize >= 4) array[j++] = attribute.getW(i)
}
return new THREE.BufferAttribute(array, itemSize, attribute.normalized)
@@ -779,187 +791,192 @@ export function registerGLTFLoader(THREE) {
return attribute.clone()
}
function GLTFParser(json, extensions, options) {
- this.json = json || {};
- this.extensions = extensions || {};
- this.options = options || {};
- this.cache = new GLTFRegistry();
- this.primitiveCache = {};
- this.textureLoader = new THREE.TextureLoader(this.options.manager);
- this.textureLoader.setCrossOrigin(this.options.crossOrigin);
- this.fileLoader = new THREE.FileLoader(this.options.manager);
+ this.json = json || {}
+ this.extensions = extensions || {}
+ this.options = options || {}
+ this.cache = new GLTFRegistry()
+ this.primitiveCache = {}
+ this.textureLoader = new THREE.TextureLoader(this.options.manager)
+ this.textureLoader.setCrossOrigin(this.options.crossOrigin)
+ this.fileLoader = new THREE.FileLoader(this.options.manager)
this.fileLoader.setResponseType('arraybuffer')
}
- GLTFParser.prototype.parse = function(onLoad, onError) {
- var parser = this;
- var json = this.json;
- var extensions = this.extensions;
- this.cache.removeAll();
- this.markDefs();
- Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera'), ]).then(function(dependencies) {
- var result = {
+ GLTFParser.prototype.parse = function (onLoad, onError) {
+ const parser = this
+ const json = this.json
+ const extensions = this.extensions
+ this.cache.removeAll()
+ this.markDefs()
+ Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
+ const result = {
scene: dependencies[0][json.scene || 0],
scenes: dependencies[0],
animations: dependencies[1],
cameras: dependencies[2],
asset: json.asset,
- parser: parser,
+ parser,
userData: {}
- };
- addUnknownExtensionsToUserData(extensions, result, json);
- assignExtrasToUserData(result, json);
+ }
+ addUnknownExtensionsToUserData(extensions, result, json)
+ assignExtrasToUserData(result, json)
onLoad(result)
- }).
- catch(onError)
- };
- GLTFParser.prototype.markDefs = function() {
- var nodeDefs = this.json.nodes || [];
- var skinDefs = this.json.skins || [];
- var meshDefs = this.json.meshes || [];
- var meshReferences = {};
- var meshUses = {};
- for (var skinIndex = 0,
- skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
- var joints = skinDefs[skinIndex].joints;
- for (var i = 0,
- il = joints.length; i < il; i++) {
+ })
+ .catch(onError)
+ }
+ GLTFParser.prototype.markDefs = function () {
+ const nodeDefs = this.json.nodes || []
+ const skinDefs = this.json.skins || []
+ const meshDefs = this.json.meshes || []
+ const meshReferences = {}
+ const meshUses = {}
+ for (let skinIndex = 0,
+ skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
+ const joints = skinDefs[skinIndex].joints
+ for (let i = 0,
+ il = joints.length; i < il; i++) {
nodeDefs[joints[i]].isBone = true
}
}
- for (var nodeIndex = 0,
- nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
- var nodeDef = nodeDefs[nodeIndex];
+ for (let nodeIndex = 0,
+ nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
+ const nodeDef = nodeDefs[nodeIndex]
if (nodeDef.mesh !== undefined) {
if (meshReferences[nodeDef.mesh] === undefined) {
meshReferences[nodeDef.mesh] = meshUses[nodeDef.mesh] = 0
}
- meshReferences[nodeDef.mesh]++;
+ meshReferences[nodeDef.mesh]++
if (nodeDef.skin !== undefined) {
meshDefs[nodeDef.mesh].isSkinnedMesh = true
}
}
}
- this.json.meshReferences = meshReferences;
+ this.json.meshReferences = meshReferences
this.json.meshUses = meshUses
- };
- GLTFParser.prototype.getDependency = function(type, index) {
- var cacheKey = type + ':' + index;
- var dependency = this.cache.get(cacheKey);
+ }
+ GLTFParser.prototype.getDependency = function (type, index) {
+ const cacheKey = type + ':' + index
+ let dependency = this.cache.get(cacheKey)
if (!dependency) {
switch (type) {
- case 'scene':
- dependency = this.loadScene(index);
- break;
- case 'node':
- dependency = this.loadNode(index);
- break;
- case 'mesh':
- dependency = this.loadMesh(index);
- break;
- case 'accessor':
- dependency = this.loadAccessor(index);
- break;
- case 'bufferView':
- dependency = this.loadBufferView(index);
- break;
- case 'buffer':
- dependency = this.loadBuffer(index);
- break;
- case 'material':
- dependency = this.loadMaterial(index);
- break;
- case 'texture':
- dependency = this.loadTexture(index);
- break;
- case 'skin':
- dependency = this.loadSkin(index);
- break;
- case 'animation':
- dependency = this.loadAnimation(index);
- break;
- case 'camera':
- dependency = this.loadCamera(index);
- break;
- case 'light':
- dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index);
- break;
- default:
- throw new Error('Unknown type: ' + type);
+ case 'scene':
+ dependency = this.loadScene(index)
+ break
+ case 'node':
+ dependency = this.loadNode(index)
+ break
+ case 'mesh':
+ dependency = this.loadMesh(index)
+ break
+ case 'accessor':
+ dependency = this.loadAccessor(index)
+ break
+ case 'bufferView':
+ dependency = this.loadBufferView(index)
+ break
+ case 'buffer':
+ dependency = this.loadBuffer(index)
+ break
+ case 'material':
+ dependency = this.loadMaterial(index)
+ break
+ case 'texture':
+ dependency = this.loadTexture(index)
+ break
+ case 'skin':
+ dependency = this.loadSkin(index)
+ break
+ case 'animation':
+ dependency = this.loadAnimation(index)
+ break
+ case 'camera':
+ dependency = this.loadCamera(index)
+ break
+ case 'light':
+ dependency = this.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].loadLight(index)
+ break
+ default:
+ throw new Error('Unknown type: ' + type)
}
this.cache.add(cacheKey, dependency)
}
return dependency
- };
- GLTFParser.prototype.getDependencies = function(type) {
- var dependencies = this.cache.get(type);
+ }
+ GLTFParser.prototype.getDependencies = function (type) {
+ let dependencies = this.cache.get(type)
if (!dependencies) {
- var parser = this;
- var defs = this.json[type + (type === 'mesh' ? 'es': 's')] || [];
- dependencies = Promise.all(defs.map(function(def, index) {
+ const parser = this
+ const defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || []
+ dependencies = Promise.all(defs.map(function (def, index) {
return parser.getDependency(type, index)
- }));
+ }))
this.cache.add(type, dependencies)
}
return dependencies
- };
- GLTFParser.prototype.loadBuffer = function(bufferIndex) {
- var bufferDef = this.json.buffers[bufferIndex];
- var loader = this.fileLoader;
+ }
+ GLTFParser.prototype.loadBuffer = function (bufferIndex) {
+ const bufferDef = this.json.buffers[bufferIndex]
+ const loader = this.fileLoader
if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
- throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
+ throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.')
}
if (bufferDef.uri === undefined && bufferIndex === 0) {
return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body)
}
- var options = this.options;
- return new Promise(function(resolve, reject) {
- loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined,
- function() {
- reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'))
- })
+ const options = this.options
+ return new Promise(function (resolve, reject) {
+ loader.load(
+ resolveURL(bufferDef.uri, options.path),
+ resolve,
+ undefined,
+ function () {
+ reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'))
+ }
+ )
})
- };
- GLTFParser.prototype.loadBufferView = function(bufferViewIndex) {
- var bufferViewDef = this.json.bufferViews[bufferViewIndex];
- return this.getDependency('buffer', bufferViewDef.buffer).then(function(buffer) {
- var byteLength = bufferViewDef.byteLength || 0;
- var byteOffset = bufferViewDef.byteOffset || 0;
+ }
+ GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
+ const bufferViewDef = this.json.bufferViews[bufferViewIndex]
+ return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
+ const byteLength = bufferViewDef.byteLength || 0
+ const byteOffset = bufferViewDef.byteOffset || 0
return buffer.slice(byteOffset, byteOffset + byteLength)
})
- };
- GLTFParser.prototype.loadAccessor = function(accessorIndex) {
- var parser = this;
- var json = this.json;
- var accessorDef = this.json.accessors[accessorIndex];
+ }
+ GLTFParser.prototype.loadAccessor = function (accessorIndex) {
+ const parser = this
+ const json = this.json
+ const accessorDef = this.json.accessors[accessorIndex]
if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
return Promise.resolve(null)
}
- var pendingBufferViews = [];
+ const pendingBufferViews = []
if (accessorDef.bufferView !== undefined) {
pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView))
} else {
pendingBufferViews.push(null)
}
if (accessorDef.sparse !== undefined) {
- pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
+ pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView))
pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView))
}
- return Promise.all(pendingBufferViews).then(function(bufferViews) {
- var bufferView = bufferViews[0];
- var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
- var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
- var elementBytes = TypedArray.BYTES_PER_ELEMENT;
- var itemBytes = elementBytes * itemSize;
- var byteOffset = accessorDef.byteOffset || 0;
- var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride: undefined;
- var normalized = accessorDef.normalized === true;
- var array, bufferAttribute;
+ return Promise.all(pendingBufferViews).then(function (bufferViews) {
+ const bufferView = bufferViews[0]
+ const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]
+ const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]
+ const elementBytes = TypedArray.BYTES_PER_ELEMENT
+ const itemBytes = elementBytes * itemSize
+ const byteOffset = accessorDef.byteOffset || 0
+ const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined
+ const normalized = accessorDef.normalized === true
+ let array; let
+ bufferAttribute
if (byteStride && byteStride !== itemBytes) {
- var ibSlice = Math.floor(byteOffset / byteStride);
- var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
- var ib = parser.cache.get(ibCacheKey);
+ const ibSlice = Math.floor(byteOffset / byteStride)
+ const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count
+ let ib = parser.cache.get(ibCacheKey)
if (!ib) {
- array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes);
- ib = new THREE.InterleavedBuffer(array, byteStride / elementBytes);
+ array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes)
+ ib = new THREE.InterleavedBuffer(array, byteStride / elementBytes)
parser.cache.add(ibCacheKey, ib)
}
bufferAttribute = new THREE.InterleavedBufferAttribute(ib, itemSize, (byteOffset % byteStride) / elementBytes, normalized)
@@ -972,226 +989,226 @@ export function registerGLTFLoader(THREE) {
bufferAttribute = new THREE.BufferAttribute(array, itemSize, normalized)
}
if (accessorDef.sparse !== undefined) {
- var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
- var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
- var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
- var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
- var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
- var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
+ const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR
+ const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]
+ const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0
+ const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0
+ const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices)
+ const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize)
if (bufferView !== null) {
bufferAttribute.setArray(bufferAttribute.array.slice())
}
- for (var i = 0,
- il = sparseIndices.length; i < il; i++) {
- var index = sparseIndices[i];
- bufferAttribute.setX(index, sparseValues[i * itemSize]);
- if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
- if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
- if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
- if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
+ for (let i = 0,
+ il = sparseIndices.length; i < il; i++) {
+ const index = sparseIndices[i]
+ bufferAttribute.setX(index, sparseValues[i * itemSize])
+ if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1])
+ if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2])
+ if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3])
+ if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.')
}
}
return bufferAttribute
})
- };
- GLTFParser.prototype.loadTexture = function(textureIndex) {
- var parser = this;
- var json = this.json;
- var options = this.options;
- var textureLoader = this.textureLoader;
+ }
+ GLTFParser.prototype.loadTexture = function (textureIndex) {
+ const parser = this
+ const json = this.json
+ const options = this.options
+ const textureLoader = this.textureLoader
// var URL = global.URL;
- var textureDef = json.textures[textureIndex];
- var textureExtensions = textureDef.extensions || {};
- var source;
+ const textureDef = json.textures[textureIndex]
+ const textureExtensions = textureDef.extensions || {}
+ let source
if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source]
} else {
source = json.images[textureDef.source]
}
- var sourceURI = source.uri;
- var isObjectURL = false;
+ let sourceURI = source.uri
+ let isObjectURL = false
if (source.bufferView !== undefined) {
- sourceURI = parser.getDependency('bufferView', source.bufferView).then(function(bufferView) {
- isObjectURL = true;
+ sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
+ isObjectURL = true
// 微信小程序不支持 Blob 对象,则使用 base64 编码的字符串来创建 data URI
- const base64Str = wx.arrayBufferToBase64(bufferView);
- sourceURI = `data:${source.mimeType};base64,${base64Str}`;
+ const base64Str = wx.arrayBufferToBase64(bufferView)
+ sourceURI = `data:${source.mimeType};base64,${base64Str}`
return sourceURI
})
}
- return Promise.resolve(sourceURI).then(function(sourceURI) {
- var loader = THREE.Loader.Handlers.get(sourceURI);
+ return Promise.resolve(sourceURI).then(function (sourceURI) {
+ let loader = THREE.Loader.Handlers.get(sourceURI)
if (!loader) {
- loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader: textureLoader
+ loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : textureLoader
}
- return new Promise(function(resolve, reject) {
+ return new Promise(function (resolve, reject) {
loader.load(resolveURL(sourceURI, options.path), resolve, undefined, reject)
})
- }).then(function(texture) {
+ }).then(function (texture) {
if (isObjectURL === true) {
// URL.revokeObjectURL(sourceURI)
}
- texture.flipY = false;
- if (textureDef.name !== undefined) texture.name = textureDef.name;
+ texture.flipY = false
+ if (textureDef.name !== undefined) texture.name = textureDef.name
if (source.mimeType in MIME_TYPE_FORMATS) {
texture.format = MIME_TYPE_FORMATS[source.mimeType]
}
- var samplers = json.samplers || {};
- var sampler = samplers[textureDef.sampler] || {};
- texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || THREE.LinearFilter;
- texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || THREE.LinearMipmapLinearFilter;
- texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || THREE.RepeatWrapping;
- texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || THREE.RepeatWrapping;
+ const samplers = json.samplers || {}
+ const sampler = samplers[textureDef.sampler] || {}
+ texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || THREE.LinearFilter
+ texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || THREE.LinearMipmapLinearFilter
+ texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || THREE.RepeatWrapping
+ texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || THREE.RepeatWrapping
return texture
})
- };
- GLTFParser.prototype.assignTexture = function(materialParams, mapName, mapDef) {
- var parser = this;
- return this.getDependency('texture', mapDef.index).then(function(texture) {
+ }
+ GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
+ const parser = this
+ return this.getDependency('texture', mapDef.index).then(function (texture) {
if (!texture.isCompressedTexture) {
switch (mapName) {
- case 'aoMap':
- case 'emissiveMap':
- case 'metalnessMap':
- case 'normalMap':
- case 'roughnessMap':
- texture.format = THREE.RGBFormat;
- break
+ case 'aoMap':
+ case 'emissiveMap':
+ case 'metalnessMap':
+ case 'normalMap':
+ case 'roughnessMap':
+ texture.format = THREE.RGBFormat
+ break
}
}
if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
- var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
+ const transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined
if (transform) {
texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform)
}
}
materialParams[mapName] = texture
})
- };
- GLTFParser.prototype.assignFinalMaterial = function(mesh) {
- var geometry = mesh.geometry;
- var material = mesh.material;
- var extensions = this.extensions;
- var useVertexTangents = geometry.attributes.tangent !== undefined;
- var useVertexColors = geometry.attributes.color !== undefined;
- var useFlatShading = geometry.attributes.normal === undefined;
- var useSkinning = mesh.isSkinnedMesh === true;
- var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
- var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
+ }
+ GLTFParser.prototype.assignFinalMaterial = function (mesh) {
+ const geometry = mesh.geometry
+ let material = mesh.material
+ const extensions = this.extensions
+ const useVertexTangents = geometry.attributes.tangent !== undefined
+ const useVertexColors = geometry.attributes.color !== undefined
+ const useFlatShading = geometry.attributes.normal === undefined
+ const useSkinning = mesh.isSkinnedMesh === true
+ const useMorphTargets = Object.keys(geometry.morphAttributes).length > 0
+ const useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined
if (mesh.isPoints) {
- var cacheKey = 'PointsMaterial:' + material.uuid;
- var pointsMaterial = this.cache.get(cacheKey);
+ var cacheKey = 'PointsMaterial:' + material.uuid
+ let pointsMaterial = this.cache.get(cacheKey)
if (!pointsMaterial) {
- pointsMaterial = new THREE.PointsMaterial();
- THREE.Material.prototype.copy.call(pointsMaterial, material);
- pointsMaterial.color.copy(material.color);
- pointsMaterial.map = material.map;
- pointsMaterial.lights = false;
- pointsMaterial.sizeAttenuation = false;
+ pointsMaterial = new THREE.PointsMaterial()
+ THREE.Material.prototype.copy.call(pointsMaterial, material)
+ pointsMaterial.color.copy(material.color)
+ pointsMaterial.map = material.map
+ pointsMaterial.lights = false
+ pointsMaterial.sizeAttenuation = false
this.cache.add(cacheKey, pointsMaterial)
}
material = pointsMaterial
} else if (mesh.isLine) {
- var cacheKey = 'LineBasicMaterial:' + material.uuid;
- var lineMaterial = this.cache.get(cacheKey);
+ var cacheKey = 'LineBasicMaterial:' + material.uuid
+ let lineMaterial = this.cache.get(cacheKey)
if (!lineMaterial) {
- lineMaterial = new THREE.LineBasicMaterial();
- THREE.Material.prototype.copy.call(lineMaterial, material);
- lineMaterial.color.copy(material.color);
- lineMaterial.lights = false;
+ lineMaterial = new THREE.LineBasicMaterial()
+ THREE.Material.prototype.copy.call(lineMaterial, material)
+ lineMaterial.color.copy(material.color)
+ lineMaterial.lights = false
this.cache.add(cacheKey, lineMaterial)
}
material = lineMaterial
}
if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
- var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
- if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
- if (useSkinning) cacheKey += 'skinning:';
- if (useVertexTangents) cacheKey += 'vertex-tangents:';
- if (useVertexColors) cacheKey += 'vertex-colors:';
- if (useFlatShading) cacheKey += 'flat-shading:';
- if (useMorphTargets) cacheKey += 'morph-targets:';
- if (useMorphNormals) cacheKey += 'morph-normals:';
- var cachedMaterial = this.cache.get(cacheKey);
+ var cacheKey = 'ClonedMaterial:' + material.uuid + ':'
+ if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:'
+ if (useSkinning) cacheKey += 'skinning:'
+ if (useVertexTangents) cacheKey += 'vertex-tangents:'
+ if (useVertexColors) cacheKey += 'vertex-colors:'
+ if (useFlatShading) cacheKey += 'flat-shading:'
+ if (useMorphTargets) cacheKey += 'morph-targets:'
+ if (useMorphNormals) cacheKey += 'morph-normals:'
+ let cachedMaterial = this.cache.get(cacheKey)
if (!cachedMaterial) {
- cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone();
- if (useSkinning) cachedMaterial.skinning = true;
- if (useVertexTangents) cachedMaterial.vertexTangents = true;
- if (useVertexColors) cachedMaterial.vertexColors = THREE.VertexColors;
- if (useFlatShading) cachedMaterial.flatShading = true;
- if (useMorphTargets) cachedMaterial.morphTargets = true;
- if (useMorphNormals) cachedMaterial.morphNormals = true;
+ cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].cloneMaterial(material) : material.clone()
+ if (useSkinning) cachedMaterial.skinning = true
+ if (useVertexTangents) cachedMaterial.vertexTangents = true
+ if (useVertexColors) cachedMaterial.vertexColors = THREE.VertexColors
+ if (useFlatShading) cachedMaterial.flatShading = true
+ if (useMorphTargets) cachedMaterial.morphTargets = true
+ if (useMorphNormals) cachedMaterial.morphNormals = true
this.cache.add(cacheKey, cachedMaterial)
}
material = cachedMaterial
}
if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
- console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.');
+ console.log('THREE.GLTFLoader: Duplicating UVs to support aoMap.')
geometry.addAttribute('uv2', new THREE.BufferAttribute(geometry.attributes.uv.array, 2))
}
if (material.isGLTFSpecularGlossinessMaterial) {
mesh.onBeforeRender = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].refreshUniforms
}
mesh.material = material
- };
- GLTFParser.prototype.loadMaterial = function(materialIndex) {
- var parser = this;
- var json = this.json;
- var extensions = this.extensions;
- var materialDef = json.materials[materialIndex];
- var materialType;
- var materialParams = {};
- var materialExtensions = materialDef.extensions || {};
- var pending = [];
+ }
+ GLTFParser.prototype.loadMaterial = function (materialIndex) {
+ const parser = this
+ const json = this.json
+ const extensions = this.extensions
+ const materialDef = json.materials[materialIndex]
+ let materialType
+ const materialParams = {}
+ const materialExtensions = materialDef.extensions || {}
+ const pending = []
if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
- var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
- materialType = sgExtension.getMaterialType();
+ const sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]
+ materialType = sgExtension.getMaterialType()
pending.push(sgExtension.extendParams(materialParams, materialDef, parser))
} else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
- var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
- materialType = kmuExtension.getMaterialType();
+ const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]
+ materialType = kmuExtension.getMaterialType()
pending.push(kmuExtension.extendParams(materialParams, materialDef, parser))
} else {
- materialType = THREE.MeshStandardMaterial;
- var metallicRoughness = materialDef.pbrMetallicRoughness || {};
- materialParams.color = new THREE.Color(1.0, 1.0, 1.0);
- materialParams.opacity = 1.0;
+ materialType = THREE.MeshStandardMaterial
+ const metallicRoughness = materialDef.pbrMetallicRoughness || {}
+ materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
+ materialParams.opacity = 1.0
if (Array.isArray(metallicRoughness.baseColorFactor)) {
- var array = metallicRoughness.baseColorFactor;
- materialParams.color.fromArray(array);
+ const array = metallicRoughness.baseColorFactor
+ materialParams.color.fromArray(array)
materialParams.opacity = array[3]
}
if (metallicRoughness.baseColorTexture !== undefined) {
pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture))
}
- materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor: 1.0;
- materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor: 1.0;
+ materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0
+ materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0
if (metallicRoughness.metallicRoughnessTexture !== undefined) {
- pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
+ pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture))
pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture))
}
}
if (materialDef.doubleSided === true) {
materialParams.side = THREE.DoubleSide
}
- var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
+ const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE
if (alphaMode === ALPHA_MODES.BLEND) {
materialParams.transparent = true
} else {
- materialParams.transparent = false;
+ materialParams.transparent = false
if (alphaMode === ALPHA_MODES.MASK) {
- materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff: 0.5
+ materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5
}
}
if (materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
- pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
- materialParams.normalScale = new THREE.Vector2(1, 1);
+ pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture))
+ materialParams.normalScale = new THREE.Vector2(1, 1)
if (materialDef.normalTexture.scale !== undefined) {
materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale)
}
}
if (materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
- pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
+ pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture))
if (materialDef.occlusionTexture.strength !== undefined) {
materialParams.aoMapIntensity = materialDef.occlusionTexture.strength
}
@@ -1202,101 +1219,101 @@ export function registerGLTFLoader(THREE) {
if (materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture))
}
- return Promise.all(pending).then(function() {
- var material;
+ return Promise.all(pending).then(function () {
+ let material
if (materialType === THREE.ShaderMaterial) {
material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams)
} else {
material = new materialType(materialParams)
}
- if (materialDef.name !== undefined) material.name = materialDef.name;
- if (material.map) material.map.encoding = THREE.sRGBEncoding;
- if (material.emissiveMap) material.emissiveMap.encoding = THREE.sRGBEncoding;
- if (material.specularMap) material.specularMap.encoding = THREE.sRGBEncoding;
- assignExtrasToUserData(material, materialDef);
- if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
+ if (materialDef.name !== undefined) material.name = materialDef.name
+ if (material.map) material.map.encoding = THREE.sRGBEncoding
+ if (material.emissiveMap) material.emissiveMap.encoding = THREE.sRGBEncoding
+ if (material.specularMap) material.specularMap.encoding = THREE.sRGBEncoding
+ assignExtrasToUserData(material, materialDef)
+ if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef)
return material
})
- };
+ }
function addPrimitiveAttributes(geometry, primitiveDef, parser) {
- var attributes = primitiveDef.attributes;
- var pending = [];
+ const attributes = primitiveDef.attributes
+ const pending = []
function assignAttributeAccessor(accessorIndex, attributeName) {
- return parser.getDependency('accessor', accessorIndex).then(function(accessor) {
+ return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
geometry.addAttribute(attributeName, accessor)
})
}
- for (var gltfAttributeName in attributes) {
- var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase();
- if (threeAttributeName in geometry.attributes) continue;
+ for (const gltfAttributeName in attributes) {
+ const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase()
+ if (threeAttributeName in geometry.attributes) continue
pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName))
}
if (primitiveDef.indices !== undefined && !geometry.index) {
- var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function(accessor) {
+ const accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
geometry.setIndex(accessor)
- });
+ })
pending.push(accessor)
}
- assignExtrasToUserData(geometry, primitiveDef);
- return Promise.all(pending).then(function() {
+ assignExtrasToUserData(geometry, primitiveDef)
+ return Promise.all(pending).then(function () {
return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry
})
}
- GLTFParser.prototype.loadGeometries = function(primitives) {
- var parser = this;
- var extensions = this.extensions;
- var cache = this.primitiveCache;
+ GLTFParser.prototype.loadGeometries = function (primitives) {
+ const parser = this
+ const extensions = this.extensions
+ const cache = this.primitiveCache
function createDracoPrimitive(primitive) {
- return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) {
+ return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
return addPrimitiveAttributes(geometry, primitive, parser)
})
}
- var pending = [];
- for (var i = 0,
- il = primitives.length; i < il; i++) {
- var primitive = primitives[i];
- var cacheKey = createPrimitiveKey(primitive);
- var cached = cache[cacheKey];
+ const pending = []
+ for (let i = 0,
+ il = primitives.length; i < il; i++) {
+ const primitive = primitives[i]
+ const cacheKey = createPrimitiveKey(primitive)
+ const cached = cache[cacheKey]
if (cached) {
pending.push(cached.promise)
} else {
- var geometryPromise;
+ var geometryPromise
if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
geometryPromise = createDracoPrimitive(primitive)
} else {
geometryPromise = addPrimitiveAttributes(new THREE.BufferGeometry(), primitive, parser)
}
cache[cacheKey] = {
- primitive: primitive,
+ primitive,
promise: geometryPromise
- };
+ }
pending.push(geometryPromise)
}
}
return Promise.all(pending)
- };
- GLTFParser.prototype.loadMesh = function(meshIndex) {
- var parser = this;
- var json = this.json;
- var meshDef = json.meshes[meshIndex];
- var primitives = meshDef.primitives;
- var pending = [];
- for (var i = 0,
- il = primitives.length; i < il; i++) {
- var material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material);
+ }
+ GLTFParser.prototype.loadMesh = function (meshIndex) {
+ const parser = this
+ const json = this.json
+ const meshDef = json.meshes[meshIndex]
+ const primitives = meshDef.primitives
+ const pending = []
+ for (let i = 0,
+ il = primitives.length; i < il; i++) {
+ const material = primitives[i].material === undefined ? createDefaultMaterial() : this.getDependency('material', primitives[i].material)
pending.push(material)
}
- return Promise.all(pending).then(function(originalMaterials) {
- return parser.loadGeometries(primitives).then(function(geometries) {
- var meshes = [];
+ return Promise.all(pending).then(function (originalMaterials) {
+ return parser.loadGeometries(primitives).then(function (geometries) {
+ const meshes = []
for (var i = 0,
- il = geometries.length; i < il; i++) {
- var geometry = geometries[i];
- var primitive = primitives[i];
- var mesh;
- var material = originalMaterials[i];
+ il = geometries.length; i < il; i++) {
+ const geometry = geometries[i]
+ const primitive = primitives[i]
+ var mesh
+ const material = originalMaterials[i]
if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
- mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh(geometry, material) : new THREE.Mesh(geometry, material);
+ mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh(geometry, material) : new THREE.Mesh(geometry, material)
if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
mesh.normalizeSkinWeights()
}
@@ -1314,35 +1331,35 @@ export function registerGLTFLoader(THREE) {
} else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
mesh = new THREE.Points(geometry, material)
} else {
- throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
+ throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode)
}
if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
updateMorphTargets(mesh, meshDef)
}
- mesh.name = meshDef.name || ('mesh_' + meshIndex);
- if (geometries.length > 1) mesh.name += '_' + i;
- assignExtrasToUserData(mesh, meshDef);
- parser.assignFinalMaterial(mesh);
+ mesh.name = meshDef.name || ('mesh_' + meshIndex)
+ if (geometries.length > 1) mesh.name += '_' + i
+ assignExtrasToUserData(mesh, meshDef)
+ parser.assignFinalMaterial(mesh)
meshes.push(mesh)
}
if (meshes.length === 1) {
return meshes[0]
}
- var group = new THREE.Group();
+ const group = new THREE.Group()
for (var i = 0,
- il = meshes.length; i < il; i++) {
+ il = meshes.length; i < il; i++) {
group.add(meshes[i])
}
return group
})
})
- };
- GLTFParser.prototype.loadCamera = function(cameraIndex) {
- var camera;
- var cameraDef = this.json.cameras[cameraIndex];
- var params = cameraDef[cameraDef.type];
+ }
+ GLTFParser.prototype.loadCamera = function (cameraIndex) {
+ let camera
+ const cameraDef = this.json.cameras[cameraIndex]
+ const params = cameraDef[cameraDef.type]
if (!params) {
- console.warn('THREE.GLTFLoader: Missing camera parameters.');
+ console.warn('THREE.GLTFLoader: Missing camera parameters.')
return
}
if (cameraDef.type === 'perspective') {
@@ -1350,91 +1367,91 @@ export function registerGLTFLoader(THREE) {
} else if (cameraDef.type === 'orthographic') {
camera = new THREE.OrthographicCamera(params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar)
}
- if (cameraDef.name !== undefined) camera.name = cameraDef.name;
- assignExtrasToUserData(camera, cameraDef);
+ if (cameraDef.name !== undefined) camera.name = cameraDef.name
+ assignExtrasToUserData(camera, cameraDef)
return Promise.resolve(camera)
- };
- GLTFParser.prototype.loadSkin = function(skinIndex) {
- var skinDef = this.json.skins[skinIndex];
- var skinEntry = {
+ }
+ GLTFParser.prototype.loadSkin = function (skinIndex) {
+ const skinDef = this.json.skins[skinIndex]
+ const skinEntry = {
joints: skinDef.joints
- };
+ }
if (skinDef.inverseBindMatrices === undefined) {
return Promise.resolve(skinEntry)
}
- return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function(accessor) {
- skinEntry.inverseBindMatrices = accessor;
+ return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
+ skinEntry.inverseBindMatrices = accessor
return skinEntry
})
- };
- GLTFParser.prototype.loadAnimation = function(animationIndex) {
- var json = this.json;
- var animationDef = json.animations[animationIndex];
- var pendingNodes = [];
- var pendingInputAccessors = [];
- var pendingOutputAccessors = [];
- var pendingSamplers = [];
- var pendingTargets = [];
- for (var i = 0,
- il = animationDef.channels.length; i < il; i++) {
- var channel = animationDef.channels[i];
- var sampler = animationDef.samplers[channel.sampler];
- var target = channel.target;
- var name = target.node !== undefined ? target.node: target.id;
- var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
- var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
- pendingNodes.push(this.getDependency('node', name));
- pendingInputAccessors.push(this.getDependency('accessor', input));
- pendingOutputAccessors.push(this.getDependency('accessor', output));
- pendingSamplers.push(sampler);
+ }
+ GLTFParser.prototype.loadAnimation = function (animationIndex) {
+ const json = this.json
+ const animationDef = json.animations[animationIndex]
+ const pendingNodes = []
+ const pendingInputAccessors = []
+ const pendingOutputAccessors = []
+ const pendingSamplers = []
+ const pendingTargets = []
+ for (let i = 0,
+ il = animationDef.channels.length; i < il; i++) {
+ const channel = animationDef.channels[i]
+ const sampler = animationDef.samplers[channel.sampler]
+ const target = channel.target
+ const name = target.node !== undefined ? target.node : target.id
+ const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input
+ const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output
+ pendingNodes.push(this.getDependency('node', name))
+ pendingInputAccessors.push(this.getDependency('accessor', input))
+ pendingOutputAccessors.push(this.getDependency('accessor', output))
+ pendingSamplers.push(sampler)
pendingTargets.push(target)
}
- return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function(dependencies) {
- var nodes = dependencies[0];
- var inputAccessors = dependencies[1];
- var outputAccessors = dependencies[2];
- var samplers = dependencies[3];
- var targets = dependencies[4];
- var tracks = [];
- for (var i = 0,
- il = nodes.length; i < il; i++) {
- var node = nodes[i];
- var inputAccessor = inputAccessors[i];
- var outputAccessor = outputAccessors[i];
- var sampler = samplers[i];
- var target = targets[i];
- if (node === undefined) continue;
- node.updateMatrix();
- node.matrixAutoUpdate = true;
- var TypedKeyframeTrack;
+ return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
+ const nodes = dependencies[0]
+ const inputAccessors = dependencies[1]
+ const outputAccessors = dependencies[2]
+ const samplers = dependencies[3]
+ const targets = dependencies[4]
+ const tracks = []
+ for (let i = 0,
+ il = nodes.length; i < il; i++) {
+ const node = nodes[i]
+ const inputAccessor = inputAccessors[i]
+ const outputAccessor = outputAccessors[i]
+ const sampler = samplers[i]
+ const target = targets[i]
+ if (node === undefined) continue
+ node.updateMatrix()
+ node.matrixAutoUpdate = true
+ var TypedKeyframeTrack
switch (PATH_PROPERTIES[target.path]) {
- case PATH_PROPERTIES.weights:
- TypedKeyframeTrack = THREE.NumberKeyframeTrack;
- break;
- case PATH_PROPERTIES.rotation:
- TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
- break;
- case PATH_PROPERTIES.position:
- case PATH_PROPERTIES.scale:
- default:
- TypedKeyframeTrack = THREE.VectorKeyframeTrack;
- break
+ case PATH_PROPERTIES.weights:
+ TypedKeyframeTrack = THREE.NumberKeyframeTrack
+ break
+ case PATH_PROPERTIES.rotation:
+ TypedKeyframeTrack = THREE.QuaternionKeyframeTrack
+ break
+ case PATH_PROPERTIES.position:
+ case PATH_PROPERTIES.scale:
+ default:
+ TypedKeyframeTrack = THREE.VectorKeyframeTrack
+ break
}
- var targetName = node.name ? node.name: node.uuid;
- var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : THREE.InterpolateLinear;
- var targetNames = [];
+ const targetName = node.name ? node.name : node.uuid
+ const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : THREE.InterpolateLinear
+ var targetNames = []
if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
- node.traverse(function(object) {
+ node.traverse(function (object) {
if (object.isMesh === true && object.morphTargetInfluences) {
- targetNames.push(object.name ? object.name: object.uuid)
+ targetNames.push(object.name ? object.name : object.uuid)
}
})
} else {
targetNames.push(targetName)
}
- var outputArray = outputAccessor.array;
+ let outputArray = outputAccessor.array
if (outputAccessor.normalized) {
- var scale;
+ var scale
if (outputArray.constructor === Int8Array) {
scale = 1 / 127
} else if (outputArray.constructor === Uint8Array) {
@@ -1444,61 +1461,61 @@ export function registerGLTFLoader(THREE) {
} else if (outputArray.constructor === Uint16Array) {
scale = 1 / 65535
} else {
- throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
+ throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.')
}
- var scaled = new Float32Array(outputArray.length);
+ const scaled = new Float32Array(outputArray.length)
for (var j = 0,
- jl = outputArray.length; j < jl; j++) {
+ jl = outputArray.length; j < jl; j++) {
scaled[j] = outputArray[j] * scale
}
outputArray = scaled
}
for (var j = 0,
- jl = targetNames.length; j < jl; j++) {
- var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation);
+ jl = targetNames.length; j < jl; j++) {
+ const track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation)
if (sampler.interpolation === 'CUBICSPLINE') {
track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result)
- };
+ }
track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true
}
tracks.push(track)
}
}
- var name = animationDef.name !== undefined ? animationDef.name: 'animation_' + animationIndex;
+ const name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex
return new THREE.AnimationClip(name, undefined, tracks)
})
- };
- GLTFParser.prototype.loadNode = function(nodeIndex) {
- var json = this.json;
- var extensions = this.extensions;
- var parser = this;
- var meshReferences = json.meshReferences;
- var meshUses = json.meshUses;
- var nodeDef = json.nodes[nodeIndex];
- return (function() {
- var pending = [];
+ }
+ GLTFParser.prototype.loadNode = function (nodeIndex) {
+ const json = this.json
+ const extensions = this.extensions
+ const parser = this
+ const meshReferences = json.meshReferences
+ const meshUses = json.meshUses
+ const nodeDef = json.nodes[nodeIndex]
+ return (function () {
+ const pending = []
if (nodeDef.mesh !== undefined) {
- pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function(mesh) {
- var node;
+ pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
+ let node
if (meshReferences[nodeDef.mesh] > 1) {
- var instanceNum = meshUses[nodeDef.mesh]++;
- node = mesh.clone();
- node.name += '_instance_' + instanceNum;
- node.onBeforeRender = mesh.onBeforeRender;
- for (var i = 0,
- il = node.children.length; i < il; i++) {
- node.children[i].name += '_instance_' + instanceNum;
+ const instanceNum = meshUses[nodeDef.mesh]++
+ node = mesh.clone()
+ node.name += '_instance_' + instanceNum
+ node.onBeforeRender = mesh.onBeforeRender
+ for (let i = 0,
+ il = node.children.length; i < il; i++) {
+ node.children[i].name += '_instance_' + instanceNum
node.children[i].onBeforeRender = mesh.children[i].onBeforeRender
}
} else {
node = mesh
}
if (nodeDef.weights !== undefined) {
- node.traverse(function(o) {
- if (!o.isMesh) return;
- for (var i = 0,
- il = nodeDef.weights.length; i < il; i++) {
+ node.traverse(function (o) {
+ if (!o.isMesh) return
+ for (let i = 0,
+ il = nodeDef.weights.length; i < il; i++) {
o.morphTargetInfluences[i] = nodeDef.weights[i]
}
})
@@ -1513,8 +1530,8 @@ export function registerGLTFLoader(THREE) {
pending.push(parser.getDependency('light', nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light))
}
return Promise.all(pending)
- } ()).then(function(objects) {
- var node;
+ }()).then(function (objects) {
+ let node
if (nodeDef.isBone === true) {
node = new THREE.Bone()
} else if (objects.length > 1) {
@@ -1525,20 +1542,20 @@ export function registerGLTFLoader(THREE) {
node = new THREE.Object3D()
}
if (node !== objects[0]) {
- for (var i = 0,
- il = objects.length; i < il; i++) {
+ for (let i = 0,
+ il = objects.length; i < il; i++) {
node.add(objects[i])
}
}
if (nodeDef.name !== undefined) {
- node.userData.name = nodeDef.name;
+ node.userData.name = nodeDef.name
node.name = THREE.PropertyBinding.sanitizeNodeName(nodeDef.name)
}
- assignExtrasToUserData(node, nodeDef);
- if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
+ assignExtrasToUserData(node, nodeDef)
+ if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef)
if (nodeDef.matrix !== undefined) {
- var matrix = new THREE.Matrix4();
- matrix.fromArray(nodeDef.matrix);
+ const matrix = new THREE.Matrix4()
+ matrix.fromArray(nodeDef.matrix)
node.applyMatrix(matrix)
} else {
if (nodeDef.translation !== undefined) {
@@ -1553,32 +1570,32 @@ export function registerGLTFLoader(THREE) {
}
return node
})
- };
- GLTFParser.prototype.loadScene = function() {
+ }
+ GLTFParser.prototype.loadScene = (function () {
function buildNodeHierachy(nodeId, parentObject, json, parser) {
- var nodeDef = json.nodes[nodeId];
- return parser.getDependency('node', nodeId).then(function(node) {
- if (nodeDef.skin === undefined) return node;
- var skinEntry;
- return parser.getDependency('skin', nodeDef.skin).then(function(skin) {
- skinEntry = skin;
- var pendingJoints = [];
- for (var i = 0,
- il = skinEntry.joints.length; i < il; i++) {
+ const nodeDef = json.nodes[nodeId]
+ return parser.getDependency('node', nodeId).then(function (node) {
+ if (nodeDef.skin === undefined) return node
+ let skinEntry
+ return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
+ skinEntry = skin
+ const pendingJoints = []
+ for (let i = 0,
+ il = skinEntry.joints.length; i < il; i++) {
pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]))
}
return Promise.all(pendingJoints)
- }).then(function(jointNodes) {
- node.traverse(function(mesh) {
- if (!mesh.isMesh) return;
- var bones = [];
- var boneInverses = [];
- for (var j = 0,
- jl = jointNodes.length; j < jl; j++) {
- var jointNode = jointNodes[j];
+ }).then(function (jointNodes) {
+ node.traverse(function (mesh) {
+ if (!mesh.isMesh) return
+ const bones = []
+ const boneInverses = []
+ for (let j = 0,
+ jl = jointNodes.length; j < jl; j++) {
+ const jointNode = jointNodes[j]
if (jointNode) {
- bones.push(jointNode);
- var mat = new THREE.Matrix4();
+ bones.push(jointNode)
+ const mat = new THREE.Matrix4()
if (skinEntry.inverseBindMatrices !== undefined) {
mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16)
}
@@ -1588,17 +1605,17 @@ export function registerGLTFLoader(THREE) {
}
}
mesh.bind(new THREE.Skeleton(bones, boneInverses), mesh.matrixWorld)
- });
+ })
return node
})
- }).then(function(node) {
- parentObject.add(node);
- var pending = [];
+ }).then(function (node) {
+ parentObject.add(node)
+ const pending = []
if (nodeDef.children) {
- var children = nodeDef.children;
- for (var i = 0,
- il = children.length; i < il; i++) {
- var child = children[i];
+ const children = nodeDef.children
+ for (let i = 0,
+ il = children.length; i < il; i++) {
+ const child = children[i]
pending.push(buildNodeHierachy(child, node, json, parser))
}
}
@@ -1606,25 +1623,25 @@ export function registerGLTFLoader(THREE) {
})
}
return function loadScene(sceneIndex) {
- var json = this.json;
- var extensions = this.extensions;
- var sceneDef = this.json.scenes[sceneIndex];
- var parser = this;
- var scene = new THREE.Scene();
- if (sceneDef.name !== undefined) scene.name = sceneDef.name;
- assignExtrasToUserData(scene, sceneDef);
- if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
- var nodeIds = sceneDef.nodes || [];
- var pending = [];
- for (var i = 0,
- il = nodeIds.length; i < il; i++) {
+ const json = this.json
+ const extensions = this.extensions
+ const sceneDef = this.json.scenes[sceneIndex]
+ const parser = this
+ const scene = new THREE.Scene()
+ if (sceneDef.name !== undefined) scene.name = sceneDef.name
+ assignExtrasToUserData(scene, sceneDef)
+ if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef)
+ const nodeIds = sceneDef.nodes || []
+ const pending = []
+ for (let i = 0,
+ il = nodeIds.length; i < il; i++) {
pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser))
}
- return Promise.all(pending).then(function() {
+ return Promise.all(pending).then(function () {
return scene
})
}
- } ();
+ }())
return GLTFLoader
- })();
-}
\ No newline at end of file
+ }())
+}
diff --git a/miniprogram/packageAPI/pages/ar/ocr-detect/behavior.js b/miniprogram/packageAPI/pages/ar/ocr-detect/behavior.js
index 08238e25..867744d8 100644
--- a/miniprogram/packageAPI/pages/ar/ocr-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/ocr-detect/behavior.js
@@ -1,205 +1,202 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio / 2
- this.canvas.height = height * pixelRatio / 2
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.textContentList) this.textContentList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- OCR: {
- mode: 1
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio / 2
- this.canvas.height = height * pixelRatio / 2
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- console.log("anchor add")
- })
- session.on('updateAnchors', anchors => {
- this.data.textContentList = []
-
- // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
- this.data.textContentList = this.data.textContentList.concat(anchors.map(anchor => {
- return {
- text: anchor.text,
- subtext: anchor.subtext,
- box: anchor.box
- };
- }))
-
- var wholeText = undefined
- if(this.data.textContentList.length != 0){
- wholeText = this.data.textContentList[0].text
- }
-
- this.setData({
- textContentList: this.data.textContentList,
- wholeText: wholeText
- })
- })
- session.on('removeAnchors', anchors => {
- console.log("anchor remove")
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio / 2
+ this.canvas.height = height * pixelRatio / 2
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.textContentList) this.textContentList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ OCR: {
+ mode: 1
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio / 2
+ this.canvas.height = height * pixelRatio / 2
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ console.log('anchor add')
+ })
+ session.on('updateAnchors', anchors => {
+ this.data.textContentList = []
+
+ // 摄像头实时检测人脸的时候 updateAnchors 会在每帧触发,所以性能要求更高,用 gl 画
+ this.data.textContentList = this.data.textContentList.concat(anchors.map(anchor => ({
+ text: anchor.text,
+ subtext: anchor.subtext,
+ box: anchor.box
+ })))
+
+ let wholeText
+ if (this.data.textContentList.length != 0) {
+ wholeText = this.data.textContentList[0].text
+ }
+
+ this.setData({
+ textContentList: this.data.textContentList,
+ wholeText
+ })
+ })
+ session.on('removeAnchors', anchors => {
+ console.log('anchor remove')
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/ocr-detect/ocr-detect.js b/miniprogram/packageAPI/pages/ar/ocr-detect/ocr-detect.js
index 2a925ce0..8b4d313f 100644
--- a/miniprogram/packageAPI/pages/ar/ocr-detect/ocr-detect.js
+++ b/miniprogram/packageAPI/pages/ar/ocr-detect/ocr-detect.js
@@ -4,48 +4,48 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-//初始化着色器函数
+// 初始化着色器函数
let initShadersDone = false
function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
- //创建顶点着色器对象
- var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
- //创建片元着色器对象
- var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
+ // 创建顶点着色器对象
+ const vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
+ // 创建片元着色器对象
+ const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)
if (!vertexShader || !fragmentShader) {
return null
}
- //创建程序对象program
- var program = gl.createProgram()
+ // 创建程序对象program
+ const program = gl.createProgram()
if (!gl.createProgram()) {
return null
}
- //分配顶点着色器和片元着色器到program
+ // 分配顶点着色器和片元着色器到program
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
- //链接program
+ // 链接program
gl.linkProgram(program)
- //检查程序对象是否连接成功
- var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
+ // 检查程序对象是否连接成功
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS)
if (!linked) {
- var error = gl.getProgramInfoLog(program)
+ const error = gl.getProgramInfoLog(program)
console.log('程序对象连接失败: ' + error)
gl.deleteProgram(program)
gl.deleteShader(fragmentShader)
gl.deleteShader(vertexShader)
return null
}
- //返回程序program对象
+ // 返回程序program对象
initShadersDone = true
return program
}
function loadShader(gl, type, source) {
// 创建顶点着色器对象
- var shader = gl.createShader(type)
+ const shader = gl.createShader(type)
if (shader == null) {
console.log('创建着色器失败')
return null
@@ -58,9 +58,9 @@ function loadShader(gl, type, source) {
gl.compileShader(shader)
// 检查顶是否编译成功
- var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
+ const compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!compiled) {
- var error = gl.getShaderInfoLog(shader)
+ const error = gl.getShaderInfoLog(shader)
console.log('编译着色器失败: ' + error)
gl.deleteShader(shader)
return null
@@ -69,7 +69,7 @@ function loadShader(gl, type, source) {
return shader
}
-var EDGE_VSHADER_SOURCE =
+const EDGE_VSHADER_SOURCE =
`
attribute vec4 aPosition;
void main(void) {
@@ -77,7 +77,7 @@ var EDGE_VSHADER_SOURCE =
}
`
-var EDGE_FSHADER_SOURCE =
+const EDGE_FSHADER_SOURCE =
`
precision highp float;
void main() {
@@ -86,33 +86,33 @@ var EDGE_FSHADER_SOURCE =
`
function initEdgeBuffer(gl, lt, lr, rb, lb) {
- let shaderProgram = gl.program;
- var vertices = [
+ const shaderProgram = gl.program
+ const vertices = [
lt.x, lt.y, 0.0,
lr.x, lr.y, 0.0,
rb.x, rb.y, 0.0,
lb.x, lb.y, 0.0,
- ];
-
- var vertexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
- var aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');
- gl.enableVertexAttribArray(aPosition);
- gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0);
- var length = vertices.length / 3;
- return length;
+ ]
+
+ const vertexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
+ const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition')
+ gl.enableVertexAttribArray(aPosition)
+ gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0)
+ const length = vertices.length / 3
+ return length
}
function onDrawEdge(gl, lt, lr, rb, lb) {
- var n = initEdgeBuffer(gl, lt, lr, rb, lb);
- gl.drawArrays(gl.LINE_LOOP, 0, n);
+ const n = initEdgeBuffer(gl, lt, lr, rb, lb)
+ gl.drawArrays(gl.LINE_LOOP, 0, n)
}
-function convert(obj){
- obj.x = obj.x * 2 -1;
- obj.y = (1-obj.y)*2-1;
- return obj;
+function convert(obj) {
+ obj.x = obj.x * 2 - 1
+ obj.y = (1 - obj.y) * 2 - 1
+ return obj
}
Component({
@@ -126,15 +126,15 @@ Component({
*/
detached() {
initShadersDone = false
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -160,12 +160,10 @@ Component({
// this.canvas.requestAnimationFrame(onFrame1)
// }
// this.canvas.requestAnimationFrame(onFrame1)
-
},
-
render(frame) {
- var gl = this.gl
+ const gl = this.gl
this.renderGL(frame)
@@ -190,7 +188,7 @@ Component({
if (!textContentList || textContentList.length <= 0) {
return
- }else{
+ } else {
if (!initShadersDone) {
this.edgeProgram = initShaders(gl, EDGE_VSHADER_SOURCE, EDGE_FSHADER_SOURCE)
if (!this.edgeProgram) {
@@ -200,37 +198,35 @@ Component({
console.log('初始化着色器成功')
}
- if(textContentList[0].box == undefined){
- return;
+ if (textContentList[0].box == undefined) {
+ return
}
-
+
gl.useProgram(this.edgeProgram)
gl.program = this.edgeProgram
- var lt,lr,rb,lb;
- for (var i = 0; i < textContentList.length; i++) {
+ let lt; let lr; let rb; let lb
+ for (let i = 0; i < textContentList.length; i++) {
lt = textContentList[i].box[0]
lr = textContentList[i].box[1]
rb = textContentList[i].box[2]
lb = textContentList[i].box[3]
- let avgX = (lt.x + lr.x + rb.x + lb.x) / 4;
- let avgY = (lt.y + lr.y + rb.y + lb.y) / 4;
- textContentList[i].centerX = avgX * this.data.width;
- textContentList[i].centerY = avgY * this.data.height;
-
+ const avgX = (lt.x + lr.x + rb.x + lb.x) / 4
+ const avgY = (lt.y + lr.y + rb.y + lb.y) / 4
+ textContentList[i].centerX = avgX * this.data.width
+ textContentList[i].centerY = avgY * this.data.height
+
lt = convert(lt)
lr = convert(lr)
rb = convert(rb)
lb = convert(lb)
- onDrawEdge(gl,lt, lr, rb, lb);
+ onDrawEdge(gl, lt, lr, rb, lb)
}
}
this.setData({
- textContentList: textContentList
+ textContentList
})
-
-
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/ocr-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/ocr-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/ocr-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/ocr-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/osd-ar/behavior.js b/miniprogram/packageAPI/pages/ar/osd-ar/behavior.js
index a4eeacfc..68c69ff9 100644
--- a/miniprogram/packageAPI/pages/ar/osd-ar/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/osd-ar/behavior.js
@@ -128,23 +128,22 @@ export default function getBehavior() {
this.afterVKSessionCreated()
}
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
// 逐帧渲染
const onFrame = timestamp => {
- let now = Date.now()
+ const now = Date.now()
const mill = now - last
// 经过了足够的时间
if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
}
session.requestAnimationFrame(onFrame)
}
@@ -179,4 +178,4 @@ export default function getBehavior() {
},
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/osd-ar/osd-ar.js b/miniprogram/packageAPI/pages/ar/osd-ar/osd-ar.js
index ad9b747f..aea30f80 100644
--- a/miniprogram/packageAPI/pages/ar/osd-ar/osd-ar.js
+++ b/miniprogram/packageAPI/pages/ar/osd-ar/osd-ar.js
@@ -15,27 +15,27 @@ Component({
frameHeight: 0,
},
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
init() {
@@ -95,14 +95,13 @@ Component({
} = res
console.log('getImageInfo res', res)
this.setData({
- imgUrl: imgUrl,
+ imgUrl,
})
},
fail: res => {
console.error(res)
}
})
-
},
fail: res => {
console.error(res)
@@ -160,17 +159,15 @@ Component({
console.log('[addMarker] --> ', filePath)
this.markerId = this.session.addOSDMarker(filePath)
this.setData({
- "filePathNow": filePath
+ filePathNow: filePath
})
}
- const getFilePathNow = () => {
- return this.data.filePathNow;
- }
+ const getFilePathNow = () => this.data.filePathNow
fs.stat({
path: filePath,
success(res) {
- let path = getFilePathNow()
+ const path = getFilePathNow()
if (path != filePath) {
if (res.stats.isFile() && path) {
fs.unlinkSync(path)
@@ -196,4 +193,4 @@ Component({
console.log(this.session.getAllOSDMarker())
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/osd-ar/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/osd-ar/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/osd-ar/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/osd-ar/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-body-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-body-detect/behavior.js
index b5dde3e3..3cbc9a57 100644
--- a/miniprogram/packageAPI/pages/ar/photo-body-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-body-detect/behavior.js
@@ -1,206 +1,205 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- body: {
- mode: 2
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })),
- })
- })
- session.on('updateAnchors', anchors => {
- this.data.anchor2DList = []
- // 手动传入图像的时候用dom画点和框就行
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })),
- })
- })
- session.on('removeAnchors', anchors => {
- this.setData({
- anchor2DList: [],
- })
- this.data.anchor2DList = []
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ body: {
+ mode: 2
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })),
+ })
+ })
+ session.on('updateAnchors', anchors => {
+ this.data.anchor2DList = []
+ // 手动传入图像的时候用dom画点和框就行
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })),
+ })
+ })
+ session.on('removeAnchors', anchors => {
+ this.setData({
+ anchor2DList: [],
+ })
+ this.data.anchor2DList = []
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-body-detect/photo-body-detect.js b/miniprogram/packageAPI/pages/ar/photo-body-detect/photo-body-detect.js
index 9be9e562..3d90861d 100644
--- a/miniprogram/packageAPI/pages/ar/photo-body-detect/photo-body-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-body-detect/photo-body-detect.js
@@ -5,129 +5,128 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- bodyImgUrl: '',
- bodyImgWidth: 0,
- bodyImgHeight: 0,
- bodyImgOriginWidth: 0,
- bodyImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ bodyImgUrl: '',
+ bodyImgWidth: 0,
+ bodyImgHeight: 0,
+ bodyImgOriginWidth: 0,
+ bodyImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- bodyImgUrl: imgUrl,
- bodyImgWidth: fixWidth,
- bodyImgHeight: (fixWidth / width) * height,
- bodyImgOriginWidth: width,
- bodyImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- this.initGL()
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ bodyImgUrl: imgUrl,
+ bodyImgWidth: fixWidth,
+ bodyImgHeight: (fixWidth / width) * height,
+ bodyImgOriginWidth: width,
+ bodyImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- render(frame) {
- return
- this.renderGL(frame)
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ init() {
+ this.initGL()
+ },
+ render(frame) {
+ return
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullbody(this.THREE.CullbodyNone)
- },
- async detectbody() {
- if (this.data.bodyImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.bodyImgOriginWidth,
- height: this.data.bodyImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.bodyImgUrl
- })
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullbody(this.THREE.CullbodyNone)
+ },
+ async detectbody() {
+ if (this.data.bodyImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.bodyImgOriginWidth,
+ height: this.data.bodyImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.bodyImgUrl
+ })
- context.clearRect(0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
+ context.clearRect(0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.bodyImgOriginWidth, this.data.bodyImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectbody', this.session.detectbody)
- console.log('width', this.data.bodyImgOriginWidth)
- console.log('height', this.data.bodyImgOriginHeight)
- this.session.detectBody({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.bodyImgOriginWidth,
- height: this.data.bodyImgOriginHeight,
- scoreThreshold: 0.5, // 评分阈值
- sourceType: 1
- })
- }
- },
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectbody', this.session.detectbody)
+ console.log('width', this.data.bodyImgOriginWidth)
+ console.log('height', this.data.bodyImgOriginHeight)
+ this.session.detectBody({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.bodyImgOriginWidth,
+ height: this.data.bodyImgOriginHeight,
+ scoreThreshold: 0.5, // 评分阈值
+ sourceType: 1
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-body-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-body-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/photo-body-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-body-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-depth-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-depth-detect/behavior.js
index d5b516cb..f4aa1f91 100644
--- a/miniprogram/packageAPI/pages/ar/photo-depth-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-depth-detect/behavior.js
@@ -96,7 +96,7 @@ export default function getBehavior() {
depth: {
mode: 2
}
- },
+ },
cameraPosition: 0,
version: 'v1',
gl: this.gl
@@ -126,29 +126,26 @@ export default function getBehavior() {
session.on('addAnchors', anchors => {
})
session.on('updateAnchors', anchors => {
- let depthArray = []
+ const depthArray = []
// 手动传入图像的时候用dom画点和框就行
- let anchor2DList = anchors.map(anchor => {
- return {
- value: anchor.depthArray,
- size: anchor.size
- }})
- wx.hideLoading()
- if (anchor2DList.length > 0) {
- let width = 80
- let height = 80
- anchor2DList.forEach(anchor => {
- width = anchor.size[0]
- height = anchor.size[1]
- anchor.value.forEach(item =>{
- depthArray.push(item.value)
- })
- this.renderDepthGL(depthArray, width, height)
-
+ const anchor2DList = anchors.map(anchor => ({
+ value: anchor.depthArray,
+ size: anchor.size
+ }))
+ wx.hideLoading()
+ if (anchor2DList.length > 0) {
+ let width = 80
+ let height = 80
+ anchor2DList.forEach(anchor => {
+ width = anchor.size[0]
+ height = anchor.size[1]
+ anchor.value.forEach(item => {
+ depthArray.push(item.value)
+ })
+ this.renderDepthGL(depthArray, width, height)
})
- }
}
- )
+ })
session.on('removeAnchors', anchors => {
})
})
@@ -181,4 +178,4 @@ export default function getBehavior() {
},
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-depth-detect/depthBehavior.js b/miniprogram/packageAPI/pages/ar/photo-depth-detect/depthBehavior.js
index 818b18fa..5836beb6 100644
--- a/miniprogram/packageAPI/pages/ar/photo-depth-detect/depthBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-depth-detect/depthBehavior.js
@@ -1,12 +1,11 @@
const depthBehavior = Behavior({
- methods: {
- initDepthShader() {
- const gl = this.gl = this.renderer.getContext()
- const ext = gl.getExtension("OES_texture_float");
- if(!ext)
- console.warn('OES_texture_float not support');
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initDepthShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_texture_float')
+ if (!ext) console.warn('OES_texture_float not support')
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
precision highp float;
attribute vec2 a_position;
attribute vec2 a_texCoord;
@@ -16,7 +15,7 @@ const depthBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D depth_texture;
varying vec2 v_texCoord;
@@ -25,123 +24,122 @@ const depthBehavior = Behavior({
gl_FragColor = vec4(depth_color.rgb , 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._depthProgram = gl.createProgram()
- this._depthProgram.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformTexture = gl.getUniformLocation(program, 'depth_texture')
- gl.uniform1i(uniformTexture, 5)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initDepthVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._depthProgram, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._depthProgram, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 0, 0, 0, 1, 1, 0, 1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._depthVao = vao
- },
- initDepthGL() {
- this.initDepthShader()
- this.initDepthVAO()
- },
- renderDepthGL(depthBuffer, width, height) {
- const gl = this.renderer.getContext()
-
- gl.disable(gl.DEPTH_TEST) //缺少这句安卓端可能绘制不出图像
-
- let depthTexture = gl.createTexture()
- gl.bindTexture(gl.TEXTURE_2D, depthTexture)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
-
- const ext = gl.getExtension("OES_texture_float");
- if(ext){
- const data = new Float32Array(width * height * 4);
- for (let i = 0; i < depthBuffer.length; i++) {
- data[i * 4] = depthBuffer[i];
- data[i * 4 + 1] = depthBuffer[i];
- data[i * 4 + 2] = depthBuffer[i];
- data[i * 4 + 3] = depthBuffer[i];
- }
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, data);
- }else{
- const data = new Uint8Array(width * height * 4);
- for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i * 4] = num;
- data[i * 4 + 1] = num;
- data[i * 4 + 2] = num;
- data[i * 4 + 3] = num;
- }
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
- }
-
- depthTexture._gl = gl
- gl.bindTexture(gl.TEXTURE_2D, null)
-
- if (depthTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- let currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
-
- gl.useProgram(this._depthProgram)
- this.ext.bindVertexArrayOES(this._depthVao)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, depthTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._depthProgram = gl.createProgram()
+ this._depthProgram.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformTexture = gl.getUniformLocation(program, 'depth_texture')
+ gl.uniform1i(uniformTexture, 5)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initDepthVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._depthProgram, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._depthProgram, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 0, 0, 0, 1, 1, 0, 1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._depthVao = vao
+ },
+ initDepthGL() {
+ this.initDepthShader()
+ this.initDepthVAO()
+ },
+ renderDepthGL(depthBuffer, width, height) {
+ const gl = this.renderer.getContext()
+
+ gl.disable(gl.DEPTH_TEST) // 缺少这句安卓端可能绘制不出图像
+
+ const depthTexture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, depthTexture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+
+ const ext = gl.getExtension('OES_texture_float')
+ if (ext) {
+ const data = new Float32Array(width * height * 4)
+ for (let i = 0; i < depthBuffer.length; i++) {
+ data[i * 4] = depthBuffer[i]
+ data[i * 4 + 1] = depthBuffer[i]
+ data[i * 4 + 2] = depthBuffer[i]
+ data[i * 4 + 3] = depthBuffer[i]
+ }
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, data)
+ } else {
+ const data = new Uint8Array(width * height * 4)
+ for (let i = 0; i < depthBuffer.length; i++) {
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i * 4] = num
+ data[i * 4 + 1] = num
+ data[i * 4 + 2] = num
+ data[i * 4 + 3] = num
+ }
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
+ }
+
+ depthTexture._gl = gl
+ gl.bindTexture(gl.TEXTURE_2D, null)
+
+ if (depthTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._depthProgram)
+ this.ext.bindVertexArrayOES(this._depthVao)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, depthTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default depthBehavior
\ No newline at end of file
+export default depthBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-depth-detect/photo-depth-detect.js b/miniprogram/packageAPI/pages/ar/photo-depth-detect/photo-depth-detect.js
index c9cfaacd..3f533123 100644
--- a/miniprogram/packageAPI/pages/ar/photo-depth-detect/photo-depth-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-depth-detect/photo-depth-detect.js
@@ -6,120 +6,118 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior, depthBehavior],
- data: {
- depthImgUrl: '',
- depthImgWidth: 0,
- depthImgHeight: 0,
- depthImgOriginWidth: 0,
- depthImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior, depthBehavior],
+ data: {
+ depthImgUrl: '',
+ depthImgWidth: 0,
+ depthImgHeight: 0,
+ depthImgOriginWidth: 0,
+ depthImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- let depthImgWidth
- let depthImgHeight
- if(width > height){
- depthImgWidth = fixWidth
- depthImgHeight = fixWidth * height / width
- }else{
- depthImgWidth = fixWidth * width / height
- depthImgHeight = fixWidth
- }
- this.setData({
- depthImgUrl: imgUrl,
- depthImgWidth,
- depthImgHeight,
- depthImgOriginWidth: width,
- depthImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- this.initGL()
- this.initDepthGL()
- console.log("init finish")
+ let depthImgWidth
+ let depthImgHeight
+ if (width > height) {
+ depthImgWidth = fixWidth
+ depthImgHeight = fixWidth * height / width
+ } else {
+ depthImgWidth = fixWidth * width / height
+ depthImgHeight = fixWidth
+ }
+ this.setData({
+ depthImgUrl: imgUrl,
+ depthImgWidth,
+ depthImgHeight,
+ depthImgOriginWidth: width,
+ depthImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- async detectDepth() {
- if (this.data.depthImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.depthImgOriginWidth,
- height: this.data.depthImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.depthImgUrl
- })
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ init() {
+ this.initGL()
+ this.initDepthGL()
+ console.log('init finish')
+ },
+ async detectDepth() {
+ if (this.data.depthImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.depthImgOriginWidth,
+ height: this.data.depthImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.depthImgUrl
+ })
- context.clearRect(0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
+ context.clearRect(0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.depthImgOriginWidth, this.data.depthImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectDepth', this.session.detectDepth)
- console.log('width', this.data.depthImgOriginWidth)
- console.log('height', this.data.depthImgOriginHeight)
- wx.showLoading({ title: '深度图生成中...' });
- this.session.detectDepth({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.depthImgOriginWidth,
- height: this.data.depthImgOriginHeight,
- })
-
- }
- },
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectDepth', this.session.detectDepth)
+ console.log('width', this.data.depthImgOriginWidth)
+ console.log('height', this.data.depthImgOriginHeight)
+ wx.showLoading({ title: '深度图生成中...' })
+ this.session.detectDepth({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.depthImgOriginWidth,
+ height: this.data.depthImgOriginHeight,
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-depth-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-depth-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/photo-depth-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-depth-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-face-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-face-detect/behavior.js
index 89569428..a3951281 100644
--- a/miniprogram/packageAPI/pages/ar/photo-face-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-face-detect/behavior.js
@@ -1,203 +1,202 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- face: {
- mode: 2
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })),
- })
- })
- session.on('updateAnchors', anchors => {
- this.data.anchor2DList = []
- // 手动传入图像的时候用dom画点和框就行
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })),
- })
- })
- session.on('removeAnchors', anchors => {
- this.setData({
- anchor2DList: [],
- })
- this.data.anchor2DList = []
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ face: {
+ mode: 2
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })),
+ })
+ })
+ session.on('updateAnchors', anchors => {
+ this.data.anchor2DList = []
+ // 手动传入图像的时候用dom画点和框就行
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })),
+ })
+ })
+ session.on('removeAnchors', anchors => {
+ this.setData({
+ anchor2DList: [],
+ })
+ this.data.anchor2DList = []
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-face-detect/photo-face-detect.js b/miniprogram/packageAPI/pages/ar/photo-face-detect/photo-face-detect.js
index d3231f8e..d7ab5212 100644
--- a/miniprogram/packageAPI/pages/ar/photo-face-detect/photo-face-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-face-detect/photo-face-detect.js
@@ -5,131 +5,130 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- faceImgUrl: '',
- faceImgWidth: 0,
- faceImgHeight: 0,
- faceImgOriginWidth: 0,
- faceImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ faceImgUrl: '',
+ faceImgWidth: 0,
+ faceImgHeight: 0,
+ faceImgOriginWidth: 0,
+ faceImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- faceImgUrl: imgUrl,
- faceImgWidth: fixWidth,
- faceImgHeight: (fixWidth / width) * height,
- faceImgOriginWidth: width,
- faceImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- // this.initGL()
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ faceImgUrl: imgUrl,
+ faceImgWidth: fixWidth,
+ faceImgHeight: (fixWidth / width) * height,
+ faceImgOriginWidth: width,
+ faceImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- render(frame) {
- return
- this.renderGL(frame)
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ init() {
+ // this.initGL()
+ },
+ render(frame) {
+ return
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
- async detectFace() {
- if (this.data.faceImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.faceImgOriginWidth,
- height: this.data.faceImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.faceImgUrl
- })
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
+ },
+ async detectFace() {
+ if (this.data.faceImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.faceImgOriginWidth,
+ height: this.data.faceImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.faceImgUrl
+ })
- context.clearRect(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ context.clearRect(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectFace', this.session.detectFace)
- console.log('width', this.data.faceImgOriginWidth)
- console.log('height', this.data.faceImgOriginHeight)
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectFace', this.session.detectFace)
+ console.log('width', this.data.faceImgOriginWidth)
+ console.log('height', this.data.faceImgOriginHeight)
- this.session.detectFace({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.faceImgOriginWidth,
- height: this.data.faceImgOriginHeight,
- scoreThreshold: 0.5, // 评分阈值
- sourceType: 1,
- modelMode: 1,
- })
- }
- },
+ this.session.detectFace({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.faceImgOriginWidth,
+ height: this.data.faceImgOriginHeight,
+ scoreThreshold: 0.5, // 评分阈值
+ sourceType: 1,
+ modelMode: 1,
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-face-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-face-detect/yuvBehavior.js
index 47a89766..08ffb7fa 100644
--- a/miniprogram/packageAPI/pages/ar/photo-face-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-face-detect/yuvBehavior.js
@@ -1,10 +1,10 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- console.log("初始化shader完成")
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ console.log('初始化shader完成')
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -15,7 +15,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -38,103 +38,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-hand-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-hand-detect/behavior.js
index a47c0bdf..2334d272 100644
--- a/miniprogram/packageAPI/pages/ar/photo-hand-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-hand-detect/behavior.js
@@ -1,210 +1,209 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- hand: {
- mode: 2
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size,
- gesture: anchor.gesture
- })),
- })
- })
-
- session.on('updateAnchors', anchors => {
- this.data.anchor2DList = []
- // 手动传入图像的时候用dom画点和框就行
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size,
- gesture: anchor.gesture
- })),
- })
- })
-
- session.on('removeAnchors', anchors => {
- this.setData({
- anchor2DList: [],
- })
- this.data.anchor2DList = []
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ hand: {
+ mode: 2
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size,
+ gesture: anchor.gesture
+ })),
+ })
+ })
+
+ session.on('updateAnchors', anchors => {
+ this.data.anchor2DList = []
+ // 手动传入图像的时候用dom画点和框就行
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size,
+ gesture: anchor.gesture
+ })),
+ })
+ })
+
+ session.on('removeAnchors', anchors => {
+ this.setData({
+ anchor2DList: [],
+ })
+ this.data.anchor2DList = []
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-hand-detect/photo-hand-detect.js b/miniprogram/packageAPI/pages/ar/photo-hand-detect/photo-hand-detect.js
index be1f29d4..e543d90f 100644
--- a/miniprogram/packageAPI/pages/ar/photo-hand-detect/photo-hand-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-hand-detect/photo-hand-detect.js
@@ -5,129 +5,128 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- handImgUrl: '',
- handImgWidth: 0,
- handImgHeight: 0,
- handImgOriginWidth: 0,
- handImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ handImgUrl: '',
+ handImgWidth: 0,
+ handImgHeight: 0,
+ handImgOriginWidth: 0,
+ handImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- handImgUrl: imgUrl,
- handImgWidth: fixWidth,
- handImgHeight: (fixWidth / width) * height,
- handImgOriginWidth: width,
- handImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- this.initGL()
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ handImgUrl: imgUrl,
+ handImgWidth: fixWidth,
+ handImgHeight: (fixWidth / width) * height,
+ handImgOriginWidth: width,
+ handImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- render(frame) {
- return
- this.renderGL(frame)
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ init() {
+ this.initGL()
+ },
+ render(frame) {
+ return
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullhand(this.THREE.CullhandNone)
- },
- async detectHand() {
- if (this.data.handImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.handImgOriginWidth,
- height: this.data.handImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.handImgUrl
- })
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullhand(this.THREE.CullhandNone)
+ },
+ async detectHand() {
+ if (this.data.handImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.handImgOriginWidth,
+ height: this.data.handImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.handImgUrl
+ })
- context.clearRect(0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
+ context.clearRect(0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.handImgOriginWidth, this.data.handImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectHand', this.session.detectHand)
- console.log('width', this.data.handImgOriginWidth)
- console.log('height', this.data.handImgOriginHeight)
- this.session.detectHand({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.handImgOriginWidth,
- height: this.data.handImgOriginHeight,
- scoreThreshold: 0.5, // 评分阈值
- algoMode: 2
- })
- }
- },
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectHand', this.session.detectHand)
+ console.log('width', this.data.handImgOriginWidth)
+ console.log('height', this.data.handImgOriginHeight)
+ this.session.detectHand({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.handImgOriginWidth,
+ height: this.data.handImgOriginHeight,
+ scoreThreshold: 0.5, // 评分阈值
+ algoMode: 2
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-hand-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-hand-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/photo-hand-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-hand-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-idcard-detect/photo-idcard-detect.js b/miniprogram/packageAPI/pages/ar/photo-idcard-detect/photo-idcard-detect.js
index 44c06be5..a3a1a0b3 100644
--- a/miniprogram/packageAPI/pages/ar/photo-idcard-detect/photo-idcard-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-idcard-detect/photo-idcard-detect.js
@@ -1,226 +1,223 @@
Component({
- behaviors: [],
- data: {
- // 主题相关逻辑
- theme: 'light',
- // 上传识别相关逻辑
- imgUrl: '',
- imgWidth: 0,
- imgHeight: 0,
- imgOriginWidth: 0,
- imgOriginHeight: 0,
- // 显示身份证识别结果
- detected: false,
- detectSuccess: false,
- isComplete: false,
- label: '',
- orientation: 0,
- box: [],
- cropImg: null,
- },
- lifetimes: {
- /**
+ behaviors: [],
+ data: {
+ // 主题相关逻辑
+ theme: 'light',
+ // 上传识别相关逻辑
+ imgUrl: '',
+ imgWidth: 0,
+ imgHeight: 0,
+ imgOriginWidth: 0,
+ imgOriginHeight: 0,
+ // 显示身份证识别结果
+ detected: false,
+ detectSuccess: false,
+ isComplete: false,
+ label: '',
+ orientation: 0,
+ box: [],
+ cropImg: null,
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
},
- methods: {
- onReady() {
- this.initVK();
+ },
+ methods: {
+ onReady() {
+ this.initVK()
+ },
+ // VK 初始化逻辑
+ initVK() {
+ // VKSession 配置
+ const session = this.session = wx.createVKSession({
+ track: {
+ IDCard: {
+ mode: 2 // 照片模式
+ }
},
- // VK 初始化逻辑
- initVK() {
- // VKSession 配置
- const session = this.session = wx.createVKSession({
- track: {
- IDCard: {
- mode: 2 // 照片模式
- }
- },
- version: 'v1',
- gl: this.gl
- })
-
- // VKSession start
- session.start(err => {
-
- session.on('updateAnchors', anchors => {
- console.log("updateAnchors")
-
- // 处理返回的身份证信息
- if (anchors && anchors[0]) {
- // 存在数组,证明存在身份证信息
- const anchor = anchors[0];
-
- // console.log(anchor.isComplete, anchor.label, anchor.orientation, anchor.box);
-
- this.setData({
- detected: true,
- detectSuccess: true,
- isComplete: anchor.isComplete,
- label: anchor.label,
- orientation: anchor.orientation,
- box: anchor.box,
- });
-
- // 裁剪信息
- const affineImgWidth = anchor.affineImgWidth;
- const affineImgHeight = anchor.affineImgHeight;
- const affineMat = anchor.affineMat;
+ version: 'v1',
+ gl: this.gl
+ })
- // 存在裁剪信息,进行身份证裁剪处理
- if (affineImgWidth && affineImgHeight && affineMat) {
+ // VKSession start
+ session.start(err => {
+ session.on('updateAnchors', anchors => {
+ console.log('updateAnchors')
- console.log(affineImgWidth, affineImgHeight, affineMat);
+ // 处理返回的身份证信息
+ if (anchors && anchors[0]) {
+ // 存在数组,证明存在身份证信息
+ const anchor = anchors[0]
- const cropIDcardImg = this.getCropIDcard(affineImgWidth, affineImgHeight, affineMat);
+ // console.log(anchor.isComplete, anchor.label, anchor.orientation, anchor.box);
- this.setData({
- cropImg: cropIDcardImg
- })
- }
- }
-
- })
- session.on('removeAnchors', anchors => {
- console.log("anchor remove")
+ this.setData({
+ detected: true,
+ detectSuccess: true,
+ isComplete: anchor.isComplete,
+ label: anchor.label,
+ orientation: anchor.orientation,
+ box: anchor.box,
+ })
- // 图片没有识别到身份证
- this.setData({
- detected: true,
- detectSuccess: false,
- });
- })
+ // 裁剪信息
+ const affineImgWidth = anchor.affineImgWidth
+ const affineImgHeight = anchor.affineImgHeight
+ const affineMat = anchor.affineMat
- });
- },
- // 裁剪身份证图片
- getCropIDcard(affineImgWidth, affineImgHeight, affineMat) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: affineImgWidth,
- height: affineImgHeight,
- })
- const context = canvas.getContext('2d')
+ // 存在裁剪信息,进行身份证裁剪处理
+ if (affineImgWidth && affineImgHeight && affineMat) {
+ console.log(affineImgWidth, affineImgHeight, affineMat)
+ const cropIDcardImg = this.getCropIDcard(affineImgWidth, affineImgHeight, affineMat)
- context.clearRect(0, 0, affineImgWidth, affineImgHeight);
- /*
+ this.setData({
+ cropImg: cropIDcardImg
+ })
+ }
+ }
+ })
+ session.on('removeAnchors', anchors => {
+ console.log('anchor remove')
+
+ // 图片没有识别到身份证
+ this.setData({
+ detected: true,
+ detectSuccess: false,
+ })
+ })
+ })
+ },
+ // 裁剪身份证图片
+ getCropIDcard(affineImgWidth, affineImgHeight, affineMat) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: affineImgWidth,
+ height: affineImgHeight,
+ })
+ const context = canvas.getContext('2d')
+
+ context.clearRect(0, 0, affineImgWidth, affineImgHeight)
+ /*
* affineMat 3x3仿射变换矩阵,行主序
* [0 1 2
* 3 4 5
* 6 7 8]
*/
- /*
+ /*
* canvas 2d setTransform
* setTransform(a, b, c, d, e, f)
* [a c e
* b d f
* 0 0 1]
*/
- context.setTransform(
- Number(affineMat[0]), Number(affineMat[3]), Number(affineMat[1]),
- Number(affineMat[4]), Number(affineMat[2]), Number(affineMat[5])
- );
- console.log(this.img, this.data.imgOriginWidth, this.data.imgOriginHeight)
- context.drawImage(this.img, 0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
- const imgUrl = canvas.toDataURL()
-
- // console.log(imgUrl);
-
- return imgUrl;
-
- },
- // 上传识别图片
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- imgUrl: imgUrl,
- imgWidth: fixWidth,
- imgHeight: (fixWidth / width) * height,
- imgOriginWidth: width,
- imgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
-
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- // 识别身份证逻辑
- async detectIDCard() {
- console.log('detectIDCard')
- if (this.data.imgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.imgOriginWidth,
- height: this.data.imgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- // 使用中的 图片对象
- this.img = img;
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.imgUrl
- })
-
- context.clearRect(0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
- context.drawImage(img, 0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
-
- // 使用中的 image ArrayBuffer
- this.imgData = context.getImageData(0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
-
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectIDCard', this.session.detectIDCard)
- console.log('width', this.data.imgOriginWidth)
- console.log('height', this.data.imgOriginHeight)
- this.session.detectIDCard({
- // 识别身份证图片的信息
- frameBuffer: this.imgData.data.buffer,
- width: this.data.imgOriginWidth,
- height: this.data.imgOriginHeight,
- // 是否获取裁剪图片信息
- getAffineImg: true,
- })
+ context.setTransform(
+ Number(affineMat[0]),
+ Number(affineMat[3]),
+ Number(affineMat[1]),
+ Number(affineMat[4]),
+ Number(affineMat[2]),
+ Number(affineMat[5])
+ )
+ console.log(this.img, this.data.imgOriginWidth, this.data.imgOriginHeight)
+ context.drawImage(this.img, 0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
+ const imgUrl = canvas.toDataURL()
+
+ // console.log(imgUrl);
+
+ return imgUrl
+ },
+ // 上传识别图片
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ imgUrl,
+ imgWidth: fixWidth,
+ imgHeight: (fixWidth / width) * height,
+ imgOriginWidth: width,
+ imgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
}
+ })
},
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ // 识别身份证逻辑
+ async detectIDCard() {
+ console.log('detectIDCard')
+ if (this.data.imgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.imgOriginWidth,
+ height: this.data.imgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ // 使用中的 图片对象
+ this.img = img
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.imgUrl
+ })
+
+ context.clearRect(0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
+
+ // 使用中的 image ArrayBuffer
+ this.imgData = context.getImageData(0, 0, this.data.imgOriginWidth, this.data.imgOriginHeight)
+
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectIDCard', this.session.detectIDCard)
+ console.log('width', this.data.imgOriginWidth)
+ console.log('height', this.data.imgOriginHeight)
+ this.session.detectIDCard({
+ // 识别身份证图片的信息
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.imgOriginWidth,
+ height: this.data.imgOriginHeight,
+ // 是否获取裁剪图片信息
+ getAffineImg: true,
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/behavior.js
index 64ab7c3f..a7b5af80 100644
--- a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/behavior.js
@@ -1,228 +1,227 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.textContentList) this.textContentList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ OCR: {
+ mode: 2
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ console.log('anchor add')
+ })
+ session.on('updateAnchors', anchors => {
+ this.data.textContentList = []
+ console.log(anchors)
+ this.data.textContentList = this.data.textContentList.concat(anchors.map(anchor => {
+ let result = {}
+ result = {
+ text: anchor.text,
+ subtext: anchor.subtext,
+ box: anchor.box,
+ centerX: anchor.centerX,
+ centerY: anchor.centerY,
+ }
+ if (anchor.box) {
+ const lt = anchor.box[0]
+ const lr = anchor.box[1]
+ const rb = anchor.box[2]
+ const lb = anchor.box[3]
+ const width = lr.x - lt.x
+ const height = lb.y - lt.y
+ const avgX = (lt.x + lr.x + rb.x + lb.x) / 4
+ const avgY = (lt.y + lr.y + rb.y + lb.y) / 4
+ anchor.centerX = avgX * this.data.faceImgWidth
+ anchor.centerY = avgY * this.data.faceImgHeight
+ result.origin = {
+ x: lt.x,
+ y: lt.y,
}
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
+ result.size = {
+ width,
+ height,
}
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.textContentList) this.textContentList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- OCR: {
- mode: 2
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- console.log("anchor add")
- })
- session.on('updateAnchors', anchors => {
- this.data.textContentList = []
- console.log(anchors)
- this.data.textContentList = this.data.textContentList.concat(anchors.map(anchor => {
- let result = {}
- result = {
- text: anchor.text,
- subtext: anchor.subtext,
- box: anchor.box,
- centerX: anchor.centerX,
- centerY: anchor.centerY,
- }
- if(anchor.box){
- let lt = anchor.box[0]
- let lr = anchor.box[1]
- let rb = anchor.box[2]
- let lb = anchor.box[3]
- let width = lr.x - lt.x
- let height = lb.y - lt.y
- let avgX = (lt.x + lr.x + rb.x + lb.x) / 4;
- let avgY = (lt.y + lr.y + rb.y + lb.y) / 4;
- anchor.centerX = avgX * this.data.faceImgWidth;
- anchor.centerY = avgY * this.data.faceImgHeight;
- result.origin = {
- x: lt.x,
- y: lt.y,
- }
- result.size = {
- width: width,
- height: height,
- }
- }
- return result
- }))
-
- var wholeText = undefined
- if(this.data.textContentList.length != 0){
- wholeText = this.data.textContentList[0].text
- }
-
- this.setData({
- textContentList: this.data.textContentList,
- wholeText: wholeText
- })
- })
- session.on('removeAnchors', anchors => {
- console.log("anchor remove")
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ }
+ return result
+ }))
+
+ let wholeText
+ if (this.data.textContentList.length != 0) {
+ wholeText = this.data.textContentList[0].text
+ }
+
+ this.setData({
+ textContentList: this.data.textContentList,
+ wholeText
+ })
+ })
+ session.on('removeAnchors', anchors => {
+ console.log('anchor remove')
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/photo-ocr-detect.js b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/photo-ocr-detect.js
index 8752d63c..568b636f 100644
--- a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/photo-ocr-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/photo-ocr-detect.js
@@ -5,127 +5,126 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- faceImgUrl: '',
- faceImgWidth: 0,
- faceImgHeight: 0,
- faceImgOriginWidth: 0,
- faceImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ faceImgUrl: '',
+ faceImgWidth: 0,
+ faceImgHeight: 0,
+ faceImgOriginWidth: 0,
+ faceImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- faceImgUrl: imgUrl,
- faceImgWidth: fixWidth,
- faceImgHeight: (fixWidth / width) * height,
- faceImgOriginWidth: width,
- faceImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- this.initGL()
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ faceImgUrl: imgUrl,
+ faceImgWidth: fixWidth,
+ faceImgHeight: (fixWidth / width) * height,
+ faceImgOriginWidth: width,
+ faceImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- render(frame) {
- return
- this.renderGL(frame)
+ fail: res => {
+ console.error(res)
+ }
+ })
+ },
+ init() {
+ this.initGL()
+ },
+ render(frame) {
+ return
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
- async runOCR() {
- if (this.data.faceImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.faceImgOriginWidth,
- height: this.data.faceImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.faceImgUrl
- })
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
+ },
+ async runOCR() {
+ if (this.data.faceImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.faceImgOriginWidth,
+ height: this.data.faceImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.faceImgUrl
+ })
- context.clearRect(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ context.clearRect(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.faceImgOriginWidth, this.data.faceImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.runOCR', this.session.runOCR)
- console.log('width', this.data.faceImgOriginWidth)
- console.log('height', this.data.faceImgOriginHeight)
- this.session.runOCR({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.faceImgOriginWidth,
- height: this.data.faceImgOriginHeight,
- })
- }
- },
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.runOCR', this.session.runOCR)
+ console.log('width', this.data.faceImgOriginWidth)
+ console.log('height', this.data.faceImgOriginHeight)
+ this.session.runOCR({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.faceImgOriginWidth,
+ height: this.data.faceImgOriginHeight,
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/photo-ocr-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-ocr-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/behavior.js b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/behavior.js
index 105eeddc..1cdfcde5 100644
--- a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/behavior.js
@@ -1,195 +1,194 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.textContentList) this.textContentList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- shoe: {
- mode: 2
- }
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- session.on('addAnchors', anchors => {
- console.log("anchor add")
- })
- session.on('updateAnchors', anchors => {
- console.log(anchors)
- this.data.anchor2DList = []
- // 手动传入图像的时候用dom画点和框就行
- this.setData({
- anchor2DList: anchors.map(anchor => ({
- points: anchor.points,
- origin: anchor.origin,
- size: anchor.size
- })),
- })
- })
- session.on('removeAnchors', anchors => {
- console.log("anchor remove")
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- },
- })
-}
\ No newline at end of file
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.textContentList) this.textContentList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ shoe: {
+ mode: 2
+ }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ session.on('addAnchors', anchors => {
+ console.log('anchor add')
+ })
+ session.on('updateAnchors', anchors => {
+ console.log(anchors)
+ this.data.anchor2DList = []
+ // 手动传入图像的时候用dom画点和框就行
+ this.setData({
+ anchor2DList: anchors.map(anchor => ({
+ points: anchor.points,
+ origin: anchor.origin,
+ size: anchor.size
+ })),
+ })
+ })
+ session.on('removeAnchors', anchors => {
+ console.log('anchor remove')
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/photo-shoe-detect.js b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/photo-shoe-detect.js
index e64687ad..8e7051c5 100644
--- a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/photo-shoe-detect.js
+++ b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/photo-shoe-detect.js
@@ -5,109 +5,108 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- shoeImgUrl: '',
- shoeImgWidth: 0,
- shoeImgHeight: 0,
- shoeImgOriginWidth: 0,
- shoeImgOriginHeight: 0,
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ shoeImgUrl: '',
+ shoeImgWidth: 0,
+ shoeImgHeight: 0,
+ shoeImgOriginWidth: 0,
+ shoeImgOriginHeight: 0,
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ chooseMedia() {
+ wx.chooseMedia({
+ count: 1,
+ mediaType: ['image'],
+ success: res => {
+ console.log('chooseMedia res', res)
+ const imgUrl = res.tempFiles[0].tempFilePath
+ wx.getImageInfo({
+ src: imgUrl,
+ success: res => {
+ const fixWidth = 300
+ const {
+ width,
+ height
+ } = res
+ console.log('getImageInfo res', res)
+ this.setData({
+ shoeImgUrl: imgUrl,
+ shoeImgWidth: fixWidth,
+ shoeImgHeight: (fixWidth / width) * height,
+ shoeImgOriginWidth: width,
+ shoeImgOriginHeight: height
+ })
+ },
+ fail: res => {
+ console.error(res)
+ }
})
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
},
+ fail: res => {
+ console.error(res)
+ }
+ })
},
- methods: {
- chooseMedia() {
- wx.chooseMedia({
- count: 1,
- mediaType: ['image'],
- success: res => {
- console.log('chooseMedia res', res)
- const imgUrl = res.tempFiles[0].tempFilePath
- wx.getImageInfo({
- src: imgUrl,
- success: res => {
- const fixWidth = 300
- const {
- width,
- height
- } = res
- console.log('getImageInfo res', res)
- this.setData({
- shoeImgUrl: imgUrl,
- shoeImgWidth: fixWidth,
- shoeImgHeight: (fixWidth / width) * height,
- shoeImgOriginWidth: width,
- shoeImgOriginHeight: height
- })
- },
- fail: res => {
- console.error(res)
- }
- })
+ init() {
+ this.initGL()
+ },
+ render(frame) {
- },
- fail: res => {
- console.error(res)
- }
- })
- },
- init() {
- this.initGL()
- },
- render(frame) {
- return
- },
- async detectShoe() {
- if (this.data.shoeImgUrl) {
- const canvas = wx.createOffscreenCanvas({
- type: '2d',
- width: this.data.shoeImgOriginWidth,
- height: this.data.shoeImgOriginHeight,
- })
- const context = canvas.getContext('2d')
- const img = canvas.createImage()
- await new Promise(resolve => {
- img.onload = resolve
- img.src = this.data.shoeImgUrl
- })
+ },
+ async detectShoe() {
+ if (this.data.shoeImgUrl) {
+ const canvas = wx.createOffscreenCanvas({
+ type: '2d',
+ width: this.data.shoeImgOriginWidth,
+ height: this.data.shoeImgOriginHeight,
+ })
+ const context = canvas.getContext('2d')
+ const img = canvas.createImage()
+ await new Promise(resolve => {
+ img.onload = resolve
+ img.src = this.data.shoeImgUrl
+ })
- context.clearRect(0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
- context.drawImage(img, 0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
+ context.clearRect(0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
+ context.drawImage(img, 0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
- this.imgData = context.getImageData(0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
+ this.imgData = context.getImageData(0, 0, this.data.shoeImgOriginWidth, this.data.shoeImgOriginHeight)
- console.log('[frameBuffer] --> ', this.imgData.data.buffer)
- console.log('this.session.detectShoe', this.session.detectShoe)
- console.log('width', this.data.shoeImgOriginWidth)
- console.log('height', this.data.shoeImgOriginHeight)
- this.session.detectShoe({
- frameBuffer: this.imgData.data.buffer,
- width: this.data.shoeImgOriginWidth,
- height: this.data.shoeImgOriginHeight,
- })
- }
- },
+ console.log('[frameBuffer] --> ', this.imgData.data.buffer)
+ console.log('this.session.detectShoe', this.session.detectShoe)
+ console.log('width', this.data.shoeImgOriginWidth)
+ console.log('height', this.data.shoeImgOriginHeight)
+ this.session.detectShoe({
+ frameBuffer: this.imgData.data.buffer,
+ width: this.data.shoeImgOriginWidth,
+ height: this.data.shoeImgOriginHeight,
+ })
+ }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/photo-shoe-detect/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/photo-shoe-detect/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/behavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/behavior.js
index ff5d3f1e..74994ab4 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/behavior.js
@@ -1,254 +1,253 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
import cloneGltf from '../loaders/gltf-clone'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
- const THREE = this.THREE
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- threeDof: true,
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- const loader = new THREE.GLTFLoader()
- loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
- this.model = {
- scene: gltf.scene,
- animations: gltf.animations,
- }
- })
-
- this.clock = new THREE.Clock()
-
- loader.load('https://dldir1.qq.com/weixin/miniprogram/reticle_4b6cc19698ca4a08b31fd3c95ce412ec.glb', gltf => {
- const reticle = this.reticle = gltf.scene
-
- reticle.visible = false
- this.scene.add(reticle)
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- updateAnimation() {
- const dt = this.clock.getDelta()
- if (this.mixers) this.mixers.forEach(mixer => mixer.update(dt))
- },
- copyRobot() {
- const THREE = this.THREE
- const {
- scene,
- animations
- } = cloneGltf(this.model, THREE)
- scene.scale.set(0.05, 0.05, 0.05)
-
- // 动画混合器
- const mixer = new THREE.AnimationMixer(scene)
- for (let i = 0; i < animations.length; i++) {
- const clip = animations[i]
- if (clip.name === 'Dance') {
- const action = mixer.clipAction(clip)
- action.play()
- }
- }
-
- this.mixers = this.mixers || []
- this.mixers.push(mixer)
-
- scene._mixer = mixer
- return scene
- },
- getRobot() {
- const THREE = this.THREE
-
- const model = new THREE.Object3D()
- model.add(this.copyRobot())
-
- this._insertModels = this._insertModels || []
- this._insertModels.push(model)
-
- if (this._insertModels.length > 5) {
- const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
- needRemove.forEach(item => {
- if (item._mixer) {
- const mixer = item._mixer
- this.mixers.splice(this.mixers.indexOf(mixer), 1)
- mixer.uncacheRoot(mixer.getRoot())
- }
- if (item.parent) item.parent.remove(item)
- })
- }
- return model
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+ const THREE = this.THREE
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onTouchEnd(evt) {
- if (this.scene && this.model && this.reticle) {
- const model = this.getRobot()
- model.position.copy(this.reticle.position)
- model.rotation.copy(this.reticle.rotation)
- this.scene.add(model)
- }
+ threeDof: true,
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ const loader = new THREE.GLTFLoader()
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
+ this.model = {
+ scene: gltf.scene,
+ animations: gltf.animations,
+ }
+ })
+
+ this.clock = new THREE.Clock()
+
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/reticle_4b6cc19698ca4a08b31fd3c95ce412ec.glb', gltf => {
+ const reticle = this.reticle = gltf.scene
+
+ reticle.visible = false
+ this.scene.add(reticle)
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ updateAnimation() {
+ const dt = this.clock.getDelta()
+ if (this.mixers) this.mixers.forEach(mixer => mixer.update(dt))
+ },
+ copyRobot() {
+ const THREE = this.THREE
+ const {
+ scene,
+ animations
+ } = cloneGltf(this.model, THREE)
+ scene.scale.set(0.05, 0.05, 0.05)
+
+ // 动画混合器
+ const mixer = new THREE.AnimationMixer(scene)
+ for (let i = 0; i < animations.length; i++) {
+ const clip = animations[i]
+ if (clip.name === 'Dance') {
+ const action = mixer.clipAction(clip)
+ action.play()
+ }
+ }
+
+ this.mixers = this.mixers || []
+ this.mixers.push(mixer)
+
+ scene._mixer = mixer
+ return scene
+ },
+ getRobot() {
+ const THREE = this.THREE
+
+ const model = new THREE.Object3D()
+ model.add(this.copyRobot())
+
+ this._insertModels = this._insertModels || []
+ this._insertModels.push(model)
+
+ if (this._insertModels.length > 5) {
+ const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
+ needRemove.forEach(item => {
+ if (item._mixer) {
+ const mixer = item._mixer
+ this.mixers.splice(this.mixers.indexOf(mixer), 1)
+ mixer.uncacheRoot(mixer.getRoot())
}
- },
- })
-}
\ No newline at end of file
+ if (item.parent) item.parent.remove(item)
+ })
+ }
+ return model
+ },
+ onTouchEnd(evt) {
+ if (this.scene && this.model && this.reticle) {
+ const model = this.getRobot()
+ model.position.copy(this.reticle.position)
+ model.rotation.copy(this.reticle.rotation)
+ this.scene.add(model)
+ }
+ }
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/plane-ar-3dof.js b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/plane-ar-3dof.js
index 8f17665e..baa31187 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/plane-ar-3dof.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/plane-ar-3dof.js
@@ -5,73 +5,73 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- this.renderGL(frame)
+ render(frame) {
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 修改光标位置
- const reticle = this.reticle
- if (reticle) {
- const hitTestRes = this.session.hitTest(0.5, 0.5)
- if (hitTestRes.length) {
- reticle.matrixAutoUpdate = false
- reticle.matrix.fromArray(hitTestRes[0].transform)
- reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
- reticle.visible = true
- } else {
- reticle.visible = false
- }
- }
+ // 修改光标位置
+ const reticle = this.reticle
+ if (reticle) {
+ const hitTestRes = this.session.hitTest(0.5, 0.5)
+ if (hitTestRes.length) {
+ reticle.matrixAutoUpdate = false
+ reticle.matrix.fromArray(hitTestRes[0].transform)
+ reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
+ reticle.visible = true
+ } else {
+ reticle.visible = false
+ }
+ }
- // 更新动画
- this.updateAnimation()
+ // 更新动画
+ this.updateAnimation()
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-3dof/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-3dof/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/behavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/behavior.js
index c61dc394..c3f72e94 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/behavior.js
@@ -19,7 +19,6 @@ export default function getBehavior() {
},
methods: {
onReady() {
-
wx.createSelectorQuery()
.select('#webgl')
.node()
@@ -111,12 +110,11 @@ export default function getBehavior() {
version: 'v2',
gl: this.gl,
})
- const session = this.session
+ const session = this.session
session.start(err => {
-
if (err) {
this.setData({
- errMsg:'VK error: ' + err
+ errMsg: 'VK error: ' + err
})
return console.error('VK error: ', err)
}
@@ -157,7 +155,6 @@ export default function getBehavior() {
this.planeBox.add(reticle)
})
-
// anchor 检测
const createPlane = size => {
const geometry = new THREE.PlaneGeometry(size.width, size.height)
@@ -185,21 +182,21 @@ export default function getBehavior() {
const size = anchor.size
let object
if (size) {
- // object = createPlane(size)
- this.planeBox.add(object)
+ // object = createPlane(size)
+ this.planeBox.add(object)
} else {
if (!this.model) {
console.warn('this.model 还没加载完成 !!!!!')
return
}
- object = new THREE.Object3D()
- const model = this.getRobot()
- model.rotateX(-Math.PI / 2)
- object.add(model)
- this.robotBox.add(object)
+ object = new THREE.Object3D()
+ const model = this.getRobot()
+ model.rotateX(-Math.PI / 2)
+ object.add(model)
+ this.robotBox.add(object)
}
- if(object){
+ if (object) {
object._id = anchor.id
object._size = size
updateMatrix(object, anchor.transform)
@@ -217,7 +214,7 @@ export default function getBehavior() {
const size = anchor.size
if (size && object._size && (size.width !== object._size.width || size.height !== object._size.height)) {
this.planeBox.remove(object)
- // object = createPlane(size)
+ // object = createPlane(size)
this.plane = object
this.planeBox.add(object)
}
@@ -240,29 +237,28 @@ export default function getBehavior() {
})
})
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
// 逐帧渲染
const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- try{
- this.render(frame)
- }catch(e){
- console.log(e)
- }
-
- }
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ try {
+ this.render(frame)
+ } catch (e) {
+ console.log(e)
+ }
}
- session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
}
session.requestAnimationFrame(onFrame)
})
@@ -351,11 +347,11 @@ export default function getBehavior() {
return model
},
onTouchEnd(evt) {
- if(this.reticle.visible){
- //0.05 -0.47 -0.14
+ if (this.reticle.visible) {
+ // 0.05 -0.47 -0.14
this.hitPosition = this.reticle.position.clone()
console.log(this.hitPosition)
-
+
const model = this.getRobot()
model.position.copy(this.hitPosition)
model.rotation.copy(this.reticle.rotation)
@@ -364,4 +360,4 @@ export default function getBehavior() {
}
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/depthBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/depthBehavior.js
index 31fcb46d..a18cdcad 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/depthBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/depthBehavior.js
@@ -2,9 +2,8 @@ const depthBehavior = Behavior({
methods: {
initDepthShader() {
const gl = this.gl = this.renderer.getContext()
- const ext = gl.getExtension("OES_texture_float");
- if (!ext)
- console.warn('OES_texture_float not support');
+ const ext = gl.getExtension('OES_texture_float')
+ if (!ext) console.warn('OES_texture_float not support')
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const vs = `
precision highp float;
@@ -27,7 +26,7 @@ const depthBehavior = Behavior({
gl_FragColor = vec4(depth_color.rgb, 1.0);
}
`
-
+
const vertShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertShader, vs)
gl.compileShader(vertShader)
@@ -89,32 +88,32 @@ const depthBehavior = Behavior({
const displayTransform = frame.getDisplayTransform()
// DepthBuffer
- const depthBufferRes = frame.getDepthBuffer();
- const depthBuffer = new Float32Array(depthBufferRes.DepthAddress);
+ const depthBufferRes = frame.getDepthBuffer()
+ const depthBuffer = new Float32Array(depthBufferRes.DepthAddress)
- const texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ const texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- const width = depthBufferRes.width;
- const height = depthBufferRes.height;
+ const width = depthBufferRes.width
+ const height = depthBufferRes.height
// const ext = gl.getExtension("OES_texture_float");
// if (ext) {
// gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.FLOAT, depthBuffer);
// } else {
// }
-
+
// 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
- const data = new Uint8Array(width * height * 4);
+ const data = new Uint8Array(width * height * 4)
for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i] = num;
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i] = num
}
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
@@ -137,9 +136,8 @@ const depthBehavior = Behavior({
gl.useProgram(currentProgram)
gl.activeTexture(currentActiveTexture)
this.ext.bindVertexArrayOES(currentVAO)
-
},
},
})
-export default depthBehavior
\ No newline at end of file
+export default depthBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/plane-ar-v2-depth.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/plane-ar-v2-depth.js
index daf74576..c28dbb50 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/plane-ar-v2-depth.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/plane-ar-v2-depth.js
@@ -5,11 +5,11 @@ import depthBehavior from './depthBehavior'
const NEAR = 0.1
const FAR = 100
let cubeVao = null
-let countNumber = 20
+const countNumber = 20
let count = 0
let time = 0
-var CUBE_VSHADER_SOURCE =
+const CUBE_VSHADER_SOURCE =
`
#version 300 es
in vec3 aPosition;
@@ -23,7 +23,7 @@ var CUBE_VSHADER_SOURCE =
}
`
-var CUBE_FSHADER_SOURCE =
+const CUBE_FSHADER_SOURCE =
`
#version 300 es
precision highp float;
@@ -34,12 +34,12 @@ var CUBE_FSHADER_SOURCE =
}
`
-function createCubeVAO(gl, program){
- const ext = gl.getExtension("OES_vertex_array_object");
+function createCubeVAO(gl, program) {
+ const ext = gl.getExtension('OES_vertex_array_object')
const vao = ext.createVertexArrayOES()
ext.bindVertexArrayOES(vao)
- var vertices = [
+ const vertices = [
-1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, -1.0,
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0,
1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0,
@@ -52,42 +52,41 @@ function createCubeVAO(gl, program){
1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0,
-1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0
- ];
- var vertexBuffer = gl.createBuffer();
- gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
- var aPosition = gl.getAttribLocation(program, 'aPosition');
- gl.enableVertexAttribArray(aPosition);
- gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0);
+ ]
+ const vertexBuffer = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW)
+ const aPosition = gl.getAttribLocation(program, 'aPosition')
+ gl.enableVertexAttribArray(aPosition)
+ gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0)
vao.posBuffer = vertexBuffer
return vao
}
function onDrawCube(gl, program, hitPosition, vm, pm) {
- const ext = gl.getExtension("OES_vertex_array_object");
+ const ext = gl.getExtension('OES_vertex_array_object')
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
const bindingTexture = gl.getParameter(gl.TEXTURE_BINDING_2D)
- if(!cubeVao){
+ if (!cubeVao) {
cubeVao = createCubeVAO(gl, program)
- }else{
+ } else {
ext.bindVertexArrayOES(cubeVao)
}
gl.useProgram(program)
- var basePos = gl.getUniformLocation(program, 'basePosition');
- gl.uniform3fv(basePos, [hitPosition.x, hitPosition.y, hitPosition.z]);
+ const basePos = gl.getUniformLocation(program, 'basePosition')
+ gl.uniform3fv(basePos, [hitPosition.x, hitPosition.y, hitPosition.z])
- var viewLoc = gl.getUniformLocation(program, 'viewMatrix')
+ const viewLoc = gl.getUniformLocation(program, 'viewMatrix')
gl.uniformMatrix4fv(viewLoc, false, vm)
- var projLoc = gl.getUniformLocation(program, 'projMatrix')
+ const projLoc = gl.getUniformLocation(program, 'projMatrix')
gl.uniformMatrix4fv(projLoc, false, pm)
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 36);
-
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 36)
gl.useProgram(currentProgram)
ext.bindVertexArrayOES(currentVAO)
@@ -95,9 +94,6 @@ function onDrawCube(gl, program, hitPosition, vm, pm) {
gl.bindTexture(gl.TEXTURE_2D, bindingTexture)
}
-
-
-
Component({
behaviors: [getBehavior(), yuvBehavior, depthBehavior],
data: {
@@ -108,15 +104,15 @@ Component({
* 生命周期函数--监听页面加载
*/
detached() {
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
+ console.log('页面准备完全')
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -136,7 +132,6 @@ Component({
this.initDepthGL()
},
render(frame) {
-
this.session.setDepthOccRange(NEAR, FAR)
const start = Date.now()
@@ -182,7 +177,6 @@ Component({
gl.depthFunc(gl.LESS)
this.renderer.render(this.scene, this.camera)
-
// if (!this.cubeProgram) {
// this.cubeProgram = this.compileShader(gl, CUBE_VSHADER_SOURCE, CUBE_FSHADER_SOURCE)
// }
@@ -204,4 +198,4 @@ Component({
}
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/yuvBehavior.js
index a375fc22..4da93380 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-depth/yuvBehavior.js
@@ -21,12 +21,11 @@ const yuvBehavior = Behavior({
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- const info = gl.getProgramInfoLog(program);
+ const info = gl.getProgramInfoLog(program)
console.log(info)
- throw new Error(`Could not compile WebGL program. \n\n${info}`);
+ throw new Error(`Could not compile WebGL program. \n\n${info}`)
}
-
gl.useProgram(program)
return program
@@ -105,7 +104,7 @@ const yuvBehavior = Behavior({
// FragColor = vec4(depth_color.rgb, 1.0);
}
`
-
+
const depthOutputProgram = this._depthOutputProgram = this.compileShader(gl, dvs, dfs)
const uniformDepthTexture = gl.getUniformLocation(depthOutputProgram, 'depth_texture')
gl.uniform1i(uniformDepthTexture, 5)
@@ -114,52 +113,57 @@ const yuvBehavior = Behavior({
gl.useProgram(currentProgram)
},
buildPlane(
- vertices, indices,
- width, height,
- widthSegments, heightSegments
+ vertices,
+ indices,
+ width,
+ height,
+ widthSegments,
+ heightSegments
) {
- const width_half = width / 2;
- const height_half = height / 2;
-
- const gridX = Math.floor( widthSegments );
- const gridY = Math.floor( heightSegments );
-
- const gridX1 = gridX + 1;
- const gridY1 = gridY + 1;
-
- const segment_width = width / gridX;
- const segment_height = height / gridY;
-
- for ( let iy = 0; iy < gridY1; iy ++ ) {
- const y = iy * segment_height - height_half;
-
- for ( let ix = 0; ix < gridX1; ix ++ ) {
- const x = ix * segment_width - width_half;
-
- vertices.push(
- // a_position
- x, -y, 0,
- // a_texCoord
- ix / gridX, 1 - ( iy / gridY )
- );
+ const width_half = width / 2
+ const height_half = height / 2
+
+ const gridX = Math.floor(widthSegments)
+ const gridY = Math.floor(heightSegments)
+
+ const gridX1 = gridX + 1
+ const gridY1 = gridY + 1
+
+ const segment_width = width / gridX
+ const segment_height = height / gridY
+
+ for (let iy = 0; iy < gridY1; iy++) {
+ const y = iy * segment_height - height_half
+
+ for (let ix = 0; ix < gridX1; ix++) {
+ const x = ix * segment_width - width_half
+
+ vertices.push(
+ // a_position
+ x,
+ -y,
+ 0,
+ // a_texCoord
+ ix / gridX,
+ 1 - (iy / gridY)
+ )
}
}
- for ( let iy = 0; iy < gridY; iy ++ ) {
- for ( let ix = 0; ix < gridX; ix ++ ) {
- const a = ix + gridX1 * iy;
- const b = ix + gridX1 * ( iy + 1 );
- const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
- const d = ( ix + 1 ) + gridX1 * iy;
- indices.push( a, b, d );
- indices.push( b, c, d );
+ for (let iy = 0; iy < gridY; iy++) {
+ for (let ix = 0; ix < gridX; ix++) {
+ const a = ix + gridX1 * iy
+ const b = ix + gridX1 * (iy + 1)
+ const c = (ix + 1) + gridX1 * (iy + 1)
+ const d = (ix + 1) + gridX1 * iy
+ indices.push(a, b, d)
+ indices.push(b, c, d)
}
}
},
initVAO(program) {
const gl = this.renderer.getContext()
const ext = gl.getExtension('OES_vertex_array_object')
- if (!this.ext)
- this.ext = ext
+ if (!this.ext) this.ext = ext
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
const vao = ext.createVertexArrayOES()
@@ -189,7 +193,7 @@ const yuvBehavior = Behavior({
const gl = this.renderer.getContext()
const ext = gl.getExtension('OES_vertex_array_object')
- if (!this.ext){
+ if (!this.ext) {
this.ext = ext
}
@@ -201,8 +205,7 @@ const yuvBehavior = Behavior({
const vertices = []
const indices = []
- this.buildPlane(vertices, indices, 1, 1, width, height);
-
+ this.buildPlane(vertices, indices, 1, 1, width, height)
const posAttr = gl.getAttribLocation(program, 'a_position')
const pos = gl.createBuffer()
@@ -232,18 +235,18 @@ const yuvBehavior = Behavior({
const displayTransform = frame.getDisplayTransform()
// DepthBuffer
- const depthBufferRes = frame.getDepthBuffer();
- const depthBuffer = new Float32Array(depthBufferRes.DepthAddress);
+ const depthBufferRes = frame.getDepthBuffer()
+ const depthBuffer = new Float32Array(depthBufferRes.DepthAddress)
- const texture = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, texture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ const texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, texture)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- const width = depthBufferRes.width;
- const height = depthBufferRes.height;
+ const width = depthBufferRes.width
+ const height = depthBufferRes.height
// const ext = gl.getExtension("OES_texture_float");
// if (ext) {
@@ -252,24 +255,23 @@ const yuvBehavior = Behavior({
// }
// 先直接采用 uint8 写入深度纹理,使用浮点写入的方法会存在锯齿
- const data = new Uint8Array(width * height * 4);
+ const data = new Uint8Array(width * height * 4)
for (let i = 0; i < depthBuffer.length; i++) {
- let num = parseInt(depthBuffer[i] * 255);
- data[i] = num;
+ const num = parseInt(depthBuffer[i] * 255)
+ data[i] = num
}
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
const bindingTexture = gl.getParameter(gl.TEXTURE_BINDING_2D)
-
- if(!this._vao2){
- // this._vao2 = this.initDepthOutputVAO(this._depthOutputProgram, width, height)
- this._vao2 = this.initVAO(this._depthOutputProgram)
+ if (!this._vao2) {
+ // this._vao2 = this.initDepthOutputVAO(this._depthOutputProgram, width, height)
+ this._vao2 = this.initVAO(this._depthOutputProgram)
}
-
+
this.ext.bindVertexArrayOES(this._vao2)
gl.useProgram(this._depthOutputProgram)
@@ -289,7 +291,6 @@ const yuvBehavior = Behavior({
gl.bindTexture(gl.TEXTURE_2D, bindingTexture)
this.ext.bindVertexArrayOES(currentVAO)
-
},
renderGL(frame) {
const gl = this.renderer.getContext()
@@ -305,7 +306,6 @@ const yuvBehavior = Behavior({
const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
const bindingTexture = gl.getParameter(gl.TEXTURE_BINDING_2D)
-
gl.enable(gl.DEPTH_TEST)
gl.depthMask(true)
gl.depthFunc(gl.ALWAYS)
@@ -333,7 +333,6 @@ const yuvBehavior = Behavior({
gl.activeTexture(gl.TEXTURE0 + 5)
gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
gl.useProgram(currentProgram)
gl.activeTexture(currentActiveTexture)
gl.bindTexture(gl.TEXTURE_2D, bindingTexture)
@@ -344,4 +343,4 @@ const yuvBehavior = Behavior({
},
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/behavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/behavior.js
index 6627b04d..8ab8877a 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/behavior.js
@@ -7,7 +7,7 @@ import {
import cloneGltf from '../loaders/gltf-clone'
const info = wx.getSystemInfoSync()
- // 此处如果为jpeg,则后缀名也需要改成对应后缀
+// 此处如果为jpeg,则后缀名也需要改成对应后缀
// const filePath = `${wx.env.USER_DATA_PATH}/marker-ar1.jpg`
// const mapfilePath = `${wx.env.USER_DATA_PATH}/marker-ar.jpg`
@@ -43,7 +43,7 @@ export default function getBehavior() {
}
calcSize(info.windowWidth, info.windowHeight * 0.6)
- // this.downloadFile()
+ // this.downloadFile()
this.initVK()
})
@@ -112,40 +112,39 @@ export default function getBehavior() {
console.error(res)
}
})
-
},
fail: res => {
console.error(res)
}
})
},
- errImg(e){
- console.log("err img",e)
+ errImg(e) {
+ console.log('err img', e)
},
- loadImg(){
- console.log("load img")
+ loadImg() {
+ console.log('load img')
},
- add3DMarker(){
+ add3DMarker() {
const mapfilePath = `${wx.env.USER_DATA_PATH}/marker-ar1.map`
console.log('now download....')
const fs = wx.getFileSystemManager()
-
+
const download = callback => wx.downloadFile({
- // 此处设置为识别的2d对象的jpg地址
- url: 'http://dldir1.qq.com/weixin/checkresupdate/ncov_7bf1a739c43f4f80b3fb3488b592f355.map',
- success(res) {
- console.log("downloadFile success:", res)
- fs.saveFile({
- mapfilePath,
- tempFilePath: res.tempFilePath,
- success: callback,
- })
- },
- fail(e) {
- console.log("downloadFile fail:", e)
- }
+ // 此处设置为识别的2d对象的jpg地址
+ url: 'http://dldir1.qq.com/weixin/checkresupdate/ncov_7bf1a739c43f4f80b3fb3488b592f355.map',
+ success(res) {
+ console.log('downloadFile success:', res)
+ fs.saveFile({
+ mapfilePath,
+ tempFilePath: res.tempFilePath,
+ success: callback,
+ })
+ },
+ fail(e) {
+ console.log('downloadFile fail:', e)
+ }
})
const add = () => {
@@ -155,12 +154,12 @@ export default function getBehavior() {
path: mapfilePath,
success(res) {
// 文件存在
- console.log("文件存在")
+ console.log('文件存在')
console.log(res)
},
fail(res) {
// 文件不存在或其他错误
- console.log("文件不存在")
+ console.log('文件不存在')
console.error(res)
}
})
@@ -168,27 +167,27 @@ export default function getBehavior() {
}
download(add)
},
- add3DMarker2(){
+ add3DMarker2() {
const mapfilePath = `${wx.env.USER_DATA_PATH}/marker-ar.map`
console.log('now download....')
const fs = wx.getFileSystemManager()
-
+
const download = callback => wx.downloadFile({
- // 此处设置为识别的2d对象的jpg地址
- url: 'http://dldir1.qq.com/weixin/checkresupdate/ncov_7bf1a739c43f4f80b3fb3488b592f355.map',
- success(res) {
- console.log("downloadFile success:", res)
- fs.saveFile({
- mapfilePath,
- tempFilePath: res.tempFilePath,
- success: callback,
- })
- },
- fail(e) {
- console.log("downloadFile fail:", e)
- }
+ // 此处设置为识别的2d对象的jpg地址
+ url: 'http://dldir1.qq.com/weixin/checkresupdate/ncov_7bf1a739c43f4f80b3fb3488b592f355.map',
+ success(res) {
+ console.log('downloadFile success:', res)
+ fs.saveFile({
+ mapfilePath,
+ tempFilePath: res.tempFilePath,
+ success: callback,
+ })
+ },
+ fail(e) {
+ console.log('downloadFile fail:', e)
+ }
})
const add = () => {
@@ -202,8 +201,8 @@ export default function getBehavior() {
const fs = wx.getFileSystemManager()
// 此处如果为jpeg,则后缀名也需要改成对应后缀
// const filePath = `${wx.env.USER_DATA_PATH}/marker-ar.map`
- const filePath = `${wx.env.USER_DATA_PATH}/marker-ar`+this.data.markerId.length+`.jpeg`
-
+ const filePath = `${wx.env.USER_DATA_PATH}/marker-ar` + this.data.markerId.length + '.jpeg'
+
const download = callback => {
fs.saveFile({
filePath,
@@ -215,13 +214,13 @@ export default function getBehavior() {
})
}
const add = () => {
- console.log('[addMarker'+this.data.markerId.length+'] --> ', filePath)
- var id = this.session.addMarker(filePath)
+ console.log('[addMarker' + this.data.markerId.length + '] --> ', filePath)
+ const id = this.session.addMarker(filePath)
this.data.markerId.push(id)
this.data.imgList.push(filePath)
this.setData({
- markerId:this.data.markerId,
+ markerId: this.data.markerId,
imgList: this.data.imgList
})
}
@@ -229,9 +228,9 @@ export default function getBehavior() {
},
removeAllMarker() {
- if (this.data.markerId.length!=0) {
- for(let i = 0; i {
-
if (err) {
this.setData({
- errMsg:'VK error: ' + err
+ errMsg: 'VK error: ' + err
})
return console.error('VK error: ', err)
}
@@ -305,7 +302,7 @@ export default function getBehavior() {
animations: gltf.animations,
}
- console.log("model加载完成")
+ console.log('model加载完成')
})
this.clock = new THREE.Clock()
@@ -320,7 +317,7 @@ export default function getBehavior() {
this.setData({
showTip: true
})
- setTimeout(()=>{
+ setTimeout(() => {
this.setData({
showTip: false
})
@@ -346,25 +343,25 @@ export default function getBehavior() {
object.matrix.fromArray(m)
}
session.on('addAnchors', anchors => {
- console.log("add anchor")
+ console.log('add anchor')
anchors.forEach(anchor => {
- console.log("type: ", anchor.type)
+ console.log('type: ', anchor.type)
const size = anchor.size
let object
if (anchor.type == 0) {
- object = createPlane(size)
- this.setData({
- showTip: false
- })
+ object = createPlane(size)
+ this.setData({
+ showTip: false
+ })
} else {
if (!this.model) {
console.warn('this.model 还没加载完成 !!!!!')
return
}
- object = new THREE.Object3D()
- const model = this.getRobot()
- model.rotateX(-Math.PI / 2)
- object.add(model)
+ object = new THREE.Object3D()
+ const model = this.getRobot()
+ model.rotateX(-Math.PI / 2)
+ object.add(model)
}
object._id = anchor.id
@@ -374,7 +371,7 @@ export default function getBehavior() {
})
})
session.on('updateAnchors', anchors => {
- console.log("update")
+ console.log('update')
const map = anchors.reduce((temp, item) => {
temp[item.id] = item
console.log(item.id, item)
@@ -397,9 +394,9 @@ export default function getBehavior() {
})
})
session.on('removeAnchors', anchors => {
- console.log("remove anchor")
+ console.log('remove anchor')
const map = anchors.reduce((temp, item) => {
- console.log("type:", item.type)
+ console.log('type:', item.type)
temp[item.id] = item
return temp
}, {})
@@ -412,32 +409,32 @@ export default function getBehavior() {
const planeBox = this.planeBox = new THREE.Object3D()
this.scene.add(planeBox)
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
// 逐帧渲染
const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
}
- session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
}
session.requestAnimationFrame(onFrame)
})
},
- removeRobot(){
+ removeRobot() {
this.planeBox.children.forEach(object => {
- this.planeBox.remove(object)
- })
+ this.planeBox.remove(object)
+ })
},
initTHREE() {
const THREE = this.THREE = createScopedThreejs(this.canvas)
@@ -525,4 +522,4 @@ export default function getBehavior() {
}
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/plane-ar-v2-marker.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/plane-ar-v2-marker.js
index cac53daa..0808c873 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/plane-ar-v2-marker.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/plane-ar-v2-marker.js
@@ -4,90 +4,89 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-let time = 0;
-let countNumber = 20;
-let count = 0;
+let time = 0
+const countNumber = 20
+let count = 0
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- let start = Date.now()
+ render(frame) {
+ const start = Date.now()
- this.renderGL(frame)
- const camera = frame.camera
+ this.renderGL(frame)
+ const camera = frame.camera
- // 修改光标位置
- const reticle = this.reticle
- if (reticle) {
- const hitTestRes = this.session.hitTest(0.5, 0.5)
- if (hitTestRes.length) {
- reticle.matrixAutoUpdate = false
- reticle.matrix.fromArray(hitTestRes[0].transform)
- reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
- if(reticle.position.z !=0 )
- reticle.visible = true
- } else {
- reticle.visible = false
- }
- }
+ // 修改光标位置
+ const reticle = this.reticle
+ if (reticle) {
+ const hitTestRes = this.session.hitTest(0.5, 0.5)
+ if (hitTestRes.length) {
+ reticle.matrixAutoUpdate = false
+ reticle.matrix.fromArray(hitTestRes[0].transform)
+ reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
+ if (reticle.position.z != 0) reticle.visible = true
+ } else {
+ reticle.visible = false
+ }
+ }
- // 更新动画
- this.updateAnimation()
+ // 更新动画
+ this.updateAnimation()
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- let end = Date.now()
+ const end = Date.now()
- time += end-start
- count++
- // if(count >= countNumber){
- // console.log(`${count}次平均耗时统计为${time/count}ms`)
- // count = 0
- // time = 0
- // }
- },
+ time += end - start
+ count++
+ // if(count >= countNumber){
+ // console.log(`${count}次平均耗时统计为${time/count}ms`)
+ // count = 0
+ // time = 0
+ // }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-marker/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2-options/plane-ar-v2-options.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2-options/plane-ar-v2-options.js
index ba4608c1..92528fe2 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2-options/plane-ar-v2-options.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2-options/plane-ar-v2-options.js
@@ -9,37 +9,37 @@ Component({
behaviors: [arBehavior, threeBehavior],
data: {
theme: 'light',
- widthScale: 1, // canvas宽度缩放值
- heightScale: 0.6, // canvas高度缩放值
- markerImgList: [], // 使用的 marker 列表
+ widthScale: 1, // canvas宽度缩放值
+ heightScale: 0.6, // canvas高度缩放值
+ markerImgList: [], // 使用的 marker 列表
chooseImgList: [], // 使用的 图片 列表
},
- markerIndex: 0, // 使用的 marker 索引
+ markerIndex: 0, // 使用的 marker 索引
showBoxList: [], // 提示盒子列表,
hintCenter: null, // 红色提示点
useDepthBuffer: false, // 开启深度buffer
lifetimes: {
- /**
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
+ detached() {
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
},
methods: {
@@ -47,7 +47,7 @@ Component({
init() {
// 初始化 Three.js,用于模型相关的渲染
this.initTHREE()
- this.initDepthGL();
+ this.initDepthGL()
this.loader.load('https://dldir1.qq.com/weixin/miniprogram/reticle_4b6cc19698ca4a08b31fd3c95ce412ec.glb', gltf => {
const reticle = this.hintCenter = gltf.scene
@@ -61,13 +61,11 @@ Component({
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
-
- this.markerIndex = 0;
- this.showBoxList = [];
- this.useDepthBuffer = false;
-
+ this.initVK()
+ this.markerIndex = 0
+ this.showBoxList = []
+ this.useDepthBuffer = false
},
initVK() {
// VKSession 配置
@@ -80,7 +78,7 @@ Component({
},
version: 'v2',
gl: this.gl
- });
+ })
session.start(err => {
if (err) return console.error('VK error: ', err)
@@ -89,7 +87,7 @@ Component({
// VKSession EVENT resize
session.on('resize', () => {
- this.calcCanvasSize();
+ this.calcCanvasSize()
})
// VKSession EVENT addAnchors
@@ -101,34 +99,33 @@ Component({
id: anchor.id,
size: anchor.size,
transform: anchor.transform
- };
-
- switch(anchor.type) {
+ }
+
+ switch (anchor.type) {
case 0:
// plane Anchor
- const boxPlane = this.createBox(0xffffff, anchor.type);
- boxPlane.box.scale.set(showBox.size.width, 0.02, showBox.height);
- console.log('boxPlane.size', showBox.size);
-
- showBox.type = 'Plane';
- showBox.wrap = boxPlane.wrap;
- showBox.box = boxPlane.box;
- break;
+ const boxPlane = this.createBox(0xffffff, anchor.type)
+ boxPlane.box.scale.set(showBox.size.width, 0.02, showBox.height)
+ console.log('boxPlane.size', showBox.size)
+
+ showBox.type = 'Plane'
+ showBox.wrap = boxPlane.wrap
+ showBox.box = boxPlane.box
+ break
case 1:
// marker Anchor
- const boxMarker = this.createBox(0x55cc55, anchor.type);
- boxMarker.box.scale.set(1, 0.1, 1);
- console.log('boxMarker.size', showBox.size);
-
-
- showBox.type = 'Marker';
- showBox.wrap = boxMarker.wrap;
- showBox.box = boxMarker.box;
- break;
+ const boxMarker = this.createBox(0x55cc55, anchor.type)
+ boxMarker.box.scale.set(1, 0.1, 1)
+ console.log('boxMarker.size', showBox.size)
+
+ showBox.type = 'Marker'
+ showBox.wrap = boxMarker.wrap
+ showBox.box = boxMarker.box
+ break
}
-
- this.showBoxList.push(showBox);
- });
+
+ this.showBoxList.push(showBox)
+ })
console.log('this.showBoxList', this.showBoxList)
})
@@ -140,26 +137,26 @@ Component({
// 仅更新已经添加的Anchor
this.showBoxList.forEach(showBox => {
- for(let i = 0; i < anchors.length; i++) {
+ for (let i = 0; i < anchors.length; i++) {
if (showBox.id === anchors[i].id) {
// 匹配
if (showBox.size !== anchors[i].size) {
- switch(showBox.type) {
+ switch (showBox.type) {
case 'Plane':
- showBox.box.scale.set(anchors[i].size.width, 0.02, anchors[i].size.height);
- break;
+ showBox.box.scale.set(anchors[i].size.width, 0.02, anchors[i].size.height)
+ break
case 'Marker':
- break;
+ break
}
}
- showBox.size = anchors[i].size;
- showBox.transform = anchors[i].transform;
- break;
+ showBox.size = anchors[i].size
+ showBox.transform = anchors[i].transform
+ break
}
}
- });
+ })
})
-
+
// VKSession removeAnchors
// 识别目标丢失时,会触发一次
session.on('removeAnchors', anchors => {
@@ -168,33 +165,30 @@ Component({
// 存在要删除的 Anchor
if (anchors.length > 0) {
this.showBoxList = this.showBoxList.filter((showBox) => {
- let flag = true;
- for(let i = 0; i < anchors.length; i++) {
+ let flag = true
+ for (let i = 0; i < anchors.length; i++) {
if (showBox.id === anchors[i].id) {
console.log('remove', showBox.id)
- let scene = this.scene;
- if (showBox.type === "Marker") {
- scene = this.sceneCull;
+ let scene = this.scene
+ if (showBox.type === 'Marker') {
+ scene = this.sceneCull
}
// 从three里面去掉
- scene.remove(showBox.wrap);
+ scene.remove(showBox.wrap)
// 标记删除
- flag = false;
- break;
+ flag = false
+ break
}
}
- return flag;
-
+ return flag
})
}
- });
-
+ })
console.log('ready to initloop')
// start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
-
+ this.initLoop()
+ })
},
loop() {
// console.log('loop')
@@ -203,7 +197,7 @@ Component({
const frame = this.session.getVKFrame(this.canvas.width, this.canvas.height)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新相机 YUV 数据
this.renderYUV(frame)
@@ -217,8 +211,8 @@ Component({
this.camera.matrixAutoUpdate = false
// 视图矩阵
- this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix);
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse);
+ this.camera.matrixWorldInverse.fromArray(VKCamera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
// 投影矩阵
const projectionMatrix = VKCamera.getProjectionMatrix(NEAR, FAR)
@@ -229,11 +223,11 @@ Component({
// 更新提示盒子 位置
if (this.showBoxList) {
this.showBoxList.forEach(showBox => {
- showBox.wrap.matrix.fromArray(showBox.transform);
- });
+ showBox.wrap.matrix.fromArray(showBox.transform)
+ })
}
- const reticle = this.hintCenter;
+ const reticle = this.hintCenter
if (reticle) {
const hitTestRes = this.session.hitTest(0.5, 0.5)
if (hitTestRes.length) {
@@ -257,39 +251,39 @@ Component({
if (this.useDepthBuffer) {
// 1. 在左下角绘制深度提示
// 2. 写入深度遮挡纹理到深度值
- this.renderDepthGL(frame);
+ this.renderDepthGL(frame)
}
// 绘制进行深度遮挡的物体
this.renderer.render(this.sceneCull, this.camera)
this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
createBox(color, type) {
- const THREE = this.THREE;
- let scene = this.scene;
+ const THREE = this.THREE
+ let scene = this.scene
- let material;
+ let material
// 根据类型添加不一样的行为
- switch(type) {
+ switch (type) {
case 0:
// plane Anchor
material = new THREE.MeshBasicMaterial({
metalness: 0.0,
roughness: 0.1,
- color: color,
+ color,
transparent: true,
opacity: 0.8
- } );
- break;
+ })
+ break
case 1:
// marker Anchor
const uniforms = {
time: { value: Math.random() * 100 }
- };
-
+ }
+
material = new THREE.ShaderMaterial({
- uniforms: uniforms,
+ uniforms,
vertexShader: `
varying vec2 vUv;
void main() {
@@ -327,33 +321,33 @@ Component({
f = ( sin( a * g ) + 1.0 ) / 2.0;
gl_FragColor = vec4( vec3( f * i / 1.6, i / 2.0 + d / 13.0, i ) * d * p.x + vec3( i / 1.3 + d / 8.0, i / 2.0 + d / 18.0, i ) * d * ( 1.0 - p.x ), 1.0 );
}`,
- });
+ })
+
+ scene = this.sceneCull
- scene = this.sceneCull;
-
- break;
+ break
}
- const geometry = new THREE.BoxGeometry( 1, 1, 1 );
+ const geometry = new THREE.BoxGeometry(1, 1, 1)
- const wrap = new THREE.Object3D();
+ const wrap = new THREE.Object3D()
// 禁止矩阵自动更新,只能手动写入信息
- wrap.matrixAutoUpdate = false;
+ wrap.matrixAutoUpdate = false
// 绘制区域的box
- const box = new THREE.Mesh( geometry, material );
- wrap.add(box);
+ const box = new THREE.Mesh(geometry, material)
+ wrap.add(box)
- scene.add( wrap );
+ scene.add(wrap)
- box.visible = true;
+ box.visible = true
return {
- wrap: wrap,
- box: box,
- };
+ wrap,
+ box,
+ }
},
- chooseMedia() {
+ chooseMedia() {
// marker图片上传逻辑
wx.chooseMedia({
count: 9,
@@ -362,10 +356,10 @@ Component({
success: res => {
console.log('chooseMedia res', res)
- const chooseImgListRes = [];
+ const chooseImgListRes = []
for (let i = 0; i < res.tempFiles.length; i++) {
- const imgUrl = res.tempFiles[i].tempFilePath;
- chooseImgListRes.push(imgUrl);
+ const imgUrl = res.tempFiles[i].tempFilePath
+ chooseImgListRes.push(imgUrl)
}
console.log('set chooseImgList', chooseImgListRes)
@@ -381,88 +375,87 @@ Component({
async addMarker() {
console.log('addMarker')
const fs = wx.getFileSystemManager()
-
- const markerImgListRes = this.data.markerImgList.concat([]);
- const preMarkerIndex = this.markerIndex;
- console.log('pre markerImgList', preMarkerIndex, markerImgListRes);
-
+ const markerImgListRes = this.data.markerImgList.concat([])
+ const preMarkerIndex = this.markerIndex
+
+ console.log('pre markerImgList', preMarkerIndex, markerImgListRes)
+
// 检查与添加 marker 函数
- const chooseImgCount = this.data.chooseImgList.length;
- let handledCount = 0;
+ const chooseImgCount = this.data.chooseImgList.length
+ let handledCount = 0
const checkMarkerAdded = () => {
if (handledCount === chooseImgCount) {
- this.markerIndex = markerImgListRes.length;
+ this.markerIndex = markerImgListRes.length
- console.log('markerImgList set', markerImgListRes, this.markerIndex);
+ console.log('markerImgList set', markerImgListRes, this.markerIndex)
this.setData({
chooseImgList: [],
markerImgList: markerImgListRes
- });
+ })
}
}
-
+
// 准备进行choose的图片保存到fs
for (let i = 0; i < chooseImgCount; i++) {
- const chooseImgUrl = this.data.chooseImgList[i];
- const fileEnd = chooseImgUrl.split('.').slice(-1)[0];
- const fileIndex = preMarkerIndex + i;
+ const chooseImgUrl = this.data.chooseImgList[i]
+ const fileEnd = chooseImgUrl.split('.').slice(-1)[0]
+ const fileIndex = preMarkerIndex + i
// 算法侧目前只认 map png jpg jpeg 后缀文件
- const filePath = `${wx.env.USER_DATA_PATH}/marker-ar-${fileIndex}.${fileEnd}`;
+ const filePath = `${wx.env.USER_DATA_PATH}/marker-ar-${fileIndex}.${fileEnd}`
const saveAndAddMarker = () => {
- console.log('saveFileSync start', filePath, chooseImgUrl);
+ console.log('saveFileSync start', filePath, chooseImgUrl)
// 存入文件系统,并添加到marker
fs.saveFile({
filePath,
tempFilePath: chooseImgUrl,
- success: ()=> {
+ success: () => {
console.log('[addMarker] --> ', filePath)
const markerId = this.session.addMarker(filePath)
markerImgListRes.push({
- markerId: markerId,
- filePath: filePath
+ markerId,
+ filePath
})
- handledCount++;
- checkMarkerAdded();
+ handledCount++
+ checkMarkerAdded()
},
fail: res => {
console.error(res)
- console.log('文件保存失败', filePath);
- handledCount++;
- checkMarkerAdded();
+ console.log('文件保存失败', filePath)
+ handledCount++
+ checkMarkerAdded()
}
})
}
- console.log('uploadFile Path', filePath);
+ console.log('uploadFile Path', filePath)
// 确定文件,存在即删除
fs.stat({
path: filePath,
success: (res) => {
if (res.stats.isFile()) {
- fs.unlinkSync(filePath);
- console.log('fs unlinkSync', filePath);
+ fs.unlinkSync(filePath)
+ console.log('fs unlinkSync', filePath)
}
- saveAndAddMarker();
+ saveAndAddMarker()
},
fail: (res) => {
console.error(res)
- console.log('fs中不存在,直接写入', filePath);
+ console.log('fs中不存在,直接写入', filePath)
- saveAndAddMarker();
+ saveAndAddMarker()
}
})
}
-
},
removeMarker() {
if (this.data.markerImgList) {
for (let i = 0; i < this.data.markerImgList.length; i++) {
- const markerImg = this.data.markerImgList[i];
- this.session.removeMarker(markerImg.markerId);
+ const markerImg = this.data.markerImgList[i]
+ this.session.removeMarker(markerImg.markerId)
}
- this.markerIndex = 0;
+ this.markerIndex = 0
this.setData({
markerImgList: [],
})
@@ -470,42 +463,40 @@ Component({
},
placeItem() {
if (this.hintCenter && this.hintCenter.visible) {
- const THREE = this.THREE;
- const scene = this.sceneCull;
+ const THREE = this.THREE
+ const scene = this.sceneCull
// 加载模型
this.loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
- const wrap = new THREE.Object3D();
+ const wrap = new THREE.Object3D()
- wrap.add(gltf.scene);
-
- scene.add( wrap );
+ wrap.add(gltf.scene)
- const position = new THREE.Vector3();
- const rotation = new THREE.Quaternion();
- const scale = new THREE.Vector3();
- this.hintCenter.matrix.decompose(position, rotation, scale);
- wrap.position.set(position.x, position.y, position.z);
- wrap.rotation.set(rotation.x, rotation.y, rotation.z, rotation.w);
- wrap.scale.set(0.1, 0.1, 0.1);
+ scene.add(wrap)
- console.log("model加载完成")
+ const position = new THREE.Vector3()
+ const rotation = new THREE.Quaternion()
+ const scale = new THREE.Vector3()
+ this.hintCenter.matrix.decompose(position, rotation, scale)
+ wrap.position.set(position.x, position.y, position.z)
+ wrap.rotation.set(rotation.x, rotation.y, rotation.z, rotation.w)
+ wrap.scale.set(0.1, 0.1, 0.1)
- console.log('position', position.x, position.y, position.z);
+ console.log('model加载完成')
+
+ console.log('position', position.x, position.y, position.z)
// console.log('rotation', rotation.x, rotation.y, rotation.z, rotation.w);
// boxPlace.box.matrix.FromMatrix4(this.hintCenter.matrix);
})
-
-
}
},
changeDepthFlag() {
- const depthNear = 0.1;
- const depthFar = 20;
+ const depthNear = 0.1
+ const depthFar = 20
this.session.setDepthOccRange(depthNear, depthFar)
- this.useDepthBuffer = !this.useDepthBuffer;
- this.session.setDepthSwitch(this.useDepthBuffer);
+ this.useDepthBuffer = !this.useDepthBuffer
+ this.session.setDepthSwitch(this.useDepthBuffer)
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2/behavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2/behavior.js
index 54375034..d28996f6 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2/behavior.js
@@ -102,12 +102,11 @@ export default function getBehavior() {
version: 'v2',
gl: this.gl,
})
- const session = this.session
+ const session = this.session
session.start(err => {
-
if (err) {
this.setData({
- errMsg:'VK error: ' + err
+ errMsg: 'VK error: ' + err
})
return console.error('VK error: ', err)
}
@@ -151,7 +150,7 @@ export default function getBehavior() {
this.setData({
showTip: true
})
- setTimeout(()=>{
+ setTimeout(() => {
this.setData({
showTip: false
})
@@ -181,19 +180,19 @@ export default function getBehavior() {
const size = anchor.size
let object
if (anchor.type == 0) {
- object = createPlane(size)
- this.setData({
- showTip: false
- })
+ object = createPlane(size)
+ this.setData({
+ showTip: false
+ })
} else {
if (!this.model) {
console.warn('this.model 还没加载完成 !!!!!')
return
}
- object = new THREE.Object3D()
- const model = this.getRobot()
- model.rotateX(-Math.PI / 2)
- object.add(model)
+ object = new THREE.Object3D()
+ const model = this.getRobot()
+ model.rotateX(-Math.PI / 2)
+ object.add(model)
}
object._id = anchor.id
@@ -207,8 +206,8 @@ export default function getBehavior() {
temp[item.id] = item
return temp
}, {})
- const deletePlaneBoxs = [];
- const newPlaneBoxs = [];
+ const deletePlaneBoxs = []
+ const newPlaneBoxs = []
this.planeBox.children.forEach(object => {
if (object._id && map[object._id]) {
const anchor = map[object._id]
@@ -218,13 +217,13 @@ export default function getBehavior() {
// object = createPlane(size)
// this.planeBox.add(object)
// 塞入删除队列
- deletePlaneBoxs.push(object);
- const newPlane = createPlane(size);
+ deletePlaneBoxs.push(object)
+ const newPlane = createPlane(size)
newPlane._id = anchor.id
newPlane._size = size
updateMatrix(newPlane, anchor.transform)
// 塞入添加队列
- newPlaneBoxs.push(newPlane);
+ newPlaneBoxs.push(newPlane)
} else {
object._id = anchor.id
object._size = size
@@ -233,12 +232,12 @@ export default function getBehavior() {
}
})
// 延后删除
- for(let i = 0; i < deletePlaneBoxs.length; i++) {
+ for (let i = 0; i < deletePlaneBoxs.length; i++) {
this.planeBox.remove(deletePlaneBoxs[i])
}
// 延后添加
- for(let i = 0; i < newPlaneBoxs.length; i++) {
- this.planeBox.add(newPlaneBoxs[i]);
+ for (let i = 0; i < newPlaneBoxs.length; i++) {
+ this.planeBox.add(newPlaneBoxs[i])
}
})
session.on('removeAnchors', anchors => {
@@ -246,16 +245,16 @@ export default function getBehavior() {
temp[item.id] = item
return temp
}, {})
- const deletePlaneBoxs = [];
+ const deletePlaneBoxs = []
this.planeBox.children.forEach(object => {
if (object._id && map[object._id]) {
// this.planeBox.remove(object)
// 塞入删除队列
- deletePlaneBoxs.push(object);
+ deletePlaneBoxs.push(object)
}
})
// 延后删除
- for(let i = 0; i < deletePlaneBoxs.length; i++) {
+ for (let i = 0; i < deletePlaneBoxs.length; i++) {
this.planeBox.remove(deletePlaneBoxs[i])
}
})
@@ -264,24 +263,24 @@ export default function getBehavior() {
const planeBox = this.planeBox = new THREE.Object3D()
this.scene.add(planeBox)
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
let last = Date.now()
// 逐帧渲染
const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
}
- session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
}
session.requestAnimationFrame(onFrame)
})
@@ -312,38 +311,38 @@ export default function getBehavior() {
renderer.gammaOutput = true
renderer.gammaFactor = 2.2
- const geometry = new THREE.BoxGeometry( 1, 1, 1 );
+ const geometry = new THREE.BoxGeometry(1, 1, 1)
- const scale = 0.1;
- const m1 = new THREE.MeshPhysicalMaterial( {
+ const scale = 0.1
+ const m1 = new THREE.MeshPhysicalMaterial({
metalness: 0.0,
roughness: 0.1,
color: 0xff0000,
- } );
- const x = new THREE.Mesh( geometry, m1 );
- x.position.set(1.5 * scale, 0, 0 );
- x.scale.set(3 * scale, 0.1 * scale, 0.1 * scale);
- scene.add( x );
+ })
+ const x = new THREE.Mesh(geometry, m1)
+ x.position.set(1.5 * scale, 0, 0)
+ x.scale.set(3 * scale, 0.1 * scale, 0.1 * scale)
+ scene.add(x)
- const m2 = new THREE.MeshPhysicalMaterial( {
+ const m2 = new THREE.MeshPhysicalMaterial({
metalness: 0.0,
roughness: 0.1,
color: 0x00ff00,
- } );
- const y = new THREE.Mesh( geometry, m2 );
- y.position.set(0, 1.5 * scale, 0 );
- y.scale.set(0.1 * scale, 3 * scale, 0.1 * scale);
- scene.add( y );
+ })
+ const y = new THREE.Mesh(geometry, m2)
+ y.position.set(0, 1.5 * scale, 0)
+ y.scale.set(0.1 * scale, 3 * scale, 0.1 * scale)
+ scene.add(y)
- const m3 = new THREE.MeshPhysicalMaterial( {
+ const m3 = new THREE.MeshPhysicalMaterial({
metalness: 0.0,
roughness: 0.1,
color: 0x0000ff,
- } );
- const z = new THREE.Mesh( geometry, m3 );
- z.position.set(0, 0, 1.5 * scale );
- z.scale.set(0.1 * scale, 0.1 * scale, 3 * scale);
- scene.add( z );
+ })
+ const z = new THREE.Mesh(geometry, m3)
+ z.position.set(0, 0, 1.5 * scale)
+ z.scale.set(0.1 * scale, 0.1 * scale, 3 * scale)
+ scene.add(z)
},
updateAnimation() {
const dt = this.clock.getDelta()
@@ -405,4 +404,4 @@ export default function getBehavior() {
}
},
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2/plane-ar-v2.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2/plane-ar-v2.js
index cac53daa..0808c873 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2/plane-ar-v2.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2/plane-ar-v2.js
@@ -4,90 +4,89 @@ import yuvBehavior from './yuvBehavior'
const NEAR = 0.001
const FAR = 1000
-let time = 0;
-let countNumber = 20;
-let count = 0;
+let time = 0
+const countNumber = 20
+let count = 0
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- let start = Date.now()
+ render(frame) {
+ const start = Date.now()
- this.renderGL(frame)
- const camera = frame.camera
+ this.renderGL(frame)
+ const camera = frame.camera
- // 修改光标位置
- const reticle = this.reticle
- if (reticle) {
- const hitTestRes = this.session.hitTest(0.5, 0.5)
- if (hitTestRes.length) {
- reticle.matrixAutoUpdate = false
- reticle.matrix.fromArray(hitTestRes[0].transform)
- reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
- if(reticle.position.z !=0 )
- reticle.visible = true
- } else {
- reticle.visible = false
- }
- }
+ // 修改光标位置
+ const reticle = this.reticle
+ if (reticle) {
+ const hitTestRes = this.session.hitTest(0.5, 0.5)
+ if (hitTestRes.length) {
+ reticle.matrixAutoUpdate = false
+ reticle.matrix.fromArray(hitTestRes[0].transform)
+ reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
+ if (reticle.position.z != 0) reticle.visible = true
+ } else {
+ reticle.visible = false
+ }
+ }
- // 更新动画
- this.updateAnimation()
+ // 更新动画
+ this.updateAnimation()
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- let end = Date.now()
+ const end = Date.now()
- time += end-start
- count++
- // if(count >= countNumber){
- // console.log(`${count}次平均耗时统计为${time/count}ms`)
- // count = 0
- // time = 0
- // }
- },
+ time += end - start
+ count++
+ // if(count >= countNumber){
+ // console.log(`${count}次平均耗时统计为${time/count}ms`)
+ // count = 0
+ // time = 0
+ // }
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar-v2/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar-v2/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar-v2/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar-v2/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar/behavior.js b/miniprogram/packageAPI/pages/ar/plane-ar/behavior.js
index 6225f46c..9cabf6a9 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar/behavior.js
@@ -1,253 +1,252 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
import cloneGltf from '../loaders/gltf-clone'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
- const THREE = this.THREE
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- const loader = new THREE.GLTFLoader()
- loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
- this.model = {
- scene: gltf.scene,
- animations: gltf.animations,
- }
- })
-
- this.clock = new THREE.Clock()
-
- loader.load('https://dldir1.qq.com/weixin/miniprogram/reticle_4b6cc19698ca4a08b31fd3c95ce412ec.glb', gltf => {
- const reticle = this.reticle = gltf.scene
-
- reticle.visible = false
- this.scene.add(reticle)
- })
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
- updateAnimation() {
- const dt = this.clock.getDelta()
- if (this.mixers) this.mixers.forEach(mixer => mixer.update(dt))
- },
- copyRobot() {
- const THREE = this.THREE
- const {
- scene,
- animations
- } = cloneGltf(this.model, THREE)
- scene.scale.set(0.05, 0.05, 0.05)
-
- // 动画混合器
- const mixer = new THREE.AnimationMixer(scene)
- for (let i = 0; i < animations.length; i++) {
- const clip = animations[i]
- if (clip.name === 'Dance') {
- const action = mixer.clipAction(clip)
- action.play()
- }
- }
-
- this.mixers = this.mixers || []
- this.mixers.push(mixer)
-
- scene._mixer = mixer
- return scene
- },
- getRobot() {
- const THREE = this.THREE
-
- const model = new THREE.Object3D()
- model.add(this.copyRobot())
-
- this._insertModels = this._insertModels || []
- this._insertModels.push(model)
-
- if (this._insertModels.length > 5) {
- const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
- needRemove.forEach(item => {
- if (item._mixer) {
- const mixer = item._mixer
- this.mixers.splice(this.mixers.indexOf(mixer), 1)
- mixer.uncacheRoot(mixer.getRoot())
- }
- if (item.parent) item.parent.remove(item)
- })
- }
- return model
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+ const THREE = this.THREE
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onTouchEnd(evt) {
- if (this.scene && this.model && this.reticle) {
- const model = this.getRobot()
- model.position.copy(this.reticle.position)
- model.rotation.copy(this.reticle.rotation)
- this.scene.add(model)
- }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ const loader = new THREE.GLTFLoader()
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
+ this.model = {
+ scene: gltf.scene,
+ animations: gltf.animations,
+ }
+ })
+
+ this.clock = new THREE.Clock()
+
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/reticle_4b6cc19698ca4a08b31fd3c95ce412ec.glb', gltf => {
+ const reticle = this.reticle = gltf.scene
+
+ reticle.visible = false
+ this.scene.add(reticle)
+ })
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+ updateAnimation() {
+ const dt = this.clock.getDelta()
+ if (this.mixers) this.mixers.forEach(mixer => mixer.update(dt))
+ },
+ copyRobot() {
+ const THREE = this.THREE
+ const {
+ scene,
+ animations
+ } = cloneGltf(this.model, THREE)
+ scene.scale.set(0.05, 0.05, 0.05)
+
+ // 动画混合器
+ const mixer = new THREE.AnimationMixer(scene)
+ for (let i = 0; i < animations.length; i++) {
+ const clip = animations[i]
+ if (clip.name === 'Dance') {
+ const action = mixer.clipAction(clip)
+ action.play()
+ }
+ }
+
+ this.mixers = this.mixers || []
+ this.mixers.push(mixer)
+
+ scene._mixer = mixer
+ return scene
+ },
+ getRobot() {
+ const THREE = this.THREE
+
+ const model = new THREE.Object3D()
+ model.add(this.copyRobot())
+
+ this._insertModels = this._insertModels || []
+ this._insertModels.push(model)
+
+ if (this._insertModels.length > 5) {
+ const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
+ needRemove.forEach(item => {
+ if (item._mixer) {
+ const mixer = item._mixer
+ this.mixers.splice(this.mixers.indexOf(mixer), 1)
+ mixer.uncacheRoot(mixer.getRoot())
}
- },
- })
-}
\ No newline at end of file
+ if (item.parent) item.parent.remove(item)
+ })
+ }
+ return model
+ },
+ onTouchEnd(evt) {
+ if (this.scene && this.model && this.reticle) {
+ const model = this.getRobot()
+ model.position.copy(this.reticle.position)
+ model.rotation.copy(this.reticle.rotation)
+ this.scene.add(model)
+ }
+ }
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar/plane-ar.js b/miniprogram/packageAPI/pages/ar/plane-ar/plane-ar.js
index 8f17665e..baa31187 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar/plane-ar.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar/plane-ar.js
@@ -5,73 +5,73 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- this.renderGL(frame)
+ render(frame) {
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- // 修改光标位置
- const reticle = this.reticle
- if (reticle) {
- const hitTestRes = this.session.hitTest(0.5, 0.5)
- if (hitTestRes.length) {
- reticle.matrixAutoUpdate = false
- reticle.matrix.fromArray(hitTestRes[0].transform)
- reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
- reticle.visible = true
- } else {
- reticle.visible = false
- }
- }
+ // 修改光标位置
+ const reticle = this.reticle
+ if (reticle) {
+ const hitTestRes = this.session.hitTest(0.5, 0.5)
+ if (hitTestRes.length) {
+ reticle.matrixAutoUpdate = false
+ reticle.matrix.fromArray(hitTestRes[0].transform)
+ reticle.matrix.decompose(reticle.position, reticle.quaternion, reticle.scale)
+ reticle.visible = true
+ } else {
+ reticle.visible = false
+ }
+ }
- // 更新动画
- this.updateAnimation()
+ // 更新动画
+ this.updateAnimation()
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/plane-ar/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/plane-ar/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/plane-ar/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/plane-ar/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/shoe-detect/shoe-detect.js b/miniprogram/packageAPI/pages/ar/shoe-detect/shoe-detect.js
index dfecff86..f0586668 100644
--- a/miniprogram/packageAPI/pages/ar/shoe-detect/shoe-detect.js
+++ b/miniprogram/packageAPI/pages/ar/shoe-detect/shoe-detect.js
@@ -5,7 +5,7 @@ import xrFrameBehavior from '../behavior/behavior-xrframe'
const NEAR = 0.01
const FAR = 1000
-let loggerOnce = false;
+const loggerOnce = false
Component({
behaviors: [arBehavior, xrFrameBehavior],
@@ -24,14 +24,14 @@ Component({
* 生命周期函数--监听页面加载
*/
detached() {
- console.log("页面detached")
+ console.log('页面detached')
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
ready() {
- console.log("页面准备完全")
- const systemInfo = wx.getSystemInfoSync();
+ console.log('页面准备完全')
+ const systemInfo = wx.getSystemInfoSync()
this.setData({
theme: systemInfo.theme || 'light',
isIOS: systemInfo.platform === 'ios',
@@ -53,295 +53,289 @@ Component({
init() {
// 初始化VK
// start完毕后,进行更新渲染循环
- this.initVK();
+ this.initVK()
},
initVK() {
// VKSession 配置
const session = this.session = wx.createVKSession({
- track: {
- shoe: {
- mode: 1
- }
- },
- cameraPosition: 0,
- version: 'v1',
- gl: this.gl
+ track: {
+ shoe: {
+ mode: 1
+ }
+ },
+ cameraPosition: 0,
+ version: 'v1',
+ gl: this.gl
})
- try{
-
+ try {
// VKSession start
- session.start(err => {
- if (err) return console.error('VK error: ', err)
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
- console.log('@@@@@@@@ VKSession.version', session.version)
+ console.log('@@@@@@@@ VKSession.version', session.version)
- if (!this.data.showLegMask) {
+ if (!this.data.showLegMask) {
// 初始化设定
- this.session.updateMaskMode({useMask: false});
- }
+ this.session.updateMaskMode({ useMask: false })
+ }
- // VKSession EVENT resize
- session.on('resize', () => {
- this.calcCanvasSize();
- })
+ // VKSession EVENT resize
+ session.on('resize', () => {
+ this.calcCanvasSize()
+ })
- // VKSession EVENT addAnchors
- session.on('addAnchors', anchors => {
+ // VKSession EVENT addAnchors
+ session.on('addAnchors', anchors => {
// console.log("addAnchor", anchors)
- })
+ })
- // VKSession EVENT updateAnchors
- session.on('updateAnchors', anchors => {
+ // VKSession EVENT updateAnchors
+ session.on('updateAnchors', anchors => {
// console.log("updateAnchors")
- if (anchors.length === 1) {
+ if (anchors.length === 1) {
// 只有一双的情况下,可以做一个简单的显示性检测,进行非 remove 事件下的隐藏
- const anchorSingle = anchors[0];
- const shoedirecSingle = anchorSingle.shoedirec;
+ const anchorSingle = anchors[0]
+ const shoedirecSingle = anchorSingle.shoedirec
- if (shoedirecSingle === 0) {
+ if (shoedirecSingle === 0) {
// 只有左脚,此时尝试隐藏右脚
- if (this.modelShowRight && this.modelTrsRight) {
+ if (this.modelShowRight && this.modelTrsRight) {
// 右脚
- this.scaleTrs(this.modelTrsRight, 0, 0, 0);
- this.updateHintBoxVisible(this.hintBoxListRight, false);
- this.modelShowRight = false;
- }
- } else if (shoedirecSingle === 1) {
+ this.scaleTrs(this.modelTrsRight, 0, 0, 0)
+ this.updateHintBoxVisible(this.hintBoxListRight, false)
+ this.modelShowRight = false
+ }
+ } else if (shoedirecSingle === 1) {
// 只有右脚,此时尝试隐藏左脚
- if (this.modelShowLeft && this.modelTrsLeft) {
+ if (this.modelShowLeft && this.modelTrsLeft) {
// 左脚
- this.scaleTrs(this.modelTrsLeft, 0, 0, 0);
- this.updateHintBoxVisible(this.hintBoxListLeft, false);
- this.modelShowLeft = false;
+ this.scaleTrs(this.modelTrsLeft, 0, 0, 0)
+ this.updateHintBoxVisible(this.hintBoxListLeft, false)
+ this.modelShowLeft = false
+ }
}
}
- }
-
- for (let i = 0; i < anchors.length; i++ ) {
- const anchor = anchors[i];
- // console.log('transform', anchor.transform);
- // console.log('points3d', anchor.points3d);
- let modelScale = 1;
+ for (let i = 0; i < anchors.length; i++) {
+ const anchor = anchors[i]
+ // console.log('transform', anchor.transform);
+ // console.log('points3d', anchor.points3d);
+ const modelScale = 1
- if (anchor.shoedirec === 0) {
+ if (anchor.shoedirec === 0) {
// 左脚
- this.shoeTransformLeft = anchor.transform;
- this.points3dLeft = anchor.points3d;
+ this.shoeTransformLeft = anchor.transform
+ this.points3dLeft = anchor.points3d
- if (!this.modelShowLeft && this.modelTrsLeft) {
- this.scaleTrs(this.modelTrsLeft, modelScale, modelScale, modelScale);
- this.updateHintBoxVisible(this.hintBoxListLeft, true);
- this.modelShowLeft = true;
- }
- } else if (anchor.shoedirec === 1) {
+ if (!this.modelShowLeft && this.modelTrsLeft) {
+ this.scaleTrs(this.modelTrsLeft, modelScale, modelScale, modelScale)
+ this.updateHintBoxVisible(this.hintBoxListLeft, true)
+ this.modelShowLeft = true
+ }
+ } else if (anchor.shoedirec === 1) {
// 右脚
- this.shoeTransformRight = anchor.transform;
- this.points3dRight = anchor.points3d;
+ this.shoeTransformRight = anchor.transform
+ this.points3dRight = anchor.points3d
- if (!this.modelShowRight && this.modelTrsRight) {
- this.scaleTrs(this.modelTrsRight, modelScale, modelScale, modelScale);
- this.updateHintBoxVisible(this.hintBoxListRight, true);
- this.modelShowRight = true;
+ if (!this.modelShowRight && this.modelTrsRight) {
+ this.scaleTrs(this.modelTrsRight, modelScale, modelScale, modelScale)
+ this.updateHintBoxVisible(this.hintBoxListRight, true)
+ this.modelShowRight = true
+ }
}
}
+ })
- }
-
- })
-
- // VKSession removeAnchors
- // 识别目标丢失时,会不断触发
- session.on('removeAnchors', anchors => {
+ // VKSession removeAnchors
+ // 识别目标丢失时,会不断触发
+ session.on('removeAnchors', anchors => {
// console.log("removeAnchors")
- // Hide
- if (this.modelShowLeft && this.modelTrsLeft) {
+ // Hide
+ if (this.modelShowLeft && this.modelTrsLeft) {
// 左脚
- this.scaleTrs(this.modelTrsLeft, 0);
- this.updateHintBoxVisible(this.hintBoxListLeft, false);
- this.modelShowLeft = false;
- }
- if (this.modelShowRight && this.modelTrsRight) {
+ this.scaleTrs(this.modelTrsLeft, 0)
+ this.updateHintBoxVisible(this.hintBoxListLeft, false)
+ this.modelShowLeft = false
+ }
+ if (this.modelShowRight && this.modelTrsRight) {
// 右脚
- this.scaleTrs(this.modelTrsRight, 0);
- this.updateHintBoxVisible(this.hintBoxListRight, false);
- this.modelShowRight = false;
- }
- })
-
- console.log('ready to initloop')
- // start 初始化完毕后,进行更新渲染循环
- this.initLoop();
- });
+ this.scaleTrs(this.modelTrsRight, 0)
+ this.updateHintBoxVisible(this.hintBoxListRight, false)
+ this.modelShowRight = false
+ }
+ })
- } catch(e) {
- console.error(e);
+ console.log('ready to initloop')
+ // start 初始化完毕后,进行更新渲染循环
+ this.initLoop()
+ })
+ } catch (e) {
+ console.error(e)
}
},
// 针对 xr-frame 的初始化逻辑
async initXRFrame() {
- const xrFrameSystem = wx.getXrFrameSystem();
- const scene = this.xrScene;
- const {rootShadow} = scene;
-
+ const xrFrameSystem = wx.getXrFrameSystem()
+ const scene = this.xrScene
+ const { rootShadow } = scene
+
// 缓存主相机
this.xrCameraMain = this.xrCamera
- this.xrCameraMainTrs = this.xrCameraTrs;
+ this.xrCameraMainTrs = this.xrCameraTrs
// 试鞋案例,使用rt相机作为xrCamera
- const xrCameraEl = scene.getElementById('rtCamera');
- this.xrCamera = xrCameraEl.getComponent(xrFrameSystem.Camera);
- this.xrCameraTrs = xrCameraEl.getComponent(xrFrameSystem.Transform);
-
+ const xrCameraEl = scene.getElementById('rtCamera')
+ this.xrCamera = xrCameraEl.getComponent(xrFrameSystem.Camera)
+ this.xrCameraTrs = xrCameraEl.getComponent(xrFrameSystem.Transform)
+
// 初始化YUV相机配置
- this.initXRYUVCamera();
+ this.initXRYUVCamera()
// 初始化ShoeMask平面,会用绘制RT中物体
- this.addShoeMaskPlane();
+ this.addShoeMaskPlane()
// 左右鞋子分别处理
- const shoeFrontFix = 0.2; // 额外前移,适配鞋后
- const shoeBottomFix = -0.4; // 额外下移,适配鞋底
+ const shoeFrontFix = 0.2 // 额外前移,适配鞋后
+ const shoeBottomFix = -0.4 // 额外下移,适配鞋底
// const shoeFrontFix = 0;
// const shoeBottomFix = 0;
- const shoeScaleFactorX = 1.1; // 针对窄鞋缩放,优化效果
+ const shoeScaleFactorX = 1.1 // 针对窄鞋缩放,优化效果
// 模型缩放
- let modelScale = 220;
+ let modelScale = 220
// 针对 3.2.1 版本基础库,iOS 试鞋,返回的投影矩阵,进行的兼容修复
if (!this.data.isIOS) {
- modelScale *= 1.2;
+ modelScale *= 1.2
}
// 遮挡模型
- const occGeometry = scene.assets.getAsset('geometry', 'cylinder');
- const occEffect = scene.assets.getAsset('effect', 'standard');
+ const occGeometry = scene.assets.getAsset('geometry', 'cylinder')
+ const occEffect = scene.assets.getAsset('effect', 'standard')
// === 左边鞋子流程 ===
// 初始化挂载点
- this.modelWrapLeft = scene.createElement(xrFrameSystem.XRNode);
- this.modelWrapTrsLeft = this.modelWrapLeft.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( this.modelWrapLeft );
+ this.modelWrapLeft = scene.createElement(xrFrameSystem.XRNode)
+ this.modelWrapTrsLeft = this.modelWrapLeft.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(this.modelWrapLeft)
- console.log('modelWrapLeft ready');
+ console.log('modelWrapLeft ready')
// 点挂载
const modelPointLeft = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
- scale: "0 0 0",
- });
- this.modelTrsLeft = modelPointLeft.getComponent(xrFrameSystem.Transform);
- this.modelShowLeft = false;
- this.modelWrapLeft.addChild(modelPointLeft);
+ position: '0 0 0',
+ scale: '0 0 0',
+ })
+ this.modelTrsLeft = modelPointLeft.getComponent(xrFrameSystem.Transform)
+ this.modelShowLeft = false
+ this.modelWrapLeft.addChild(modelPointLeft)
// 加载鞋子模型
const shoeModelLeft = await scene.assets.loadAsset({
type: 'gltf',
- assetId: `gltf-shoe-left`,
+ assetId: 'gltf-shoe-left',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/shoe-1-left.glb',
})
- console.log('shoeModelLeft', shoeModelLeft.value);
+ console.log('shoeModelLeft', shoeModelLeft.value)
const elLeft = scene.createElement(xrFrameSystem.XRGLTF, {
- model: "gltf-shoe-left",
+ model: 'gltf-shoe-left',
position: `0 ${shoeBottomFix} ${shoeFrontFix}`,
scale: `${modelScale * shoeScaleFactorX} ${modelScale} ${modelScale}`,
layer: 2
- });
- this.modelLeft = elLeft;
+ })
+ this.modelLeft = elLeft
// this.modelTrsLeft = elLeft.getComponent(xrFrameSystem.Transform);
// this.modelShowLeft = false;
// this.modelWrapLeft.addChild(elLeft);
- modelPointLeft.addChild(elLeft);
+ modelPointLeft.addChild(elLeft)
// 遮挡模型
const occlusionLeft = scene.createElement(xrFrameSystem.XRNode, {
- position: "0.1 3.5 -2.3",
- rotation: "-20 0 0",
- scale: "1.5 2 1.6",
+ position: '0.1 3.5 -2.3',
+ rotation: '-20 0 0',
+ scale: '1.5 2 1.6',
layer: 2
- });
- const occMatLeft = scene.createMaterial(occEffect);
+ })
+ const occMatLeft = scene.createMaterial(occEffect)
// 遮挡渲染状态
- occMatLeft.renderQueue = 1;
- occMatLeft.alphaMode = 'BLEND';
- occMatLeft.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, 1.0, 1.0, 0.0));
+ occMatLeft.renderQueue = 1
+ occMatLeft.alphaMode = 'BLEND'
+ occMatLeft.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, 1.0, 1.0, 0.0))
const occMeshLeft = occlusionLeft.addComponent(xrFrameSystem.Mesh, {
geometry: occGeometry,
material: occMatLeft,
- });
- modelPointLeft.addChild(occlusionLeft);
+ })
+ modelPointLeft.addChild(occlusionLeft)
// left done
- console.log('this.modelTrsLeft', this.modelTrsLeft);
- console.log('shoeModelLeft ready');
+ console.log('this.modelTrsLeft', this.modelTrsLeft)
+ console.log('shoeModelLeft ready')
// 加载提示点
- this.hintBoxListLeft = this.getHintBox(xrFrameSystem, scene, this.modelWrapLeft);
+ this.hintBoxListLeft = this.getHintBox(xrFrameSystem, scene, this.modelWrapLeft)
// === 右边鞋子流程 ===
// 初始化挂载点
- this.modelWrapRight = scene.createElement(xrFrameSystem.XRNode);
- this.modelWrapTrsRight = this.modelWrapRight.getComponent(xrFrameSystem.Transform);
- rootShadow.addChild( this.modelWrapRight );
+ this.modelWrapRight = scene.createElement(xrFrameSystem.XRNode)
+ this.modelWrapTrsRight = this.modelWrapRight.getComponent(xrFrameSystem.Transform)
+ rootShadow.addChild(this.modelWrapRight)
- console.log('modelWrapRight ready');
+ console.log('modelWrapRight ready')
// 点挂载
const modelPointRight = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
- scale: "0 0 0",
- });
- this.modelTrsRight = modelPointRight.getComponent(xrFrameSystem.Transform);
- this.modelShowRight = false;
- this.modelWrapRight.addChild(modelPointRight);
+ position: '0 0 0',
+ scale: '0 0 0',
+ })
+ this.modelTrsRight = modelPointRight.getComponent(xrFrameSystem.Transform)
+ this.modelShowRight = false
+ this.modelWrapRight.addChild(modelPointRight)
// 加载鞋子模型
const shoeModelRight = await scene.assets.loadAsset({
type: 'gltf',
- assetId: `gltf-shoe-right`,
+ assetId: 'gltf-shoe-right',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/demo/shoe-1-right.glb',
})
- console.log('shoeModelRight', shoeModelRight.value);
+ console.log('shoeModelRight', shoeModelRight.value)
const elRight = scene.createElement(xrFrameSystem.XRGLTF, {
- model: "gltf-shoe-right",
+ model: 'gltf-shoe-right',
position: `0 ${shoeBottomFix} ${shoeFrontFix}`,
scale: `${modelScale * shoeScaleFactorX} ${modelScale} ${modelScale}`,
layer: 2
- });
- this.modelRight = elRight;
+ })
+ this.modelRight = elRight
// this.modelTrsRight = elRight.getComponent(xrFrameSystem.Transform);
// this.modelShowRight = false;
// this.modelWrapRight.addChild(elRight);
- modelPointRight.addChild(elRight);
+ modelPointRight.addChild(elRight)
// 遮挡模型
const occlusionRight = scene.createElement(xrFrameSystem.XRNode, {
- position: "0.1 3.5 -2.3",
- rotation: "-20 0 0",
- scale: "1.5 2 1.6",
+ position: '0.1 3.5 -2.3',
+ rotation: '-20 0 0',
+ scale: '1.5 2 1.6',
layer: 2
- });
- const occMatRight = scene.createMaterial(occEffect);
+ })
+ const occMatRight = scene.createMaterial(occEffect)
// 遮挡渲染状态
- occMatRight.renderQueue = 1;
- occMatRight.alphaMode = 'BLEND';
- occMatRight.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, 1.0, 1.0, 0.0));
+ occMatRight.renderQueue = 1
+ occMatRight.alphaMode = 'BLEND'
+ occMatRight.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(1.0, 1.0, 1.0, 0.0))
const occMeshRight = occlusionRight.addComponent(xrFrameSystem.Mesh, {
geometry: occGeometry,
material: occMatRight,
- });
- modelPointRight.addChild(occlusionRight);
+ })
+ modelPointRight.addChild(occlusionRight)
// right done
- console.log('this.modelTrsRight', this.modelTrsRight);
- console.log('shoeModelRight ready');
+ console.log('this.modelTrsRight', this.modelTrsRight)
+ console.log('shoeModelRight ready')
// 加载提示点
- this.hintBoxListRight = this.getHintBox(xrFrameSystem, scene, this.modelWrapRight);
-
+ this.hintBoxListRight = this.getHintBox(xrFrameSystem, scene, this.modelWrapRight)
},
loop() {
// console.log('loop')
@@ -349,113 +343,111 @@ Component({
const frame = this.session.getVKFrame(this.data.domWidth, this.data.domHeight)
// 成功获取 VKFrame 才进行
- if(!frame) { return; }
+ if (!frame) { return }
// 更新腿部分割纹理
if (this.data.showLegMask) {
- this.updateShoeMask(frame)
+ this.updateShoeMask(frame)
// console.log(getLegSegmentBuffer);
}
// 更新相机 YUV 数据
- this.updataXRYUV(frame);
+ this.updataXRYUV(frame)
// 获取 VKCamera
const VKCamera = frame.camera
// 更新 xrFrame 相机矩阵
- this.updataXRCameraMatrix(VKCamera, NEAR, FAR);
-
+ this.updataXRCameraMatrix(VKCamera, NEAR, FAR)
+
// 存在model,更新矩阵
// 左边鞋子流程
if (this.modelWrapLeft && this.modelTrsLeft && this.points3dLeft && this.shoeTransformLeft) {
- const xrFrameSystem = wx.getXrFrameSystem();
+ const xrFrameSystem = wx.getXrFrameSystem()
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(this.shoeTransformLeft);
- this.DT.transpose(this.DT2);
- this.modelWrapTrsLeft.setLocalMatrix(this.DT2);
+ this.DT.setArray(this.shoeTransformLeft)
+ this.DT.transpose(this.DT2)
+ this.modelWrapTrsLeft.setLocalMatrix(this.DT2)
// 放置鞋子
- this.modelTrsLeft.position.x = (this.points3dLeft[3].x + this.points3dLeft[4].x ) / 2;
- this.modelTrsLeft.position.y = (this.points3dLeft[3].y + this.points3dLeft[4].y ) / 2;
- this.modelTrsLeft.position.z = (this.points3dLeft[0].z + this.points3dLeft[1].z ) / 2;
-
-
- this.updateHintBoxPosition(this.hintBoxListLeft, this.points3dLeft);
+ this.modelTrsLeft.position.x = (this.points3dLeft[3].x + this.points3dLeft[4].x) / 2
+ this.modelTrsLeft.position.y = (this.points3dLeft[3].y + this.points3dLeft[4].y) / 2
+ this.modelTrsLeft.position.z = (this.points3dLeft[0].z + this.points3dLeft[1].z) / 2
+ this.updateHintBoxPosition(this.hintBoxListLeft, this.points3dLeft)
}
// 右边鞋子流程
if (this.modelWrapRight && this.modelTrsRight && this.points3dRight && this.shoeTransformRight) {
- const xrFrameSystem = wx.getXrFrameSystem();
+ const xrFrameSystem = wx.getXrFrameSystem()
- if (!this.DT) { this.DT = new xrFrameSystem.Matrix4(); }
- if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4(); }
+ if (!this.DT) { this.DT = new xrFrameSystem.Matrix4() }
+ if (!this.DT2) { this.DT2 = new xrFrameSystem.Matrix4() }
// 目前VK返回的是行主序矩阵
// xrframe 矩阵存储为列主序
- this.DT.setArray(this.shoeTransformRight);
- this.DT.transpose(this.DT2);
- this.modelWrapTrsRight.setLocalMatrix(this.DT2);
+ this.DT.setArray(this.shoeTransformRight)
+ this.DT.transpose(this.DT2)
+ this.modelWrapTrsRight.setLocalMatrix(this.DT2)
// 放置鞋子
- this.modelTrsRight.position.x = (this.points3dRight[3].x + this.points3dRight[4].x ) / 2;
- this.modelTrsRight.position.y = (this.points3dRight[3].y + this.points3dRight[4].y ) / 2;
- this.modelTrsRight.position.z = (this.points3dRight[0].z + this.points3dRight[1].z ) / 2;
+ this.modelTrsRight.position.x = (this.points3dRight[3].x + this.points3dRight[4].x) / 2
+ this.modelTrsRight.position.y = (this.points3dRight[3].y + this.points3dRight[4].y) / 2
+ this.modelTrsRight.position.z = (this.points3dRight[0].z + this.points3dRight[1].z) / 2
- this.updateHintBoxPosition(this.hintBoxListRight, this.points3dRight);
+ this.updateHintBoxPosition(this.hintBoxListRight, this.points3dRight)
}
},
// 缩放 xr-frame TRS
scaleTrs(trs, scaleX, scaleY, scaleZ) {
- trs.scale.x = scaleX;
- trs.scale.y = scaleY;
- trs.scale.z = scaleZ;
+ trs.scale.x = scaleX
+ trs.scale.y = scaleY
+ trs.scale.z = scaleZ
},
getHintBox(xrFrameSystem, scene, wrap) {
// 初始化提示点
- const geometryCube = scene.assets.getAsset('geometry', 'cube');
- const effectCube = scene.assets.getAsset('effect', 'standard');
- const boxScale = 0.2;
- const hintBoxList = [];
+ const geometryCube = scene.assets.getAsset('geometry', 'cube')
+ const effectCube = scene.assets.getAsset('effect', 'standard')
+ const boxScale = 0.2
+ const hintBoxList = []
for (let i = 0; i < 8; i++) {
- const colorFloat = i / 16;
+ const colorFloat = i / 16
const el = scene.createElement(xrFrameSystem.XRNode, {
- position: "0 0 0",
+ position: '0 0 0',
scale: `${boxScale} ${boxScale} ${boxScale}`,
layer: 2
- });
- const elTrs = el.getComponent(xrFrameSystem.Transform);
- const mat = scene.createMaterial(effectCube);
- mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(colorFloat + 0.3, 0.2, 0.2, 1.0));
- mat.renderQueue = 9990;
- mat.setRenderState('depthTestOn', false);
+ })
+ const elTrs = el.getComponent(xrFrameSystem.Transform)
+ const mat = scene.createMaterial(effectCube)
+ mat.setVector('u_baseColorFactor', xrFrameSystem.Vector4.createFromNumber(colorFloat + 0.3, 0.2, 0.2, 1.0))
+ mat.renderQueue = 9990
+ mat.setRenderState('depthTestOn', false)
const mesh = el.addComponent(xrFrameSystem.Mesh, {
geometry: geometryCube,
material: mat,
- });
+ })
+
+ wrap.addChild(el)
+ elTrs.visible = false
- wrap.addChild( el );
- elTrs.visible = false;
-
- hintBoxList.push( elTrs );
+ hintBoxList.push(elTrs)
}
- return hintBoxList;
+ return hintBoxList
},
updateHintBoxVisible(hintBoxList, visible) {
if (hintBoxList && hintBoxList.length > 0) {
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
- const visibleFlag = this.data.showHintBox && visible;
+ const hintBox = hintBoxList[i]
+ const visibleFlag = this.data.showHintBox && visible
if (hintBox.visible !== visibleFlag) {
- hintBox.visible = visibleFlag;
+ hintBox.visible = visibleFlag
}
}
}
@@ -465,26 +457,25 @@ Component({
// console.log('ready to set', hintBoxList);
// 存在提示列表,则更新点信息
for (let i = 0; i < hintBoxList.length; i++) {
- const hintBox = hintBoxList[i];
- hintBox.position.x = points3d[i].x;
- hintBox.position.y = points3d[i].y;
- hintBox.position.z = points3d[i].z;
+ const hintBox = hintBoxList[i]
+ hintBox.position.x = points3d[i].x
+ hintBox.position.y = points3d[i].y
+ hintBox.position.z = points3d[i].z
}
}
},
addShoeMaskPlane() {
- const scene = this.xrScene;
- const {rootShadow} = scene;
+ const scene = this.xrScene
+ const { rootShadow } = scene
- const xrFrameSystem = wx.getXrFrameSystem();
-
+ const xrFrameSystem = wx.getXrFrameSystem()
const el = scene.createElement(xrFrameSystem.XRNode, {
layer: 1
- });
+ })
- const shoeMaskGeometry = scene.assets.getAsset('geometry', `ar-camera-plane`);
- let shoeMaskEffect = scene.assets.getAsset('effect', 'ar-shoe-mask');
+ const shoeMaskGeometry = scene.assets.getAsset('geometry', 'ar-camera-plane')
+ let shoeMaskEffect = scene.assets.getAsset('effect', 'ar-shoe-mask')
if (!shoeMaskEffect) {
xrFrameSystem.registerEffect('ar-shoe-mask', scene => scene.createEffect({
@@ -492,31 +483,31 @@ Component({
{ key: 'u_baseColorFactor', type: xrFrameSystem.EUniformType.FLOAT4, default: [1, 1, 1, 1] },
],
images: [
- {
- key: 'u_shoeMask',
- default: 'black',
- macro: 'WX_AR_SHOEMASk'
- },
- {
- key: 'u_renderTexture',
- default: 'black',
- macro: 'WX_AR_RENDERTEXTURE'
+ {
+ key: 'u_shoeMask',
+ default: 'black',
+ macro: 'WX_AR_SHOEMASk'
+ },
+ {
+ key: 'u_renderTexture',
+ default: 'black',
+ macro: 'WX_AR_RENDERTEXTURE'
},
],
- defaultRenderQueue: 2,
- passes: [{
- renderStates: {
- blendOn: true,
- depthWrite: false,
- // Default FrontFace is CW
- cullOn: true,
- cullFace: xrFrameSystem.ECullMode.BACK,
- },
- lightMode: 'ForwardBase',
- useMaterialRenderStates: true,
- shaders: [0, 1]
- }],
- shaders:
+ defaultRenderQueue: 2,
+ passes: [{
+ renderStates: {
+ blendOn: true,
+ depthWrite: false,
+ // Default FrontFace is CW
+ cullOn: true,
+ cullFace: xrFrameSystem.ECullMode.BACK,
+ },
+ lightMode: 'ForwardBase',
+ useMaterialRenderStates: true,
+ shaders: [0, 1]
+ }],
+ shaders:
[
`#version 100
attribute vec3 a_position;
@@ -565,44 +556,44 @@ Component({
`
]
}))
- shoeMaskEffect = scene.assets.getAsset('effect', 'ar-shoe-mask');
+ shoeMaskEffect = scene.assets.getAsset('effect', 'ar-shoe-mask')
}
- const shoeMaskMat = scene.createMaterial(shoeMaskEffect);
+ const shoeMaskMat = scene.createMaterial(shoeMaskEffect)
// 获取屏幕renderTexture
- this.renderTexture = scene.assets.getAsset('render-texture', 'rt');
- shoeMaskMat.setTexture('u_renderTexture', this.renderTexture.texture);
+ this.renderTexture = scene.assets.getAsset('render-texture', 'rt')
+ shoeMaskMat.setTexture('u_renderTexture', this.renderTexture.texture)
- shoeMaskMat.renderQueue = 2; // 第二个绘制
+ shoeMaskMat.renderQueue = 2 // 第二个绘制
const mesh = el.addComponent(xrFrameSystem.Mesh, {
geometry: shoeMaskGeometry,
material: shoeMaskMat
- });
+ })
// ShoeMask纹理
- this.shoeMaskMat = shoeMaskMat;
- this.shoeMaskMatInit = false;
+ this.shoeMaskMat = shoeMaskMat
+ this.shoeMaskMatInit = false
// 不进入正常的剔除
- rootShadow.addChild(el);
-
+ rootShadow.addChild(el)
},
updateShoeMask(frame) {
- const scene = this.xrScene;
- const xrFrameSystem = wx.getXrFrameSystem();
+ const scene = this.xrScene
+ const xrFrameSystem = wx.getXrFrameSystem()
// 腿部分割
- const legSegmentBuffer = frame.getLegSegmentBuffer();
+ const legSegmentBuffer = frame.getLegSegmentBuffer()
// 存在数据才进行rt初始化
if (legSegmentBuffer && legSegmentBuffer.width > 0 && legSegmentBuffer.height > 0) {
// 存在数据,开启宏
- this.shoeMaskMat.setMacro("WX_USE_SHOEMASK", true);
+ this.shoeMaskMat.setMacro('WX_USE_SHOEMASK', true)
- // 未创建贴图缓存,先创建
+ // 未创建贴图缓存,先创建
if (!this.shoeMaskTexure) {
this.shoeMaskTexure = scene.createTexture({
- width: legSegmentBuffer.width, height: legSegmentBuffer.height,
+ width: legSegmentBuffer.width,
+ height: legSegmentBuffer.height,
source: [legSegmentBuffer.MaskAddress],
magFilter: xrFrameSystem.EFilterMode.LINEAR,
minFilter: xrFrameSystem.EFilterMode.LINEAR,
@@ -610,56 +601,56 @@ Component({
})
}
- const shoeMaskMat = this.shoeMaskMat;
+ const shoeMaskMat = this.shoeMaskMat
// 未绑定贴图的情况下,绑定贴图
if (!this.shoeMaskMatInit) {
- shoeMaskMat.setTexture('u_shoeMask', this.shoeMaskTexure);
- this.shoeMaskMatInit = true;
+ shoeMaskMat.setTexture('u_shoeMask', this.shoeMaskTexure)
+ this.shoeMaskMatInit = true
}
- this.shoeMaskTexure.update({buffer: legSegmentBuffer.MaskAddress});
+ this.shoeMaskTexure.update({ buffer: legSegmentBuffer.MaskAddress })
} else {
console.error('getLegSegmentBuffer is empty', legSegmentBuffer, legSegmentBuffer.width, legSegmentBuffer.height)
}
},
// 点击腿Mask切换
onTapMask() {
- const maskFlag = !this.data.showLegMask;
+ const maskFlag = !this.data.showLegMask
if (this.session && this.session.updateMaskMode) {
// 开启关闭 shoeMask
- this.session.updateMaskMode({useMask: maskFlag});
+ this.session.updateMaskMode({ useMask: maskFlag })
if (!maskFlag) {
- this.shoeMaskMat.setMacro("WX_USE_SHOEMASK", false);
+ this.shoeMaskMat.setMacro('WX_USE_SHOEMASK', false)
}
this.setData({
showLegMask: maskFlag
})
} else {
- console.error("请初始化vk后,再点击切换按钮")
+ console.error('请初始化vk后,再点击切换按钮')
}
},
- // 点击提示点切换
- onTapHint() {
- const hintFlag = !this.data.showHintBox;
+ // 点击提示点切换
+ onTapHint() {
+ const hintFlag = !this.data.showHintBox
this.setData({
showHintBox: hintFlag
})
// nextTick 保证 setData
- setTimeout(()=>{
+ setTimeout(() => {
if (this.modelShowLeft && this.modelTrsLeft) {
// 左脚
- this.updateHintBoxVisible(this.hintBoxListLeft, hintFlag);
+ this.updateHintBoxVisible(this.hintBoxListLeft, hintFlag)
}
if (this.modelShowRight && this.modelTrsRight) {
// 右脚
- this.updateHintBoxVisible(this.hintBoxListRight, hintFlag);
+ this.updateHintBoxVisible(this.hintBoxListRight, hintFlag)
}
- }, 33);
+ }, 33)
},
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/behavior.js b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/behavior.js
index 5727b637..e2e3eb19 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/behavior.js
@@ -1,252 +1,252 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
import cloneGltf from '../loaders/gltf-clone'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
- const THREE = this.THREE
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 1
- },
- },
- version: 'v2',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- const loader = new THREE.GLTFLoader()
- loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
- this.model = {
- scene: gltf.scene,
- animations: gltf.animations,
- }
- })
-
- this.clock = new THREE.Clock()
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
-
- copyRobot() {
- const THREE = this.THREE
- const {
- scene,
- animations
- } = cloneGltf(this.model, THREE)
- scene.scale.set(0.05, 0.05, 0.05)
-
- // 动画混合器
- const mixer = new THREE.AnimationMixer(scene)
- for (let i = 0; i < animations.length; i++) {
- const clip = animations[i]
- if (clip.name === 'Dance') {
- const action = mixer.clipAction(clip)
- action.play()
- }
- }
-
- this.mixers = this.mixers || []
- this.mixers.push(mixer)
-
- scene._mixer = mixer
- return scene
- },
- getRobot() {
- const THREE = this.THREE
-
- const model = new THREE.Object3D()
- model.add(this.copyRobot())
-
- this._insertModels = this._insertModels || []
- this._insertModels.push(model)
-
- if (this._insertModels.length > 5) {
- const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
- needRemove.forEach(item => {
- if (item._mixer) {
- const mixer = item._mixer
- this.mixers.splice(this.mixers.indexOf(mixer), 1)
- mixer.uncacheRoot(mixer.getRoot())
- }
- if (item.parent) item.parent.remove(item)
- })
- }
-
- return model
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+ const THREE = this.THREE
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 1
},
- onTouchEnd(evt) {
- // 点击位置放一个机器人
- const touches = evt.changedTouches.length ? evt.changedTouches : evt.touches
- if (touches.length === 1) {
- const touch = touches[0]
- if (this.session && this.scene && this.model) {
- const hitTestRes = this.session.hitTest(touch.x / this.data.width, touch.y / this.data.height, this.resetPanel)
- this.resetPanel = false
- if (hitTestRes.length) {
- const model = this.getRobot()
- model.matrixAutoUpdate = false
- model.matrix.fromArray(hitTestRes[0].transform)
- this.scene.add(model)
- }
- }
- }
+ },
+ version: 'v2',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ const loader = new THREE.GLTFLoader()
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
+ this.model = {
+ scene: gltf.scene,
+ animations: gltf.animations,
+ }
+ })
+
+ this.clock = new THREE.Clock()
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+
+ copyRobot() {
+ const THREE = this.THREE
+ const {
+ scene,
+ animations
+ } = cloneGltf(this.model, THREE)
+ scene.scale.set(0.05, 0.05, 0.05)
+
+ // 动画混合器
+ const mixer = new THREE.AnimationMixer(scene)
+ for (let i = 0; i < animations.length; i++) {
+ const clip = animations[i]
+ if (clip.name === 'Dance') {
+ const action = mixer.clipAction(clip)
+ action.play()
+ }
+ }
+
+ this.mixers = this.mixers || []
+ this.mixers.push(mixer)
+
+ scene._mixer = mixer
+ return scene
+ },
+ getRobot() {
+ const THREE = this.THREE
+
+ const model = new THREE.Object3D()
+ model.add(this.copyRobot())
+
+ this._insertModels = this._insertModels || []
+ this._insertModels.push(model)
+
+ if (this._insertModels.length > 5) {
+ const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
+ needRemove.forEach(item => {
+ if (item._mixer) {
+ const mixer = item._mixer
+ this.mixers.splice(this.mixers.indexOf(mixer), 1)
+ mixer.uncacheRoot(mixer.getRoot())
+ }
+ if (item.parent) item.parent.remove(item)
+ })
+ }
+
+ return model
+ },
+ onTouchEnd(evt) {
+ // 点击位置放一个机器人
+ const touches = evt.changedTouches.length ? evt.changedTouches : evt.touches
+ if (touches.length === 1) {
+ const touch = touches[0]
+ if (this.session && this.scene && this.model) {
+ const hitTestRes = this.session.hitTest(touch.x / this.data.width, touch.y / this.data.height, this.resetPanel)
+ this.resetPanel = false
+ if (hitTestRes.length) {
+ const model = this.getRobot()
+ model.matrixAutoUpdate = false
+ model.matrix.fromArray(hitTestRes[0].transform)
+ this.scene.add(model)
}
- },
- })
-}
\ No newline at end of file
+ }
+ }
+ }
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/visionkit-basic-v2.js b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/visionkit-basic-v2.js
index 8029a4fe..95ce730c 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/visionkit-basic-v2.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/visionkit-basic-v2.js
@@ -5,61 +5,61 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- this.renderGL(frame)
+ render(frame) {
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- const dt = this.clock.getDelta()
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.update(dt))
- }
+ const dt = this.clock.getDelta()
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.update(dt))
+ }
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic-v2/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic/behavior.js b/miniprogram/packageAPI/pages/ar/visionkit-basic/behavior.js
index d2f0ea1d..a39b11b6 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic/behavior.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic/behavior.js
@@ -1,253 +1,252 @@
import {
- createScopedThreejs
+ createScopedThreejs
} from './threejs-miniprogram'
import {
- registerGLTFLoader
+ registerGLTFLoader
} from '../loaders/gltf-loader'
import cloneGltf from '../loaders/gltf-clone'
const info = wx.getSystemInfoSync()
export default function getBehavior() {
- return Behavior({
- data: {
- width: 1,
- height: 1,
- fps: 0,
- memory: 0,
- cpu: 0,
- },
- methods: {
- onReady() {
- wx.createSelectorQuery()
- .select('#webgl')
- .node()
- .exec(res => {
- this.canvas = res[0].node
-
- const info = wx.getSystemInfoSync()
- const pixelRatio = info.pixelRatio
- const calcSize = (width, height) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
- calcSize(info.windowWidth, info.windowHeight * 0.8)
-
- this.initVK()
- })
- },
- onUnload() {
- if (this._texture) {
- this._texture.dispose()
- this._texture = null
- }
- if (this.renderer) {
- this.renderer.dispose()
- this.renderer = null
- }
- if (this.scene) {
- this.scene.dispose()
- this.scene = null
- }
- if (this.camera) this.camera = null
- if (this.model) this.model = null
- if (this._insertModel) this._insertModel = null
- if (this._insertModels) this._insertModels = null
- if (this.planeBox) this.planeBox = null
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
- this.mixers = null
- }
- if (this.clock) this.clock = null
-
- if (this.THREE) this.THREE = null
- if (this._tempTexture && this._tempTexture.gl) {
- this._tempTexture.gl.deleteTexture(this._tempTexture)
- this._tempTexture = null
- }
- if (this._fb && this._fb.gl) {
- this._fb.gl.deleteFramebuffer(this._fb)
- this._fb = null
- }
- if (this._program && this._program.gl) {
- this._program.gl.deleteProgram(this._program)
- this._program = null
- }
- if (this.canvas) this.canvas = null
- if (this.gl) this.gl = null
- if (this.session) this.session = null
- if (this.anchor2DList) this.anchor2DList = []
- },
- initVK() {
- // 初始化 threejs
- this.initTHREE()
- const THREE = this.THREE
-
- // 自定义初始化
- if (this.init) this.init()
-
- console.log('this.gl', this.gl)
-
- const session = this.session = wx.createVKSession({
- track: {
- plane: {
- mode: 3
- },
- },
- version: 'v1',
- gl: this.gl
- })
- session.start(err => {
- if (err) return console.error('VK error: ', err)
-
- console.log('@@@@@@@@ VKSession.version', session.version)
-
- const canvas = this.canvas
-
- const calcSize = (width, height, pixelRatio) => {
- console.log(`canvas size: width = ${width} , height = ${height}`)
- this.canvas.width = width * pixelRatio
- this.canvas.height = height * pixelRatio
- this.setData({
- width,
- height,
- })
- }
-
- session.on('resize', () => {
- const info = wx.getSystemInfoSync()
- calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
- })
-
- const loader = new THREE.GLTFLoader()
- loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
- this.model = {
- scene: gltf.scene,
- animations: gltf.animations,
- }
- })
-
- this.clock = new THREE.Clock()
-
-
- //限制调用帧率
- let fps = 30
- let fpsInterval = 1000 / fps
- let last = Date.now()
-
- // 逐帧渲染
- const onFrame = timestamp => {
- let now = Date.now()
- const mill = now - last
- // 经过了足够的时间
- if (mill > fpsInterval) {
- last = now - (mill % fpsInterval); //校正当前时间
- const frame = session.getVKFrame(canvas.width, canvas.height)
- if (frame) {
- this.render(frame)
- }
- }
- session.requestAnimationFrame(onFrame)
- }
- session.requestAnimationFrame(onFrame)
- })
- },
- initTHREE() {
- const THREE = this.THREE = createScopedThreejs(this.canvas)
- registerGLTFLoader(THREE)
-
- // 相机
- this.camera = new THREE.Camera()
-
- // 场景
- const scene = this.scene = new THREE.Scene()
-
- // 光源
- const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
- light1.position.set(0, 0.2, 0)
- scene.add(light1)
- const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
- light2.position.set(0, 0.2, 0.1)
- scene.add(light2)
-
- // 渲染层
- const renderer = this.renderer = new THREE.WebGLRenderer({
- antialias: true,
- alpha: true
- })
- renderer.gammaOutput = true
- renderer.gammaFactor = 2.2
- },
-
- copyRobot() {
- const THREE = this.THREE
- const {
- scene,
- animations
- } = cloneGltf(this.model, THREE)
- scene.scale.set(0.05, 0.05, 0.05)
-
- // 动画混合器
- const mixer = new THREE.AnimationMixer(scene)
- for (let i = 0; i < animations.length; i++) {
- const clip = animations[i]
- if (clip.name === 'Dance') {
- const action = mixer.clipAction(clip)
- action.play()
- }
- }
-
- this.mixers = this.mixers || []
- this.mixers.push(mixer)
-
- scene._mixer = mixer
- return scene
- },
- getRobot() {
- const THREE = this.THREE
-
- const model = new THREE.Object3D()
- model.add(this.copyRobot())
-
- this._insertModels = this._insertModels || []
- this._insertModels.push(model)
-
- if (this._insertModels.length > 5) {
- const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
- needRemove.forEach(item => {
- if (item._mixer) {
- const mixer = item._mixer
- this.mixers.splice(this.mixers.indexOf(mixer), 1)
- mixer.uncacheRoot(mixer.getRoot())
- }
- if (item.parent) item.parent.remove(item)
- })
- }
-
- return model
+ return Behavior({
+ data: {
+ width: 1,
+ height: 1,
+ fps: 0,
+ memory: 0,
+ cpu: 0,
+ },
+ methods: {
+ onReady() {
+ wx.createSelectorQuery()
+ .select('#webgl')
+ .node()
+ .exec(res => {
+ this.canvas = res[0].node
+
+ const info = wx.getSystemInfoSync()
+ const pixelRatio = info.pixelRatio
+ const calcSize = (width, height) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+ calcSize(info.windowWidth, info.windowHeight * 0.8)
+
+ this.initVK()
+ })
+ },
+ onUnload() {
+ if (this._texture) {
+ this._texture.dispose()
+ this._texture = null
+ }
+ if (this.renderer) {
+ this.renderer.dispose()
+ this.renderer = null
+ }
+ if (this.scene) {
+ this.scene.dispose()
+ this.scene = null
+ }
+ if (this.camera) this.camera = null
+ if (this.model) this.model = null
+ if (this._insertModel) this._insertModel = null
+ if (this._insertModels) this._insertModels = null
+ if (this.planeBox) this.planeBox = null
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.uncacheRoot(mixer.getRoot()))
+ this.mixers = null
+ }
+ if (this.clock) this.clock = null
+
+ if (this.THREE) this.THREE = null
+ if (this._tempTexture && this._tempTexture.gl) {
+ this._tempTexture.gl.deleteTexture(this._tempTexture)
+ this._tempTexture = null
+ }
+ if (this._fb && this._fb.gl) {
+ this._fb.gl.deleteFramebuffer(this._fb)
+ this._fb = null
+ }
+ if (this._program && this._program.gl) {
+ this._program.gl.deleteProgram(this._program)
+ this._program = null
+ }
+ if (this.canvas) this.canvas = null
+ if (this.gl) this.gl = null
+ if (this.session) this.session = null
+ if (this.anchor2DList) this.anchor2DList = []
+ },
+ initVK() {
+ // 初始化 threejs
+ this.initTHREE()
+ const THREE = this.THREE
+
+ // 自定义初始化
+ if (this.init) this.init()
+
+ console.log('this.gl', this.gl)
+
+ const session = this.session = wx.createVKSession({
+ track: {
+ plane: {
+ mode: 3
},
- onTouchEnd(evt) {
- // 点击位置放一个机器人
- const touches = evt.changedTouches.length ? evt.changedTouches : evt.touches
- if (touches.length === 1) {
- const touch = touches[0]
- if (this.session && this.scene && this.model) {
- const hitTestRes = this.session.hitTest(touch.x / this.data.width, touch.y / this.data.height, this.resetPanel)
- this.resetPanel = false
- if (hitTestRes.length) {
- const model = this.getRobot()
- model.matrixAutoUpdate = false
- model.matrix.fromArray(hitTestRes[0].transform)
- this.scene.add(model)
- }
- }
- }
+ },
+ version: 'v1',
+ gl: this.gl
+ })
+ session.start(err => {
+ if (err) return console.error('VK error: ', err)
+
+ console.log('@@@@@@@@ VKSession.version', session.version)
+
+ const canvas = this.canvas
+
+ const calcSize = (width, height, pixelRatio) => {
+ console.log(`canvas size: width = ${width} , height = ${height}`)
+ this.canvas.width = width * pixelRatio
+ this.canvas.height = height * pixelRatio
+ this.setData({
+ width,
+ height,
+ })
+ }
+
+ session.on('resize', () => {
+ const info = wx.getSystemInfoSync()
+ calcSize(info.windowWidth, info.windowHeight * 0.8, info.pixelRatio)
+ })
+
+ const loader = new THREE.GLTFLoader()
+ loader.load('https://dldir1.qq.com/weixin/miniprogram/RobotExpressive_aa2603d917384b68bb4a086f32dabe83.glb', gltf => {
+ this.model = {
+ scene: gltf.scene,
+ animations: gltf.animations,
+ }
+ })
+
+ this.clock = new THREE.Clock()
+
+ // 限制调用帧率
+ const fps = 30
+ const fpsInterval = 1000 / fps
+ let last = Date.now()
+
+ // 逐帧渲染
+ const onFrame = timestamp => {
+ const now = Date.now()
+ const mill = now - last
+ // 经过了足够的时间
+ if (mill > fpsInterval) {
+ last = now - (mill % fpsInterval) // 校正当前时间
+ const frame = session.getVKFrame(canvas.width, canvas.height)
+ if (frame) {
+ this.render(frame)
+ }
+ }
+ session.requestAnimationFrame(onFrame)
+ }
+ session.requestAnimationFrame(onFrame)
+ })
+ },
+ initTHREE() {
+ const THREE = this.THREE = createScopedThreejs(this.canvas)
+ registerGLTFLoader(THREE)
+
+ // 相机
+ this.camera = new THREE.Camera()
+
+ // 场景
+ const scene = this.scene = new THREE.Scene()
+
+ // 光源
+ const light1 = new THREE.HemisphereLight(0xffffff, 0x444444) // 半球光
+ light1.position.set(0, 0.2, 0)
+ scene.add(light1)
+ const light2 = new THREE.DirectionalLight(0xffffff) // 平行光
+ light2.position.set(0, 0.2, 0.1)
+ scene.add(light2)
+
+ // 渲染层
+ const renderer = this.renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true
+ })
+ renderer.gammaOutput = true
+ renderer.gammaFactor = 2.2
+ },
+
+ copyRobot() {
+ const THREE = this.THREE
+ const {
+ scene,
+ animations
+ } = cloneGltf(this.model, THREE)
+ scene.scale.set(0.05, 0.05, 0.05)
+
+ // 动画混合器
+ const mixer = new THREE.AnimationMixer(scene)
+ for (let i = 0; i < animations.length; i++) {
+ const clip = animations[i]
+ if (clip.name === 'Dance') {
+ const action = mixer.clipAction(clip)
+ action.play()
+ }
+ }
+
+ this.mixers = this.mixers || []
+ this.mixers.push(mixer)
+
+ scene._mixer = mixer
+ return scene
+ },
+ getRobot() {
+ const THREE = this.THREE
+
+ const model = new THREE.Object3D()
+ model.add(this.copyRobot())
+
+ this._insertModels = this._insertModels || []
+ this._insertModels.push(model)
+
+ if (this._insertModels.length > 5) {
+ const needRemove = this._insertModels.splice(0, this._insertModels.length - 5)
+ needRemove.forEach(item => {
+ if (item._mixer) {
+ const mixer = item._mixer
+ this.mixers.splice(this.mixers.indexOf(mixer), 1)
+ mixer.uncacheRoot(mixer.getRoot())
+ }
+ if (item.parent) item.parent.remove(item)
+ })
+ }
+
+ return model
+ },
+ onTouchEnd(evt) {
+ // 点击位置放一个机器人
+ const touches = evt.changedTouches.length ? evt.changedTouches : evt.touches
+ if (touches.length === 1) {
+ const touch = touches[0]
+ if (this.session && this.scene && this.model) {
+ const hitTestRes = this.session.hitTest(touch.x / this.data.width, touch.y / this.data.height, this.resetPanel)
+ this.resetPanel = false
+ if (hitTestRes.length) {
+ const model = this.getRobot()
+ model.matrixAutoUpdate = false
+ model.matrix.fromArray(hitTestRes[0].transform)
+ this.scene.add(model)
}
- },
- })
-}
\ No newline at end of file
+ }
+ }
+ }
+ },
+ })
+}
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic/visionkit-basic.js b/miniprogram/packageAPI/pages/ar/visionkit-basic/visionkit-basic.js
index 8029a4fe..95ce730c 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic/visionkit-basic.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic/visionkit-basic.js
@@ -5,61 +5,61 @@ const NEAR = 0.001
const FAR = 1000
Component({
- behaviors: [getBehavior(), yuvBehavior],
- data: {
- theme: 'light',
- },
- lifetimes: {
- /**
+ behaviors: [getBehavior(), yuvBehavior],
+ data: {
+ theme: 'light',
+ },
+ lifetimes: {
+ /**
* 生命周期函数--监听页面加载
*/
- detached() {
- console.log("页面detached")
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
- ready() {
- console.log("页面准备完全")
- this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
- })
-
- if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
- })
- }
- },
+ detached() {
+ console.log('页面detached')
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
+ },
+ ready() {
+ console.log('页面准备完全')
+ this.setData({
+ theme: getApp().globalData.theme || 'light'
+ })
+
+ if (wx.onThemeChange) {
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
+ })
+ }
+ },
+ },
+ methods: {
+ init() {
+ this.initGL()
},
- methods: {
- init() {
- this.initGL()
- },
- render(frame) {
- this.renderGL(frame)
+ render(frame) {
+ this.renderGL(frame)
- const camera = frame.camera
+ const camera = frame.camera
- const dt = this.clock.getDelta()
- if (this.mixers) {
- this.mixers.forEach(mixer => mixer.update(dt))
- }
+ const dt = this.clock.getDelta()
+ if (this.mixers) {
+ this.mixers.forEach(mixer => mixer.update(dt))
+ }
- // 相机
- if (camera) {
- this.camera.matrixAutoUpdate = false
- this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
- this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
+ // 相机
+ if (camera) {
+ this.camera.matrixAutoUpdate = false
+ this.camera.matrixWorldInverse.fromArray(camera.viewMatrix)
+ this.camera.matrixWorld.getInverse(this.camera.matrixWorldInverse)
- const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
- this.camera.projectionMatrix.fromArray(projectionMatrix)
- this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
- }
+ const projectionMatrix = camera.getProjectionMatrix(NEAR, FAR)
+ this.camera.projectionMatrix.fromArray(projectionMatrix)
+ this.camera.projectionMatrixInverse.getInverse(this.camera.projectionMatrix)
+ }
- this.renderer.autoClearColor = false
- this.renderer.render(this.scene, this.camera)
- this.renderer.state.setCullFace(this.THREE.CullFaceNone)
- },
+ this.renderer.autoClearColor = false
+ this.renderer.render(this.scene, this.camera)
+ this.renderer.state.setCullFace(this.THREE.CullFaceNone)
},
-})
\ No newline at end of file
+ },
+})
diff --git a/miniprogram/packageAPI/pages/ar/visionkit-basic/yuvBehavior.js b/miniprogram/packageAPI/pages/ar/visionkit-basic/yuvBehavior.js
index 5d4e249c..1c7cb263 100644
--- a/miniprogram/packageAPI/pages/ar/visionkit-basic/yuvBehavior.js
+++ b/miniprogram/packageAPI/pages/ar/visionkit-basic/yuvBehavior.js
@@ -1,9 +1,9 @@
const yuvBehavior = Behavior({
- methods: {
- initShader() {
- const gl = this.gl = this.renderer.getContext()
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const vs = `
+ methods: {
+ initShader() {
+ const gl = this.gl = this.renderer.getContext()
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const vs = `
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform mat3 displayTransform;
@@ -14,7 +14,7 @@ const yuvBehavior = Behavior({
v_texCoord = a_texCoord;
}
`
- const fs = `
+ const fs = `
precision highp float;
uniform sampler2D y_texture;
@@ -37,103 +37,103 @@ const yuvBehavior = Behavior({
gl_FragColor = vec4(R, G, B, 1.0);
}
`
- const vertShader = gl.createShader(gl.VERTEX_SHADER)
- gl.shaderSource(vertShader, vs)
- gl.compileShader(vertShader)
-
- const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
- gl.shaderSource(fragShader, fs)
- gl.compileShader(fragShader)
-
- const program = this._program = gl.createProgram()
- this._program.gl = gl
- gl.attachShader(program, vertShader)
- gl.attachShader(program, fragShader)
- gl.deleteShader(vertShader)
- gl.deleteShader(fragShader)
- gl.linkProgram(program)
- gl.useProgram(program)
-
- const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
- gl.uniform1i(uniformYTexture, 5)
- const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
- gl.uniform1i(uniformUVTexture, 6)
-
- this._dt = gl.getUniformLocation(program, 'displayTransform')
- gl.useProgram(currentProgram)
- },
- initVAO() {
- const gl = this.renderer.getContext()
- const ext = gl.getExtension('OES_vertex_array_object')
- this.ext = ext
-
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
- const vao = ext.createVertexArrayOES()
-
- ext.bindVertexArrayOES(vao)
-
- const posAttr = gl.getAttribLocation(this._program, 'a_position')
- const pos = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, pos)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(posAttr)
- vao.posBuffer = pos
-
- const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
- const texcoord = gl.createBuffer()
- gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
- gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
- gl.enableVertexAttribArray(texcoordAttr)
- vao.texcoordBuffer = texcoord
-
- ext.bindVertexArrayOES(currentVAO)
- this._vao = vao
- },
- initGL() {
- this.initShader()
- this.initVAO()
- },
- renderGL(frame) {
- const gl = this.renderer.getContext()
- gl.disable(gl.DEPTH_TEST)
- const {
- yTexture,
- uvTexture
- } = frame.getCameraTexture(gl, 'yuv')
- const displayTransform = frame.getDisplayTransform()
- if (yTexture && uvTexture) {
- const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
- const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
- const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
-
- gl.useProgram(this._program)
- this.ext.bindVertexArrayOES(this._vao)
-
- gl.uniformMatrix3fv(this._dt, false, displayTransform)
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
-
- gl.activeTexture(gl.TEXTURE0 + 5)
- const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, yTexture)
-
- gl.activeTexture(gl.TEXTURE0 + 6)
- const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
- gl.bindTexture(gl.TEXTURE_2D, uvTexture)
-
- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
-
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
- gl.activeTexture(gl.TEXTURE0 + 5)
- gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
-
- gl.useProgram(currentProgram)
- gl.activeTexture(currentActiveTexture)
- this.ext.bindVertexArrayOES(currentVAO)
- }
- },
+ const vertShader = gl.createShader(gl.VERTEX_SHADER)
+ gl.shaderSource(vertShader, vs)
+ gl.compileShader(vertShader)
+
+ const fragShader = gl.createShader(gl.FRAGMENT_SHADER)
+ gl.shaderSource(fragShader, fs)
+ gl.compileShader(fragShader)
+
+ const program = this._program = gl.createProgram()
+ this._program.gl = gl
+ gl.attachShader(program, vertShader)
+ gl.attachShader(program, fragShader)
+ gl.deleteShader(vertShader)
+ gl.deleteShader(fragShader)
+ gl.linkProgram(program)
+ gl.useProgram(program)
+
+ const uniformYTexture = gl.getUniformLocation(program, 'y_texture')
+ gl.uniform1i(uniformYTexture, 5)
+ const uniformUVTexture = gl.getUniformLocation(program, 'uv_texture')
+ gl.uniform1i(uniformUVTexture, 6)
+
+ this._dt = gl.getUniformLocation(program, 'displayTransform')
+ gl.useProgram(currentProgram)
},
+ initVAO() {
+ const gl = this.renderer.getContext()
+ const ext = gl.getExtension('OES_vertex_array_object')
+ this.ext = ext
+
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+ const vao = ext.createVertexArrayOES()
+
+ ext.bindVertexArrayOES(vao)
+
+ const posAttr = gl.getAttribLocation(this._program, 'a_position')
+ const pos = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, pos)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, -1, 1, 1, -1, -1, -1]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(posAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(posAttr)
+ vao.posBuffer = pos
+
+ const texcoordAttr = gl.getAttribLocation(this._program, 'a_texCoord')
+ const texcoord = gl.createBuffer()
+ gl.bindBuffer(gl.ARRAY_BUFFER, texcoord)
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([1, 1, 0, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
+ gl.vertexAttribPointer(texcoordAttr, 2, gl.FLOAT, false, 0, 0)
+ gl.enableVertexAttribArray(texcoordAttr)
+ vao.texcoordBuffer = texcoord
+
+ ext.bindVertexArrayOES(currentVAO)
+ this._vao = vao
+ },
+ initGL() {
+ this.initShader()
+ this.initVAO()
+ },
+ renderGL(frame) {
+ const gl = this.renderer.getContext()
+ gl.disable(gl.DEPTH_TEST)
+ const {
+ yTexture,
+ uvTexture
+ } = frame.getCameraTexture(gl, 'yuv')
+ const displayTransform = frame.getDisplayTransform()
+ if (yTexture && uvTexture) {
+ const currentProgram = gl.getParameter(gl.CURRENT_PROGRAM)
+ const currentActiveTexture = gl.getParameter(gl.ACTIVE_TEXTURE)
+ const currentVAO = gl.getParameter(gl.VERTEX_ARRAY_BINDING)
+
+ gl.useProgram(this._program)
+ this.ext.bindVertexArrayOES(this._vao)
+
+ gl.uniformMatrix3fv(this._dt, false, displayTransform)
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)
+
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ const bindingTexture5 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, yTexture)
+
+ gl.activeTexture(gl.TEXTURE0 + 6)
+ const bindingTexture6 = gl.getParameter(gl.TEXTURE_BINDING_2D)
+ gl.bindTexture(gl.TEXTURE_2D, uvTexture)
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture6)
+ gl.activeTexture(gl.TEXTURE0 + 5)
+ gl.bindTexture(gl.TEXTURE_2D, bindingTexture5)
+
+ gl.useProgram(currentProgram)
+ gl.activeTexture(currentActiveTexture)
+ this.ext.bindVertexArrayOES(currentVAO)
+ }
+ },
+ },
})
-export default yuvBehavior
\ No newline at end of file
+export default yuvBehavior
diff --git a/miniprogram/packageAPI/pages/chattool/activity_assist/activity_assist.js b/miniprogram/packageAPI/pages/chattool/activity_assist/activity_assist.js
index 7f2eb1bf..b4d87e33 100644
--- a/miniprogram/packageAPI/pages/chattool/activity_assist/activity_assist.js
+++ b/miniprogram/packageAPI/pages/chattool/activity_assist/activity_assist.js
@@ -1,6 +1,7 @@
const config = require('../../../../config')
const util = require('../../../../util/util')
-const systemInfo = wx.getSystemInfoSync()
+
+const systemInfo = getApp().globalData
Page({
data: {
activityList: [],
@@ -33,9 +34,9 @@ Page({
env: config.envId,
traceUser: true,
})
-
+
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
diff --git a/miniprogram/packageAPI/pages/chattool/material_open/material_open.js b/miniprogram/packageAPI/pages/chattool/material_open/material_open.js
index f06e7a8f..8ae28e84 100644
--- a/miniprogram/packageAPI/pages/chattool/material_open/material_open.js
+++ b/miniprogram/packageAPI/pages/chattool/material_open/material_open.js
@@ -1,15 +1,16 @@
import { getGroupEnterInfo } from '../util'
+
const config = require('../../../../config')
let needShowEntrance = true
-let entrancePath = 'packageAPI/pages/chattool/material_open/material_open'
-let templateId = '4A68CBB88A92B0A9311848DBA1E94A199B166463' // 完成
+const entrancePath = 'packageAPI/pages/chattool/material_open/material_open'
+const templateId = '4A68CBB88A92B0A9311848DBA1E94A199B166463' // 完成
// let templateId = '2A84254B945674A2F88CE4970782C402795EB607' // 参与
const fileUrl = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js'
const videoUrl = 'https://res.wx.qq.com/op_res/o3RWIC_o--wNf_qA3B4ghHbL_qKRRwsUM39dGTzltCR2__61DnEANInj5AJJmVXsHvx9FyHlDftU3KhcGCukDA'
-const {envVersion} = wx.getAccountInfoSync().miniProgram
+const { envVersion } = wx.getAccountInfoSync().miniProgram
const getVersionType = () => {
if (envVersion === 'release') {
@@ -48,9 +49,9 @@ Page({
env: config.envId,
traceUser: true,
})
-
+
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -71,24 +72,24 @@ Page({
}
await getGroupEnterInfo()
- .then(groupInfo => {
- const {groupOpenID} = groupInfo
- this.updateChatToolMsg(activityId, {
- targetState: 1,
- parameterList: [{
- groupOpenID,
- state: 1,
- }]
- })
- wx.showToast({
- title: '签到成功',
- icon: 'none'
+ .then(groupInfo => {
+ const { groupOpenID } = groupInfo
+ this.updateChatToolMsg(activityId, {
+ targetState: 1,
+ parameterList: [{
+ groupOpenID,
+ state: 1,
+ }]
+ })
+ wx.showToast({
+ title: '签到成功',
+ icon: 'none'
+ })
+ }).catch(err => {
+ console.error('getGroupEnterInfo fail: ', err)
})
- }).catch(err => {
- console.error('getGroupEnterInfo fail: ', err)
- })
},
-
+
remindExpiration() {
const activityId = this._activityId
if (!activityId) {
@@ -126,7 +127,7 @@ Page({
},
updateChatToolMsg(activityId, params = {}) {
- const {targetState, parameterList } = params
+ const { targetState, parameterList } = params
wx.cloud.callFunction({
name: 'openapi',
data: {
@@ -203,7 +204,7 @@ Page({
complete(res) {
console.info('shareImageToGroup: ', res)
}
- })
+ })
}
})
},
@@ -219,7 +220,7 @@ Page({
complete(res) {
console.info('shareEmojiToGroup: ', res)
}
- })
+ })
}
})
},
@@ -227,7 +228,7 @@ Page({
shareVideo() {
wx.downloadFile({
url: videoUrl,
- success (res) {
+ success(res) {
wx.shareVideoToGroup({
videoPath: res.tempFilePath,
thumbPath: '',
@@ -236,7 +237,7 @@ Page({
complete(res) {
console.info('shareVideoToGroup: ', res)
}
- })
+ })
},
fail: console.error,
})
@@ -245,7 +246,7 @@ Page({
shareFile() {
wx.downloadFile({
url: fileUrl,
- success (res) {
+ success(res) {
wx.shareFileToGroup({
filePath: res.tempFilePath,
fileName: '',
@@ -254,7 +255,7 @@ Page({
complete(res) {
console.info('shareFileToGroup: ', res)
}
- })
+ })
},
fail: console.error,
})
diff --git a/miniprogram/packageAPI/pages/chattool/material_view/material_view.js b/miniprogram/packageAPI/pages/chattool/material_view/material_view.js
index 4a72ef5a..2d042b82 100644
--- a/miniprogram/packageAPI/pages/chattool/material_view/material_view.js
+++ b/miniprogram/packageAPI/pages/chattool/material_view/material_view.js
@@ -104,7 +104,7 @@ Page({
// this.formatMaterials(mockData.materials)
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
@@ -131,7 +131,7 @@ Page({
this.triggerMergedImage()
const materials = []
- for (let item of forwardMaterials) {
+ for (const item of forwardMaterials) {
let recordType = ''
if (item.type === 'text/message') {
recordType = chatRecordTypes[0]
@@ -155,15 +155,14 @@ Page({
async triggerMergedImage() {
try {
const tempFilePaths = this._forwardMaterials
- .filter(item => item.type.startsWith('image'))
- .map(item => item.path)
+ .filter(item => item.type.startsWith('image'))
+ .map(item => item.path)
console.info('tempFilePaths: ', tempFilePaths)
const shareImagePath = await this.mergeImages(tempFilePaths)
this.setData({
shareImagePath,
})
console.info('shareImagePath: ', shareImagePath)
-
} catch (error) {
console.error('mergeImages fail: ', error)
}
@@ -190,22 +189,22 @@ Page({
async mergeImages(tempFilePaths) {
try {
// 获取 canvas 节点
- const { node: canvas, width: cw, height: ch } = await this.getCanvasNode();
-
+ const { node: canvas, width: cw, height: ch } = await this.getCanvasNode()
+
// 获取 2D 上下文
- const ctx = canvas.getContext('2d');
-
+ const ctx = canvas.getContext('2d')
+
// 预加载所有图片
- const images = await this.loadAllImages(canvas, tempFilePaths);
-
+ const images = await this.loadAllImages(canvas, tempFilePaths)
+
// 绘制图片
- this.drawImages(ctx, images, 400);
-
+ this.drawImages(ctx, images, 400)
+
// 生成临时文件
- return await this.canvasToTempFile(canvas);
+ return await this.canvasToTempFile(canvas)
} catch (err) {
- console.error('合并失败:', err);
- return null;
+ console.error('合并失败:', err)
+ return null
}
},
@@ -216,72 +215,76 @@ Page({
.select('#myCanvas')
.fields({ node: true, size: true })
.exec(res => {
- if (res[0]) resolve(res[0]);
- else reject(new Error('Canvas 节点获取失败'));
- });
- });
+ if (res[0]) resolve(res[0])
+ else reject(new Error('Canvas 节点获取失败'))
+ })
+ })
},
// 计算画布尺寸
calculateLayout(paths) {
- const imgSize = 100;
- const spacing = 10;
- const perLine = 3;
-
- const rows = Math.ceil(paths.length / perLine);
+ const imgSize = 100
+ const spacing = 10
+ const perLine = 3
+
+ const rows = Math.ceil(paths.length / perLine)
return {
canvasWidth: perLine * imgSize + (perLine - 1) * spacing,
canvasHeight: rows * imgSize + (rows - 1) * spacing
- };
+ }
},
// 加载所有图片(Web Image 对象)
loadAllImages(canvas, paths) {
- return Promise.all(paths.map(url => {
- return new Promise((resolve, reject) => {
- const image = canvas.createImage();
- image.onload = () => resolve(image);
- image.onerror = reject;
- image.src = url; // 支持本地路径和网络图片
- });
- }));
+ return Promise.all(paths.map(url => new Promise((resolve, reject) => {
+ const image = canvas.createImage()
+ image.onload = () => resolve(image)
+ image.onerror = reject
+ image.src = url // 支持本地路径和网络图片
+ })))
},
// 执行图片绘制
drawImages(ctx, images, canvasWidth) {
- const imgSize = 100;
- const spacing = 10;
- const perLine = 3;
-
+ const imgSize = 100
+ const spacing = 10
+ const perLine = 3
+
images.forEach((image, index) => {
- const row = Math.floor(index / perLine);
- const col = index % perLine;
-
- const x = col * (imgSize + spacing);
- const y = row * (imgSize + spacing);
-
+ const row = Math.floor(index / perLine)
+ const col = index % perLine
+
+ const x = col * (imgSize + spacing)
+ const y = row * (imgSize + spacing)
+
// 绘制图像(支持缩放裁剪)
ctx.drawImage(
image,
- 0, 0, image.width, image.height, // 源图裁剪区域
- x, y, imgSize, imgSize // 画布绘制区域
- );
- });
+ 0,
+ 0,
+ image.width,
+ image.height, // 源图裁剪区域
+ x,
+ y,
+ imgSize,
+ imgSize // 画布绘制区域
+ )
+ })
},
// Canvas 转临时文件
canvasToTempFile(canvas) {
return new Promise((resolve, reject) => {
wx.canvasToTempFilePath({
- canvas: canvas,
+ canvas,
fileType: 'png',
width: 400,
height: 500,
quality: 1,
success: res => resolve(res.tempFilePath),
fail: reject
- });
- });
+ })
+ })
}
})
diff --git a/miniprogram/packageAPI/pages/chattool/util.js b/miniprogram/packageAPI/pages/chattool/util.js
index 9efb68aa..81a52ae7 100644
--- a/miniprogram/packageAPI/pages/chattool/util.js
+++ b/miniprogram/packageAPI/pages/chattool/util.js
@@ -36,8 +36,8 @@ export function getGroupEnterInfo() {
reject(res)
},
complete(res) {
- console.info('getGroupEnterInfo complete: ',res)
+ console.info('getGroupEnterInfo complete: ', res)
}
})
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageAPI/pages/device/add-contact/add-contact.js b/miniprogram/packageAPI/pages/device/add-contact/add-contact.js
index 4e31a7f5..9618da9c 100644
--- a/miniprogram/packageAPI/pages/device/add-contact/add-contact.js
+++ b/miniprogram/packageAPI/pages/device/add-contact/add-contact.js
@@ -29,12 +29,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js b/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js
index b67860c1..d22c288d 100644
--- a/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js
+++ b/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js
@@ -32,9 +32,6 @@ Page({
connected: false,
chs: [],
},
- onUnload() {
- this.closeBluetoothAdapter()
- },
openBluetoothAdapter() {
const that = this
wx.openBluetoothAdapter({
@@ -252,15 +249,16 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ this.closeBluetoothAdapter()
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js b/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js
index 7d0886c9..8674f8b2 100644
--- a/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js
+++ b/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js
@@ -1,10 +1,8 @@
-
const uuid3 = '0C76801A-62EB-45E5-96A8-37C8882ABB2B'
const serviceId = 'D0611E78-BBB4-4591-A5F8-487910AE4366'
const characteristicId = '8667556C-9A37-4C91-84ED-54EE27D90049'
// 上面需要配置主机的 serviceId 和 characteristicId
-
// ArrayBuffer转16进制字符串示例
// function ab2hex(buffer) {
// const hexArr = Array.prototype.map.call(
@@ -43,15 +41,19 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ this.data.servers.forEach(() => {
+ // server.close()
+ })
},
+
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
wx.onBLEPeripheralConnectionStateChanged(res => {
@@ -63,7 +65,7 @@ Page({
} else {
connects.push(res)
}
- this.setData({connects})
+ this.setData({ connects })
})
},
@@ -106,7 +108,7 @@ Page({
title: '创建 server ',
})
this.server.onCharacteristicReadRequest(res => {
- const {serviceId, characteristicId, callbackId} = res
+ const { serviceId, characteristicId, callbackId } = res
const buffer = new ArrayBuffer(1)
const dataView = new DataView(buffer)
const newValue = Math.ceil(Math.random() * 10)
@@ -141,7 +143,7 @@ Page({
}).catch(() => {})
},
closeServer() {
- if (this.server) {
+ if (this.server) {
this.server.close()
wx.showToast({
title: '关闭 server',
@@ -302,10 +304,4 @@ Page({
})
wx.closeBluetoothAdapter()
},
-
- onUnload() {
- this.data.servers.forEach(() => {
- // server.close()
- })
- },
})
diff --git a/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js b/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js
index 4e25f6d2..a31b90fb 100644
--- a/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js
+++ b/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js
@@ -17,12 +17,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
wx.onUserCaptureScreen(() => {
diff --git a/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js b/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js
index 32d86f58..19fee164 100644
--- a/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js
+++ b/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js
@@ -58,12 +58,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/get-battery-info/get-battery-info.js b/miniprogram/packageAPI/pages/device/get-battery-info/get-battery-info.js
index 681fc884..87022900 100644
--- a/miniprogram/packageAPI/pages/device/get-battery-info/get-battery-info.js
+++ b/miniprogram/packageAPI/pages/device/get-battery-info/get-battery-info.js
@@ -29,12 +29,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/get-network-type/get-network-type.js b/miniprogram/packageAPI/pages/device/get-network-type/get-network-type.js
index 3e5f14fc..fccc5093 100644
--- a/miniprogram/packageAPI/pages/device/get-network-type/get-network-type.js
+++ b/miniprogram/packageAPI/pages/device/get-network-type/get-network-type.js
@@ -35,12 +35,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/get-system-info/get-system-info.js b/miniprogram/packageAPI/pages/device/get-system-info/get-system-info.js
index d0a058a6..e0678162 100644
--- a/miniprogram/packageAPI/pages/device/get-system-info/get-system-info.js
+++ b/miniprogram/packageAPI/pages/device/get-system-info/get-system-info.js
@@ -27,12 +27,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js b/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js
index 6ebbed60..78c86ec1 100644
--- a/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js
+++ b/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js
@@ -12,10 +12,6 @@ Page({
beacons: []
},
- onUnload() {
- this.stopSearch()
- },
-
enterUuid(e) {
this.setData({
uuid: e.detail.value
@@ -29,7 +25,7 @@ Page({
uuids: [this.data.uuid],
success: (res) => {
console.log(res)
- wx.onBeaconUpdate(({beacons}) => {
+ wx.onBeaconUpdate(({ beacons }) => {
this.setData({
beacons
})
@@ -49,15 +45,16 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ this.stopSearch()
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/make-phone-call/make-phone-call.js b/miniprogram/packageAPI/pages/device/make-phone-call/make-phone-call.js
index dacdea2f..2766f8b4 100644
--- a/miniprogram/packageAPI/pages/device/make-phone-call/make-phone-call.js
+++ b/miniprogram/packageAPI/pages/device/make-phone-call/make-phone-call.js
@@ -38,12 +38,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/on-accelerometer-change/on-accelerometer-change.js b/miniprogram/packageAPI/pages/device/on-accelerometer-change/on-accelerometer-change.js
index 7364f3ca..90f649f9 100644
--- a/miniprogram/packageAPI/pages/device/on-accelerometer-change/on-accelerometer-change.js
+++ b/miniprogram/packageAPI/pages/device/on-accelerometer-change/on-accelerometer-change.js
@@ -117,22 +117,20 @@ Page({
}
})
},
- onUnload() {
- clearInterval(this.interval)
- },
onUnload() {
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ clearInterval(this.interval)
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/on-compass-change/on-compass-change.js b/miniprogram/packageAPI/pages/device/on-compass-change/on-compass-change.js
index 4332a350..c77670e1 100644
--- a/miniprogram/packageAPI/pages/device/on-compass-change/on-compass-change.js
+++ b/miniprogram/packageAPI/pages/device/on-compass-change/on-compass-change.js
@@ -52,12 +52,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/on-network-status-change/on-network-status-change.js b/miniprogram/packageAPI/pages/device/on-network-status-change/on-network-status-change.js
index 8b3b6a0f..d2f34ab2 100644
--- a/miniprogram/packageAPI/pages/device/on-network-status-change/on-network-status-change.js
+++ b/miniprogram/packageAPI/pages/device/on-network-status-change/on-network-status-change.js
@@ -17,12 +17,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const that = this
diff --git a/miniprogram/packageAPI/pages/device/scan-code/scan-code.js b/miniprogram/packageAPI/pages/device/scan-code/scan-code.js
index 112e2796..f16ce851 100644
--- a/miniprogram/packageAPI/pages/device/scan-code/scan-code.js
+++ b/miniprogram/packageAPI/pages/device/scan-code/scan-code.js
@@ -32,12 +32,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js b/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js
index a7976ab7..f9ca2268 100644
--- a/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js
+++ b/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js
@@ -18,12 +18,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this._updateScreenBrightness()
diff --git a/miniprogram/packageAPI/pages/device/vibrate/vibrate.js b/miniprogram/packageAPI/pages/device/vibrate/vibrate.js
index 1f4af12a..ea956160 100644
--- a/miniprogram/packageAPI/pages/device/vibrate/vibrate.js
+++ b/miniprogram/packageAPI/pages/device/vibrate/vibrate.js
@@ -40,12 +40,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/device/wifi/wifi.js b/miniprogram/packageAPI/pages/device/wifi/wifi.js
index a56657c9..0bc99255 100644
--- a/miniprogram/packageAPI/pages/device/wifi/wifi.js
+++ b/miniprogram/packageAPI/pages/device/wifi/wifi.js
@@ -11,10 +11,6 @@ Page({
wifiList: []
},
- onUnload() {
- this.stopSearch()
- },
-
startSearch() {
const getWifiList = () => {
wx.getWifiList({
@@ -24,7 +20,7 @@ Page({
.sort((a, b) => b.signalStrength - a.signalStrength)
.map(wifi => {
const strength = Math.ceil(wifi.signalStrength * 4)
- return Object.assign(wifi, {strength})
+ return Object.assign(wifi, { strength })
})
this.setData({
wifiList
@@ -76,18 +72,19 @@ Page({
})
},
onUnload() {
+ this.stopSearch()
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/framework/resizable/resizable.js b/miniprogram/packageAPI/pages/framework/resizable/resizable.js
index 2f66ecd8..3585a590 100644
--- a/miniprogram/packageAPI/pages/framework/resizable/resizable.js
+++ b/miniprogram/packageAPI/pages/framework/resizable/resizable.js
@@ -22,12 +22,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/framework/two-way-bindings/two-way-bindings.js b/miniprogram/packageAPI/pages/framework/two-way-bindings/two-way-bindings.js
index ea50ab59..f285414a 100644
--- a/miniprogram/packageAPI/pages/framework/two-way-bindings/two-way-bindings.js
+++ b/miniprogram/packageAPI/pages/framework/two-way-bindings/two-way-bindings.js
@@ -12,22 +12,16 @@ Page({
/**
* 生命周期函数--监听页面加载
*/
- onUnload() {
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
-
},
/**
@@ -55,7 +49,9 @@ Page({
* 生命周期函数--监听页面卸载
*/
onUnload() {
-
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
/**
diff --git a/miniprogram/packageAPI/pages/framework/wxs/movable.js b/miniprogram/packageAPI/pages/framework/wxs/movable.js
index 8071a734..d6e86550 100644
--- a/miniprogram/packageAPI/pages/framework/wxs/movable.js
+++ b/miniprogram/packageAPI/pages/framework/wxs/movable.js
@@ -30,15 +30,14 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
-
},
/**
diff --git a/miniprogram/packageAPI/pages/framework/wxs/nearby.js b/miniprogram/packageAPI/pages/framework/wxs/nearby.js
index 4b4e0efd..f2138af5 100644
--- a/miniprogram/packageAPI/pages/framework/wxs/nearby.js
+++ b/miniprogram/packageAPI/pages/framework/wxs/nearby.js
@@ -65,12 +65,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/framework/wxs/sidebar.js b/miniprogram/packageAPI/pages/framework/wxs/sidebar.js
index 8ae91b66..d3245ed6 100644
--- a/miniprogram/packageAPI/pages/framework/wxs/sidebar.js
+++ b/miniprogram/packageAPI/pages/framework/wxs/sidebar.js
@@ -19,12 +19,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const tabs = [
@@ -35,7 +35,7 @@ Page({
desc: '本视频系列课程,由腾讯课堂NEXT学院与微信团队联合出品,通过实战案例,深入浅出地进行讲解。',
},
]
- this.setData({tabs})
+ this.setData({ tabs })
// setTimeout(() => {
// this.initInteraction()
// }, 5000)
diff --git a/miniprogram/packageAPI/pages/framework/wxs/stick-top.js b/miniprogram/packageAPI/pages/framework/wxs/stick-top.js
index e9fd54d7..52fc4e40 100644
--- a/miniprogram/packageAPI/pages/framework/wxs/stick-top.js
+++ b/miniprogram/packageAPI/pages/framework/wxs/stick-top.js
@@ -25,12 +25,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const tabs = [
@@ -65,6 +65,6 @@ Page({
desc: '微信小程序应用开发赛',
},
]
- this.setData({tabs})
+ this.setData({ tabs })
}
})
diff --git a/miniprogram/packageAPI/pages/framework/wxs/wxs.js b/miniprogram/packageAPI/pages/framework/wxs/wxs.js
index 6a9037fe..fc1f38cc 100644
--- a/miniprogram/packageAPI/pages/framework/wxs/wxs.js
+++ b/miniprogram/packageAPI/pages/framework/wxs/wxs.js
@@ -19,12 +19,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/location/choose-location/choose-location.js b/miniprogram/packageAPI/pages/location/choose-location/choose-location.js
index 62ed518d..3cd0259f 100644
--- a/miniprogram/packageAPI/pages/location/choose-location/choose-location.js
+++ b/miniprogram/packageAPI/pages/location/choose-location/choose-location.js
@@ -39,12 +39,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/location/get-location/get-location.js b/miniprogram/packageAPI/pages/location/get-location/get-location.js
index e21854be..0e287be1 100644
--- a/miniprogram/packageAPI/pages/location/get-location/get-location.js
+++ b/miniprogram/packageAPI/pages/location/get-location/get-location.js
@@ -41,12 +41,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/location/open-location/open-location.js b/miniprogram/packageAPI/pages/location/open-location/open-location.js
index 3347250b..f5c3ef64 100644
--- a/miniprogram/packageAPI/pages/location/open-location/open-location.js
+++ b/miniprogram/packageAPI/pages/location/open-location/open-location.js
@@ -24,12 +24,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/media/audio/audio.js b/miniprogram/packageAPI/pages/media/audio/audio.js
index ec4b7074..fc2e0e5f 100644
--- a/miniprogram/packageAPI/pages/media/audio/audio.js
+++ b/miniprogram/packageAPI/pages/media/audio/audio.js
@@ -34,12 +34,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/media/background-audio/background-audio.js b/miniprogram/packageAPI/pages/media/background-audio/background-audio.js
index 47be9d5b..baa13d2f 100644
--- a/miniprogram/packageAPI/pages/media/background-audio/background-audio.js
+++ b/miniprogram/packageAPI/pages/media/background-audio/background-audio.js
@@ -1,7 +1,6 @@
// const app = getApp()
const util = require('../../../../util/util.js')
-
const backgroundAudioManager = wx.getBackgroundAudioManager()
let updateInterval
let draging
@@ -20,10 +19,8 @@ Page({
playing: true
})
}
-
},
-
data: {
theme: 'light',
playing: false, // 播放状态
@@ -75,33 +72,31 @@ Page({
_enableInterval() {
const that = this
function update() {
- if(!draging){
+ if (!draging) {
that.setData({
- playTime: backgroundAudioManager.currentTime + 1,
- formatedPlayTime: util.formatTime(backgroundAudioManager.currentTime + 1)
+ playTime: backgroundAudioManager.currentTime + 1,
+ formatedPlayTime: util.formatTime(backgroundAudioManager.currentTime + 1)
})
}
}
updateInterval = setInterval(update, 1000)
},
- onUnload() {
- clearInterval(updateInterval)
- },
-
onUnload() {
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ clearInterval(updateInterval)
},
+
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const that = this
@@ -125,7 +120,7 @@ Page({
// 拖动到指定位置结束,恢复slider滚动
backgroundAudioManager.onSeeked((res) => {
- draging = false
+ draging = false
})
backgroundAudioManager.onEnded(() => {
diff --git a/miniprogram/packageAPI/pages/media/file/file.js b/miniprogram/packageAPI/pages/media/file/file.js
index c802af36..162c4a2c 100644
--- a/miniprogram/packageAPI/pages/media/file/file.js
+++ b/miniprogram/packageAPI/pages/media/file/file.js
@@ -13,12 +13,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
diff --git a/miniprogram/packageAPI/pages/media/image/image.js b/miniprogram/packageAPI/pages/media/image/image.js
index 3f8153c6..8abae70a 100644
--- a/miniprogram/packageAPI/pages/media/image/image.js
+++ b/miniprogram/packageAPI/pages/media/image/image.js
@@ -65,12 +65,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/media/load-font-face/load-font-face.js b/miniprogram/packageAPI/pages/media/load-font-face/load-font-face.js
index 559d4e6b..c0d11c90 100644
--- a/miniprogram/packageAPI/pages/media/load-font-face/load-font-face.js
+++ b/miniprogram/packageAPI/pages/media/load-font-face/load-font-face.js
@@ -19,12 +19,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
@@ -39,7 +39,7 @@ Page({
source: 'url("https://sungd.github.io/Pacifico.ttf")',
success(res) {
console.log(res.status)
- self.setData({loaded: true})
+ self.setData({ loaded: true })
},
fail(res) {
console.log(res.status)
@@ -51,6 +51,6 @@ Page({
},
clear() {
- this.setData({loaded: false})
+ this.setData({ loaded: false })
}
})
diff --git a/miniprogram/packageAPI/pages/media/media-container/media-container.js b/miniprogram/packageAPI/pages/media/media-container/media-container.js
index 87a48057..6982e0ad 100644
--- a/miniprogram/packageAPI/pages/media/media-container/media-container.js
+++ b/miniprogram/packageAPI/pages/media/media-container/media-container.js
@@ -1,4 +1,3 @@
-
Page({
onShareAppMessage() {
return {
@@ -13,12 +12,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const canIUse = wx.canIUse('wx.createMediaContainer()')
diff --git a/miniprogram/packageAPI/pages/media/video/video.js b/miniprogram/packageAPI/pages/media/video/video.js
index 64249875..c289d1fd 100644
--- a/miniprogram/packageAPI/pages/media/video/video.js
+++ b/miniprogram/packageAPI/pages/media/video/video.js
@@ -62,12 +62,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/media/voice/voice.js b/miniprogram/packageAPI/pages/media/voice/voice.js
index 377528c5..6ed6c45f 100644
--- a/miniprogram/packageAPI/pages/media/voice/voice.js
+++ b/miniprogram/packageAPI/pages/media/voice/voice.js
@@ -37,12 +37,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const that = this
diff --git a/miniprogram/packageAPI/pages/network/download-file/download-file.js b/miniprogram/packageAPI/pages/network/download-file/download-file.js
index b06c1854..5eecd142 100644
--- a/miniprogram/packageAPI/pages/network/download-file/download-file.js
+++ b/miniprogram/packageAPI/pages/network/download-file/download-file.js
@@ -30,12 +30,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/network/mdns/mdns.js b/miniprogram/packageAPI/pages/network/mdns/mdns.js
index 4e376ff5..b85061c3 100644
--- a/miniprogram/packageAPI/pages/network/mdns/mdns.js
+++ b/miniprogram/packageAPI/pages/network/mdns/mdns.js
@@ -71,7 +71,6 @@ Page({
})
},
-
// 监听列表
onLocalService() {
const that = this
@@ -135,12 +134,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/network/request/request.js b/miniprogram/packageAPI/pages/network/request/request.js
index ddf8b842..5c228338 100644
--- a/miniprogram/packageAPI/pages/network/request/request.js
+++ b/miniprogram/packageAPI/pages/network/request/request.js
@@ -20,7 +20,7 @@ Page({
wx.request({
url: requestUrl,
data: {
- theme: 'light',
+ theme: 'light',
noncestr: Date.now()
},
success(result) {
@@ -36,7 +36,7 @@ Page({
console.log('request success', result)
},
- fail({errMsg}) {
+ fail({ errMsg }) {
console.log('request fail', errMsg)
self.setData({
loading: false
@@ -51,12 +51,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js b/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js
index 0a9e8681..df518b85 100644
--- a/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js
+++ b/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js
@@ -1,4 +1,3 @@
-
const AB2String = (arrayBuffer) => {
const unit8Arr = new Uint8Array(arrayBuffer)
const encodedString = String.fromCharCode.apply(null, unit8Arr)
@@ -29,12 +28,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const canIUse = wx.canIUse('createUDPSocket')
@@ -58,7 +57,7 @@ Page({
startUDP: true,
})
this.remoteUDPSocket.onMessage((res) => {
- const {remoteInfo} = res
+ const { remoteInfo } = res
console.log(res)
wx.showModal({
title: `IP:${remoteInfo.address}发来的信息`,
@@ -101,5 +100,4 @@ Page({
})
},
-
})
diff --git a/miniprogram/packageAPI/pages/network/upload-file/upload-file.js b/miniprogram/packageAPI/pages/network/upload-file/upload-file.js
index d7aab8d4..4f7f401f 100644
--- a/miniprogram/packageAPI/pages/network/upload-file/upload-file.js
+++ b/miniprogram/packageAPI/pages/network/upload-file/upload-file.js
@@ -13,7 +13,7 @@ Page({
count: 1,
sizeType: ['compressed'],
sourceType: ['album'],
- success: async function(res) {
+ async success(res) {
const imageSrc = res.tempFilePaths[0]
const r = await wx.cloud.callFunction({
name: 'login',
@@ -21,10 +21,10 @@ Page({
action: 'openid'
},
})
- const openId = r.result.openid;
+ const openId = r.result.openid
const cloudPath = `upload/${openId}.png`
wx.cloud.uploadFile({
- cloudPath, // 上传至云端的路径
+ cloudPath, // 上传至云端的路径
filePath: imageSrc, // 小程序临时文件路径
config: {
env: 'release-b86096'
@@ -44,7 +44,7 @@ Page({
fileID: res.fileID,
})
},
- fail({errMsg}) {
+ fail({ errMsg }) {
console.log('uploadImage fail, errMsg is', errMsg)
}
})
@@ -59,26 +59,25 @@ Page({
}
})
},
+
onUnload() {
if (this.data.fileID) {
wx.cloud.deleteFile({
fileList: [this.data.fileID]
})
}
- },
- onUnload() {
if (wx.offThemeChange) {
wx.offThemeChange()
}
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/network/web-socket/web-socket.js b/miniprogram/packageAPI/pages/network/web-socket/web-socket.js
index ae0e1a3b..e40a991a 100644
--- a/miniprogram/packageAPI/pages/network/web-socket/web-socket.js
+++ b/miniprogram/packageAPI/pages/network/web-socket/web-socket.js
@@ -14,7 +14,6 @@ function showSuccess(title) {
})
}
-
Page({
onShareAppMessage() {
return {
@@ -32,15 +31,16 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ this.closeSocket()
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const self = this
@@ -63,10 +63,6 @@ Page({
// })
},
- onUnload() {
- this.closeSocket()
- },
-
toggleSocket(e) {
const turnedOn = e.detail.value
@@ -91,7 +87,7 @@ Page({
wx.onSocketClose(() => {
console.log('WebSocket 已断开')
- this.setData({socketStatus: 'closed'})
+ this.setData({ socketStatus: 'closed' })
})
wx.onSocketError(error => {
@@ -122,7 +118,7 @@ Page({
wx.closeSocket({
success: () => {
showSuccess('Socket已断开')
- this.setData({socketStatus: 'closed'})
+ this.setData({ socketStatus: 'closed' })
}
})
}
diff --git a/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js b/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js
index 380b9982..0d85ba4d 100644
--- a/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js
+++ b/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js
@@ -21,12 +21,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/animation/animation.js b/miniprogram/packageAPI/pages/page/animation/animation.js
index cc00e08f..19615dae 100644
--- a/miniprogram/packageAPI/pages/page/animation/animation.js
+++ b/miniprogram/packageAPI/pages/page/animation/animation.js
@@ -18,12 +18,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const canIUse = this.animate !== undefined
@@ -39,24 +39,24 @@ Page({
change() {
this.animate('#container1', [
- {opacity: 1.0, rotate: 0, backgroundColor: '#FF0000'},
+ { opacity: 1.0, rotate: 0, backgroundColor: '#FF0000' },
{
opacity: 0.5, rotate: 45, backgroundColor: '#00FF00', offset: 0.9
},
- {opacity: 0.0, rotate: 90, backgroundColor: '#FF0000'},
+ { opacity: 0.0, rotate: 90, backgroundColor: '#FF0000' },
], 5000, function () {
- this.clearAnimation('#container1', {opacity: true, rotate: true}, function () {
+ this.clearAnimation('#container1', { opacity: true, rotate: true }, function () {
console.log('清除了#container上的动画属性')
})
}.bind(this))
this.animate('.block1', [
- {scale: [1, 1], rotate: 0, ease: 'ease-out'},
+ { scale: [1, 1], rotate: 0, ease: 'ease-out' },
{
scale: [1.5, 1.5], rotate: 45, ease: 'ease-in', offset: 0.9
},
- {scale: [2, 2], rotate: 90},
+ { scale: [2, 2], rotate: 90 },
], 5000, function () {
- this.clearAnimation('.block1', {scale: true, rotate: true}, function () {
+ this.clearAnimation('.block1', { scale: true, rotate: true }, function () {
console.log('清除了.block1上的动画属性')
})
}.bind(this))
diff --git a/miniprogram/packageAPI/pages/page/canvas/canvas.js b/miniprogram/packageAPI/pages/page/canvas/canvas.js
index 49f1c744..59c563be 100644
--- a/miniprogram/packageAPI/pages/page/canvas/canvas.js
+++ b/miniprogram/packageAPI/pages/page/canvas/canvas.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.context = wx.createContext()
diff --git a/miniprogram/packageAPI/pages/page/get-wxml-node-info/get-wxml-node-info.js b/miniprogram/packageAPI/pages/page/get-wxml-node-info/get-wxml-node-info.js
index 1d114a33..fa91ac6a 100644
--- a/miniprogram/packageAPI/pages/page/get-wxml-node-info/get-wxml-node-info.js
+++ b/miniprogram/packageAPI/pages/page/get-wxml-node-info/get-wxml-node-info.js
@@ -28,11 +28,11 @@ Page({
for (const key in rect) {
if (key !== 'id' && key !== 'dataset') {
const val = rect[key]
- metrics.push({key, val})
+ metrics.push({ key, val })
}
}
- this.setData({metrics})
+ this.setData({ metrics })
}
})
},
@@ -43,12 +43,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js b/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js
index 671153c9..b221dc60 100644
--- a/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js
+++ b/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js
@@ -14,15 +14,16 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ if (this._observer) this._observer.disconnect()
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this._observer = wx.createIntersectionObserver(this)
@@ -34,8 +35,5 @@ Page({
appear: res.intersectionRatio > 0
})
})
- },
- onUnload() {
- if (this._observer) this._observer.disconnect()
}
})
diff --git a/miniprogram/packageAPI/pages/page/modal/modal.js b/miniprogram/packageAPI/pages/page/modal/modal.js
index 6ca7ca3b..96144c77 100644
--- a/miniprogram/packageAPI/pages/page/modal/modal.js
+++ b/miniprogram/packageAPI/pages/page/modal/modal.js
@@ -33,12 +33,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/navigation-bar-loading/navigation-bar-loading.js b/miniprogram/packageAPI/pages/page/navigation-bar-loading/navigation-bar-loading.js
index 338cd7b6..e4f7759e 100644
--- a/miniprogram/packageAPI/pages/page/navigation-bar-loading/navigation-bar-loading.js
+++ b/miniprogram/packageAPI/pages/page/navigation-bar-loading/navigation-bar-loading.js
@@ -19,12 +19,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/navigator/navigator.js b/miniprogram/packageAPI/pages/page/navigator/navigator.js
index ab183fbb..7aef205e 100644
--- a/miniprogram/packageAPI/pages/page/navigator/navigator.js
+++ b/miniprogram/packageAPI/pages/page/navigator/navigator.js
@@ -7,7 +7,7 @@ Page({
},
navigateTo() {
- wx.navigateTo({url: './navigator'})
+ wx.navigateTo({ url: './navigator' })
},
navigateBack() {
@@ -15,15 +15,15 @@ Page({
},
redirectTo() {
- wx.redirectTo({url: './navigator'})
+ wx.redirectTo({ url: './navigator' })
},
switchTab() {
- wx.switchTab({url: '/page/component/index'})
+ wx.switchTab({ url: '/page/component/index' })
},
reLaunch() {
- wx.reLaunch({url: '/page/component/index'})
+ wx.reLaunch({ url: '/page/component/index' })
},
onUnload() {
if (wx.offThemeChange) {
@@ -32,12 +32,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js b/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js
index df59b257..4fb36727 100644
--- a/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js
+++ b/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js
@@ -26,12 +26,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/pull-down-refresh/pull-down-refresh.js b/miniprogram/packageAPI/pages/page/pull-down-refresh/pull-down-refresh.js
index f909f88a..9b88457c 100644
--- a/miniprogram/packageAPI/pages/page/pull-down-refresh/pull-down-refresh.js
+++ b/miniprogram/packageAPI/pages/page/pull-down-refresh/pull-down-refresh.js
@@ -29,12 +29,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/set-navigation-bar-title/set-navigation-bar-title.js b/miniprogram/packageAPI/pages/page/set-navigation-bar-title/set-navigation-bar-title.js
index ff89c480..e2ab22a0 100644
--- a/miniprogram/packageAPI/pages/page/set-navigation-bar-title/set-navigation-bar-title.js
+++ b/miniprogram/packageAPI/pages/page/set-navigation-bar-title/set-navigation-bar-title.js
@@ -28,12 +28,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/page/toast/toast.js b/miniprogram/packageAPI/pages/page/toast/toast.js
index a940d1be..0bca9545 100644
--- a/miniprogram/packageAPI/pages/page/toast/toast.js
+++ b/miniprogram/packageAPI/pages/page/toast/toast.js
@@ -37,12 +37,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js b/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js
index 5f6f8346..22ffdfb3 100644
--- a/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js
+++ b/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js
@@ -5,7 +5,6 @@ const util = require('./util')
const performance = wx.getPerformance ? wx.getPerformance() : {}
const performanceObserver = performance.createObserver ? performance.createObserver() : null
-
Page({
onShareAppMessage() {
return {
@@ -25,12 +24,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
console.log('canIUse:getPerformance:', wx.canIUse('getPerformance'))
@@ -60,7 +59,7 @@ Page({
startObserver() {
// 监听需要的性能指标
- performanceObserver.observe({entryTypes: ['render', 'script', 'navigation']})
+ performanceObserver.observe({ entryTypes: ['render', 'script', 'navigation'] })
},
stopObserver() {
diff --git a/miniprogram/packageAPI/pages/storage/get-background-fetch-data/get-background-fetch-data.js b/miniprogram/packageAPI/pages/storage/get-background-fetch-data/get-background-fetch-data.js
index 5de96a30..95fc8e10 100644
--- a/miniprogram/packageAPI/pages/storage/get-background-fetch-data/get-background-fetch-data.js
+++ b/miniprogram/packageAPI/pages/storage/get-background-fetch-data/get-background-fetch-data.js
@@ -25,7 +25,7 @@ Page({
fetchType: 'periodic',
success(res) {
console.log(res)
- const {fetchedData} = res
+ const { fetchedData } = res
const result = JSON.parse(fetchedData)
that.setData({
appid: result.appid,
@@ -60,12 +60,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/storage/get-background-prefetch-data/get-background-prefetch-data.js b/miniprogram/packageAPI/pages/storage/get-background-prefetch-data/get-background-prefetch-data.js
index 4cef2ed3..07a13389 100644
--- a/miniprogram/packageAPI/pages/storage/get-background-prefetch-data/get-background-prefetch-data.js
+++ b/miniprogram/packageAPI/pages/storage/get-background-prefetch-data/get-background-prefetch-data.js
@@ -44,7 +44,7 @@ Page({
if (wx.getBackgroundFetchData) {
console.log('读取预拉取数据')
const res = app.globalData.backgroundFetchData
- const {fetchedData} = res
+ const { fetchedData } = res
const result = JSON.parse(fetchedData)
const systemInfo = wx.getSystemInfoSync()
const timeStamp = systemInfo.brand === 'iPhone' ? res.timeStamp * 1000 : res.timeStamp
@@ -71,11 +71,11 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/storage/storage/storage.js b/miniprogram/packageAPI/pages/storage/storage/storage.js
index 6f7ec126..a77326fe 100644
--- a/miniprogram/packageAPI/pages/storage/storage/storage.js
+++ b/miniprogram/packageAPI/pages/storage/storage/storage.js
@@ -26,7 +26,7 @@ Page({
},
getStorage() {
- const {key, data} = this.data
+ const { key, data } = this.data
let storageData
if (key.length === 0) {
@@ -64,7 +64,7 @@ Page({
},
setStorage() {
- const {key, data} = this.data
+ const { key, data } = this.data
if (key.length === 0) {
this.setData({
key,
@@ -104,12 +104,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageAPI/pages/worker/worker/worker.js b/miniprogram/packageAPI/pages/worker/worker/worker.js
index c5b0ce63..5e1d60d1 100644
--- a/miniprogram/packageAPI/pages/worker/worker/worker.js
+++ b/miniprogram/packageAPI/pages/worker/worker/worker.js
@@ -1,4 +1,4 @@
-const {fib} = require('../../../../util/util.js')
+const { fib } = require('../../../../util/util.js')
Page({
onShareAppMessage() {
@@ -18,29 +18,27 @@ Page({
if (wx.offThemeChange) {
wx.offThemeChange()
}
+ clearInterval(this.interval)
+ if (this._worker) this._worker.terminate()
},
+
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this._worker = wx.createWorker('workers/fib/index.js')
},
- onUnload() {
- clearInterval(this.interval)
- if (this._worker) this._worker.terminate()
- },
-
bindInput(e) {
const val = Number(e.detail.value)
- if (val > 40) return {value: 40}
- if (Number.isNaN(val)) return {value: 33}
+ if (val > 40) return { value: 40 }
+ if (Number.isNaN(val)) return { value: 33 }
this.setData({
input: val
})
@@ -48,7 +46,7 @@ Page({
},
reset() {
- this.setData({res: ''})
+ this.setData({ res: '' })
},
compute() {
diff --git a/miniprogram/packageAPI/pages/worker/worker/worker/worker.js b/miniprogram/packageAPI/pages/worker/worker/worker/worker.js
index bfda3297..8f3d260a 100644
--- a/miniprogram/packageAPI/pages/worker/worker/worker/worker.js
+++ b/miniprogram/packageAPI/pages/worker/worker/worker/worker.js
@@ -12,56 +12,56 @@ Page({
/**
* 生命周期函数--监听页面加载
*/
- onLoad: function (options) {
+ onLoad(options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
- onReady: function () {
+ onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
- onShow: function () {
+ onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
- onHide: function () {
+ onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
- onUnload: function () {
+ onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
- onPullDownRefresh: function () {
+ onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
- onReachBottom: function () {
+ onReachBottom() {
},
/**
* 用户点击右上角分享
*/
- onShareAppMessage: function () {
+ onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageChatTool/components/apiCategory/index.js b/miniprogram/packageChatTool/components/apiCategory/index.js
index a9b4b70c..d2775c04 100644
--- a/miniprogram/packageChatTool/components/apiCategory/index.js
+++ b/miniprogram/packageChatTool/components/apiCategory/index.js
@@ -11,7 +11,7 @@ Component({
data: {
apiCategory: '',
},
-
+
methods: {
},
@@ -19,7 +19,7 @@ Component({
pageLifetimes: {
show() {
const apiCategory = wx.getApiCategory()
- this.setData({apiCategory})
+ this.setData({ apiCategory })
}
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageChatTool/pages/activity_create/index.js b/miniprogram/packageChatTool/pages/activity_create/index.js
index 26834fc5..4f64a1cc 100644
--- a/miniprogram/packageChatTool/pages/activity_create/index.js
+++ b/miniprogram/packageChatTool/pages/activity_create/index.js
@@ -79,34 +79,34 @@ Page({
},
showPicker(e) {
- const { mode } = e.currentTarget.dataset;
+ const { mode } = e.currentTarget.dataset
this.setData({
mode,
[`${mode}Visible`]: true,
- });
+ })
},
hidePicker() {
- const { mode } = this.data;
+ const { mode } = this.data
this.setData({
[`${mode}Visible`]: false,
- });
+ })
},
onConfirm(e) {
- const { value } = e.detail;
- const { mode, dateOption } = this.data;
+ const { value } = e.detail
+ const { mode, dateOption } = this.data
- console.log('confirm', value);
+ console.log('confirm', value)
this.setData({
[mode]: value,
[`${mode}Text${dateOption}`]: value,
- });
+ })
- this.hidePicker();
+ this.hidePicker()
},
onColumnChange(e) {
- console.log('pick', e.detail.value);
+ console.log('pick', e.detail.value)
},
chooseShareImage() {
@@ -125,7 +125,7 @@ Page({
wx.cloud.uploadFile({
cloudPath: `image-${Date.now()}.png`, // 上传至云端的路径
- filePath: shareImage,
+ filePath: shareImage,
success: res => {
// 返回文件 ID
console.log('uploadFile: ', res.fileID)
@@ -220,7 +220,6 @@ Page({
if (!activityId) {
this.createActivityID(() => {
this.publish()
- return
})
}
@@ -270,7 +269,7 @@ Page({
})
},
fail(res) {
- console.info("updateShareMenu fail: ", res)
+ console.info('updateShareMenu fail: ', res)
wx.showToast({
title: '分享失败',
icon: 'none'
@@ -293,4 +292,4 @@ Page({
})
})
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageChatTool/pages/activity_detail/index.js b/miniprogram/packageChatTool/pages/activity_detail/index.js
index f635c0d7..adaca218 100644
--- a/miniprogram/packageChatTool/pages/activity_detail/index.js
+++ b/miniprogram/packageChatTool/pages/activity_detail/index.js
@@ -5,7 +5,7 @@ const roleType = ['unkown', 'owner', 'participant', 'nonParticipant']
const activityStatus = ['未开始', '进行中', '已结束']
-const {envVersion} = wx.getAccountInfoSync().miniProgram
+const { envVersion } = wx.getAccountInfoSync().miniProgram
const getVersionType = () => {
if (envVersion === 'release') {
@@ -77,12 +77,11 @@ Page({
console.log('onAbort', e)
},
-
onGoHome() {
wx.reLaunch({
url: '/packageAPI/pages/chattool/activity_assist/activity_assist',
complete(res) {
- console.info("relaunch", res)
+ console.info('relaunch', res)
}
})
},
@@ -155,7 +154,6 @@ Page({
console.info('fetchActivity fail: ', err)
})
})
-
},
onTabsChange(e) {
@@ -255,7 +253,7 @@ Page({
action: 'updateChatToolMsg',
activityId: this.data.activityId,
targetState: targetState || 1,
- templateId: templateId,
+ templateId,
parameterList: parameterList || [],
versionType: getVersionType()
}
@@ -270,7 +268,7 @@ Page({
const that = this
setTimeout(() => {
this.createSelectorQuery()
- .select("#target")
+ .select('#target')
.node()
.exec(res => {
const node = res[0].node
@@ -295,7 +293,7 @@ Page({
},
sendProgress() {
- const { progressImage, activityId} = this.data
+ const { progressImage, activityId } = this.data
const entrancePath = `packageChatTool/pages/activity_detail/index?activityId=${activityId}`
wx.shareImageToGroup({
imagePath: progressImage,
@@ -323,4 +321,4 @@ Page({
fail: console.error
})
},
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageChatTool/util.js b/miniprogram/packageChatTool/util.js
index 92fa5c0d..258fa8fd 100644
--- a/miniprogram/packageChatTool/util.js
+++ b/miniprogram/packageChatTool/util.js
@@ -34,8 +34,8 @@ export function getChatToolInfo() {
reject(res)
},
complete(res) {
- console.info('getChatToolInfo complete: ',res)
+ console.info('getChatToolInfo complete: ', res)
}
})
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageCloud/pages/database/crud/crud.js b/miniprogram/packageCloud/pages/database/crud/crud.js
index 351496c1..68105246 100644
--- a/miniprogram/packageCloud/pages/database/crud/crud.js
+++ b/miniprogram/packageCloud/pages/database/crud/crud.js
@@ -28,12 +28,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (app.globalData.openid) {
@@ -74,12 +74,12 @@ Page({
if (this.data.loading) {
return
}
- const {newContent} = this.data
+ const { newContent } = this.data
if (!newContent) {
return
}
- this.setData({loading: true})
+ this.setData({ loading: true })
const db = wx.cloud.database()
db.collection('todos').add({
data: {
@@ -113,7 +113,7 @@ Page({
console.error('[数据库] [新增记录] 失败:', err)
},
complete: () => {
- this.setData({loading: false})
+ this.setData({ loading: false })
}
})
},
@@ -148,7 +148,7 @@ Page({
},
searchTodo() {
- const {searchContent} = this.data
+ const { searchContent } = this.data
if (!searchContent) {
this.queryTodoList()
return
@@ -194,13 +194,13 @@ Page({
if (this.data.loading) {
return
}
- const {id: todoId, index} = e.currentTarget.dataset
+ const { id: todoId, index } = e.currentTarget.dataset
const todo = this.data.todoList[index]
- this.setData({loading: true})
+ this.setData({ loading: true })
const db = wx.cloud.database()
db.collection('todos').doc(todoId).update({
- data: {done: !todo.done},
+ data: { done: !todo.done },
success: () => {
this.setData({
[`todoList[${index}].done`]: !todo.done
@@ -214,13 +214,13 @@ Page({
console.error('[数据库] [更新记录] 失败:', err)
},
complete: () => {
- this.setData({loading: false})
+ this.setData({ loading: false })
}
})
},
toDetail(e) {
- const {id: todoId} = e.currentTarget.dataset
+ const { id: todoId } = e.currentTarget.dataset
wx.navigateTo({
url: `/page/cloud/pages/crud-detail/crud-detail?todoId=${todoId}`,
})
diff --git a/miniprogram/packageCloud/pages/database/db-permission/db-permission.js b/miniprogram/packageCloud/pages/database/db-permission/db-permission.js
index 97cf0750..617198d8 100644
--- a/miniprogram/packageCloud/pages/database/db-permission/db-permission.js
+++ b/miniprogram/packageCloud/pages/database/db-permission/db-permission.js
@@ -47,12 +47,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (app.globalData.openid) {
@@ -127,7 +127,7 @@ Page({
},
bindInput(e) {
- const {name} = e.currentTarget.dataset
+ const { name } = e.currentTarget.dataset
this.setData({
[name]: e.detail.value
})
@@ -235,7 +235,7 @@ Page({
data,
success: res => {
console.log('[数据库] [新增记录] 成功:', res)
- if (successCallback) successCallback.call(this, {_id: res._id})
+ if (successCallback) successCallback.call(this, { _id: res._id })
},
fail: err => {
if (showError) this.showErrorModal('设置', err)
diff --git a/miniprogram/packageCloud/pages/database/server-date/server-date.js b/miniprogram/packageCloud/pages/database/server-date/server-date.js
index 3401e762..1bb3910b 100644
--- a/miniprogram/packageCloud/pages/database/server-date/server-date.js
+++ b/miniprogram/packageCloud/pages/database/server-date/server-date.js
@@ -31,12 +31,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (app.globalData.openid) {
@@ -82,7 +82,7 @@ Page({
insertOrUpdateData(existedData, data) {
const db = wx.cloud.database()
if (existedData._id) {
- db.collection(collection).doc(existedData._id).update({data})
+ db.collection(collection).doc(existedData._id).update({ data })
.then(res => {
this.setCompletedData(existedData._id)
return res
@@ -93,7 +93,7 @@ Page({
this.completeTask()
})
} else {
- db.collection(collection).add({data})
+ db.collection(collection).add({ data })
.then(res => {
this.setCompletedData(res._id)
return res
diff --git a/miniprogram/packageCloud/pages/nouse/crud-detail/crud-detail.js b/miniprogram/packageCloud/pages/nouse/crud-detail/crud-detail.js
index 0da36b13..e38a8c98 100644
--- a/miniprogram/packageCloud/pages/nouse/crud-detail/crud-detail.js
+++ b/miniprogram/packageCloud/pages/nouse/crud-detail/crud-detail.js
@@ -19,7 +19,7 @@ Page({
},
onLoad(options) {
- const {todoId} = options
+ const { todoId } = options
this.setData({
todoId
})
@@ -77,12 +77,12 @@ Page({
if (this.data.updating || !this.data.todoId) {
return
}
- const {todoId, description} = this.data
+ const { todoId, description } = this.data
if (!description) {
return
}
- this.setData({updating: true})
+ this.setData({ updating: true })
const db = wx.cloud.database()
db.collection('todos').doc(todoId).update({
data: {
@@ -103,7 +103,7 @@ Page({
console.error('[数据库] [更新记录] 失败:', err)
},
complete: () => {
- this.setData({updating: false})
+ this.setData({ updating: false })
}
})
},
@@ -112,9 +112,9 @@ Page({
if (this.data.deleting || !this.data.todoId) {
return
}
- const {todoId} = this.data
+ const { todoId } = this.data
- this.setData({deleting: true})
+ this.setData({ deleting: true })
const db = wx.cloud.database()
db.collection('todos').doc(todoId).remove({
success: () => {
@@ -131,7 +131,7 @@ Page({
console.error('[数据库] [删除记录] 失败:', err)
},
complete: () => {
- this.setData({deleting: false})
+ this.setData({ deleting: false })
}
})
},
diff --git a/miniprogram/packageCloud/pages/scf/get-wx-context/get-wx-context.js b/miniprogram/packageCloud/pages/scf/get-wx-context/get-wx-context.js
index 685c5d4b..322474e8 100644
--- a/miniprogram/packageCloud/pages/scf/get-wx-context/get-wx-context.js
+++ b/miniprogram/packageCloud/pages/scf/get-wx-context/get-wx-context.js
@@ -49,12 +49,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js b/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js
index bd2d37f7..f621e76f 100644
--- a/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js
+++ b/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js
@@ -26,12 +26,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js b/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js
index c45b0aaf..0a0bb707 100644
--- a/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js
+++ b/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js
@@ -26,12 +26,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js b/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js
index d123ecdf..7ce7bd2b 100644
--- a/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js
+++ b/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js
@@ -27,12 +27,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
diff --git a/miniprogram/packageCloud/pages/storage/cloud-file-component/cloud-file-component.js b/miniprogram/packageCloud/pages/storage/cloud-file-component/cloud-file-component.js
index dc1e3c6d..f4f785b5 100644
--- a/miniprogram/packageCloud/pages/storage/cloud-file-component/cloud-file-component.js
+++ b/miniprogram/packageCloud/pages/storage/cloud-file-component/cloud-file-component.js
@@ -1,4 +1,4 @@
-const {demoImageFileId, demoVideoFileId} = require('../../../../config')
+const { demoImageFileId, demoVideoFileId } = require('../../../../config')
Page({
onShareAppMessage() {
@@ -20,12 +20,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js b/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js
index 06f75a94..74223819 100644
--- a/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js
+++ b/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js
@@ -23,12 +23,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
diff --git a/miniprogram/packageCloud/pages/storage/download-file/download-file.js b/miniprogram/packageCloud/pages/storage/download-file/download-file.js
index c9aa920d..c63a2a5e 100644
--- a/miniprogram/packageCloud/pages/storage/download-file/download-file.js
+++ b/miniprogram/packageCloud/pages/storage/download-file/download-file.js
@@ -27,12 +27,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
diff --git a/miniprogram/packageCloud/pages/storage/get-temp-file-url/get-temp-file-url.js b/miniprogram/packageCloud/pages/storage/get-temp-file-url/get-temp-file-url.js
index 47e6da72..c76a8a2b 100644
--- a/miniprogram/packageCloud/pages/storage/get-temp-file-url/get-temp-file-url.js
+++ b/miniprogram/packageCloud/pages/storage/get-temp-file-url/get-temp-file-url.js
@@ -28,12 +28,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.setData({
diff --git a/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js b/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js
index 682227ee..8541c82f 100644
--- a/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js
+++ b/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js
@@ -24,12 +24,12 @@ Page({
},
onLoad(options) {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (options.from) {
@@ -85,7 +85,7 @@ Page({
wx.hideLoading()
})
},
- fail({errMsg}) {
+ fail({ errMsg }) {
console.log('chooseImage fail, err is', errMsg)
}
})
diff --git a/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js b/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js
index 1ee8c6e1..b89abdc0 100644
--- a/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js
+++ b/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js
@@ -43,12 +43,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js b/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js
index 07616752..7f52f326 100644
--- a/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js
+++ b/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js
@@ -1,4 +1,4 @@
-import {compareVersion} from '../../../../util/util'
+import { compareVersion } from '../../../../util/util'
Page({
onShareAppMessage() {
@@ -18,7 +18,7 @@ Page({
},
_onReady() {
// 解决基础库小于 2.7.0 的兼容问题
- const {SDKVersion} = wx.getSystemInfoSync()
+ const { SDKVersion } = wx.getSystemInfoSync()
console.log(SDKVersion)
if (compareVersion(SDKVersion, '2.7.0') < 0) {
console.log('123')
@@ -135,12 +135,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/canvas/canvas/canvas.js b/miniprogram/packageComponent/pages/canvas/canvas/canvas.js
index b671fd4e..c7dfc578 100644
--- a/miniprogram/packageComponent/pages/canvas/canvas/canvas.js
+++ b/miniprogram/packageComponent/pages/canvas/canvas/canvas.js
@@ -1,4 +1,4 @@
-import {compareVersion} from '../../../../util/util'
+import { compareVersion } from '../../../../util/util'
Page({
@@ -11,7 +11,7 @@ Page({
},
onReady() {
// 解决基础库小于 2.7.0 的兼容问题
- const {SDKVersion} = wx.getSystemInfoSync()
+ const { SDKVersion } = wx.getSystemInfoSync()
if (compareVersion(SDKVersion, '2.7.0') < 0) {
console.log('123')
this.setData({
@@ -34,49 +34,49 @@ Page({
/**
* 生命周期函数--监听页面初次渲染完成
*/
- onReady: function () {
+ onReady() {
},
/**
* 生命周期函数--监听页面显示
*/
- onShow: function () {
+ onShow() {
},
/**
* 生命周期函数--监听页面隐藏
*/
- onHide: function () {
+ onHide() {
},
/**
* 生命周期函数--监听页面卸载
*/
- onUnload: function () {
+ onUnload() {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
- onPullDownRefresh: function () {
+ onPullDownRefresh() {
},
/**
* 页面上拉触底事件的处理函数
*/
- onReachBottom: function () {
+ onReachBottom() {
},
/**
* 用户点击右上角分享
*/
- onShareAppMessage: function () {
+ onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/canvas/webgl/webgl.js b/miniprogram/packageComponent/pages/canvas/webgl/webgl.js
index c38723cf..602c617b 100644
--- a/miniprogram/packageComponent/pages/canvas/webgl/webgl.js
+++ b/miniprogram/packageComponent/pages/canvas/webgl/webgl.js
@@ -1,4 +1,4 @@
-import {compareVersion} from '../../../../util/util'
+import { compareVersion } from '../../../../util/util'
// WebGL
const vs = `
@@ -42,7 +42,7 @@ Page({
},
onReady() {
// 解决基础库小于 2.7.0 的兼容问题
- const {SDKVersion} = wx.getSystemInfoSync()
+ const { SDKVersion } = wx.getSystemInfoSync()
if (compareVersion(SDKVersion, '2.7.0') < 0) {
console.log('123')
this.setData({
@@ -129,12 +129,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/content/icon/icon.js b/miniprogram/packageComponent/pages/content/icon/icon.js
index 11c19901..9958c37e 100644
--- a/miniprogram/packageComponent/pages/content/icon/icon.js
+++ b/miniprogram/packageComponent/pages/content/icon/icon.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/content/progress/progress.js b/miniprogram/packageComponent/pages/content/progress/progress.js
index 679b7190..f84f7c22 100644
--- a/miniprogram/packageComponent/pages/content/progress/progress.js
+++ b/miniprogram/packageComponent/pages/content/progress/progress.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/content/rich-text/rich-text.js b/miniprogram/packageComponent/pages/content/rich-text/rich-text.js
index 67e3b5dd..8850be01 100644
--- a/miniprogram/packageComponent/pages/content/rich-text/rich-text.js
+++ b/miniprogram/packageComponent/pages/content/rich-text/rich-text.js
@@ -74,12 +74,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/content/selection/selection.js b/miniprogram/packageComponent/pages/content/selection/selection.js
index abf4afcc..c29a6aa8 100644
--- a/miniprogram/packageComponent/pages/content/selection/selection.js
+++ b/miniprogram/packageComponent/pages/content/selection/selection.js
@@ -30,12 +30,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageComponent/pages/content/text/text.js b/miniprogram/packageComponent/pages/content/text/text.js
index 44a49667..1b2ccf09 100644
--- a/miniprogram/packageComponent/pages/content/text/text.js
+++ b/miniprogram/packageComponent/pages/content/text/text.js
@@ -69,12 +69,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/button/button.js b/miniprogram/packageComponent/pages/form/button/button.js
index e22d9263..dd8a5a27 100644
--- a/miniprogram/packageComponent/pages/form/button/button.js
+++ b/miniprogram/packageComponent/pages/form/button/button.js
@@ -76,12 +76,12 @@ const pageObject = {
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
if (wx.getUserProfile) {
diff --git a/miniprogram/packageComponent/pages/form/checkbox/checkbox.js b/miniprogram/packageComponent/pages/form/checkbox/checkbox.js
index ccfa0e05..9cd716b5 100644
--- a/miniprogram/packageComponent/pages/form/checkbox/checkbox.js
+++ b/miniprogram/packageComponent/pages/form/checkbox/checkbox.js
@@ -9,12 +9,12 @@ Page({
data: {
theme: 'light',
items: [
- {value: 'USA', name: '美国'},
- {value: 'CHN', name: '中国', checked: 'true'},
- {value: 'BRA', name: '巴西'},
- {value: 'JPN', name: '日本'},
- {value: 'ENG', name: '英国'},
- {value: 'FRA', name: '法国'}
+ { value: 'USA', name: '美国' },
+ { value: 'CHN', name: '中国', checked: 'true' },
+ { value: 'BRA', name: '巴西' },
+ { value: 'JPN', name: '日本' },
+ { value: 'ENG', name: '英国' },
+ { value: 'FRA', name: '法国' }
]
},
@@ -45,12 +45,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/editor/editor.js b/miniprogram/packageComponent/pages/form/editor/editor.js
index a695555f..c09469e1 100644
--- a/miniprogram/packageComponent/pages/form/editor/editor.js
+++ b/miniprogram/packageComponent/pages/form/editor/editor.js
@@ -27,12 +27,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
const {
@@ -46,7 +46,7 @@ Page({
}
this._safeHeight = safeHeight
const isIOS = platform === 'ios'
- this.setData({isIOS, safeHeight, toolBarHeight: isIOS ? safeHeight + 50 : 50})
+ this.setData({ isIOS, safeHeight, toolBarHeight: isIOS ? safeHeight + 50 : 50 })
const that = this
this.updatePosition(0)
let keyboardHeight = 0
@@ -69,7 +69,7 @@ Page({
},
updatePosition(keyboardHeight) {
const toolbarHeight = 50
- const {windowHeight} = wx.getSystemInfoSync()
+ const { windowHeight } = wx.getSystemInfoSync()
let editorHeight = windowHeight
if (keyboardHeight > 0) {
editorHeight = windowHeight - keyboardHeight - toolbarHeight
@@ -92,7 +92,7 @@ Page({
},
calNavigationBarAndStatusBar() {
const systemInfo = wx.getSystemInfoSync()
- const {statusBarHeight, platform} = systemInfo
+ const { statusBarHeight, platform } = systemInfo
const isIOS = platform === 'ios'
const navigationBarHeight = isIOS ? 44 : 48
return statusBarHeight + navigationBarHeight
@@ -107,14 +107,14 @@ Page({
this.editorCtx.blur()
},
format(e) {
- const {name, value} = e.target.dataset
+ const { name, value } = e.target.dataset
if (!name) return
// console.log('format', name, value)
this.editorCtx.format(name, value)
},
onStatusChange(e) {
const formats = e.detail
- this.setData({formats})
+ this.setData({ formats })
},
insertDivider() {
this.editorCtx.insertDivider({
diff --git a/miniprogram/packageComponent/pages/form/form/form.js b/miniprogram/packageComponent/pages/form/form/form.js
index 13ae8736..f105bd3c 100644
--- a/miniprogram/packageComponent/pages/form/form/form.js
+++ b/miniprogram/packageComponent/pages/form/form/form.js
@@ -50,12 +50,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/input/input.js b/miniprogram/packageComponent/pages/form/input/input.js
index 5ee276f4..c324031b 100644
--- a/miniprogram/packageComponent/pages/form/input/input.js
+++ b/miniprogram/packageComponent/pages/form/input/input.js
@@ -10,7 +10,7 @@ Page({
theme: 'light',
focus: false,
inputValue: '',
- style: {color: '#F76260', fontSize: 16},
+ style: { color: '#F76260', fontSize: 16 },
},
bindKeyInput(e) {
@@ -53,12 +53,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/label/label.js b/miniprogram/packageComponent/pages/form/label/label.js
index f63ac2ae..2b220b9e 100644
--- a/miniprogram/packageComponent/pages/form/label/label.js
+++ b/miniprogram/packageComponent/pages/form/label/label.js
@@ -9,12 +9,12 @@ Page({
data: {
theme: 'light',
checkboxItems: [
- {name: 'USA', value: '美国'},
- {name: 'CHN', value: '中国', checked: 'true'}
+ { name: 'USA', value: '美国' },
+ { name: 'CHN', value: '中国', checked: 'true' }
],
radioItems: [
- {name: 'USA', value: '美国'},
- {name: 'CHN', value: '中国', checked: 'true'}
+ { name: 'USA', value: '美国' },
+ { name: 'CHN', value: '中国', checked: 'true' }
],
hidden: false
},
@@ -55,12 +55,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/picker-view/picker-view.js b/miniprogram/packageComponent/pages/form/picker-view/picker-view.js
index 0ee2a0a2..f25dabdf 100644
--- a/miniprogram/packageComponent/pages/form/picker-view/picker-view.js
+++ b/miniprogram/packageComponent/pages/form/picker-view/picker-view.js
@@ -51,12 +51,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/picker/picker.js b/miniprogram/packageComponent/pages/form/picker/picker.js
index 7e8a81f9..610cdf25 100644
--- a/miniprogram/packageComponent/pages/form/picker/picker.js
+++ b/miniprogram/packageComponent/pages/form/picker/picker.js
@@ -39,12 +39,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/radio/radio.js b/miniprogram/packageComponent/pages/form/radio/radio.js
index bf3e8b4b..fcc918d7 100644
--- a/miniprogram/packageComponent/pages/form/radio/radio.js
+++ b/miniprogram/packageComponent/pages/form/radio/radio.js
@@ -9,12 +9,12 @@ Page({
data: {
theme: 'light',
items: [
- {value: 'USA', name: '美国'},
- {value: 'CHN', name: '中国', checked: 'true'},
- {value: 'BRA', name: '巴西'},
- {value: 'JPN', name: '日本'},
- {value: 'ENG', name: '英国'},
- {value: 'FRA', name: '法国'},
+ { value: 'USA', name: '美国' },
+ { value: 'CHN', name: '中国', checked: 'true' },
+ { value: 'BRA', name: '巴西' },
+ { value: 'JPN', name: '日本' },
+ { value: 'ENG', name: '英国' },
+ { value: 'FRA', name: '法国' },
]
},
@@ -37,12 +37,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/slider/slider.js b/miniprogram/packageComponent/pages/form/slider/slider.js
index 15286272..d960adfe 100644
--- a/miniprogram/packageComponent/pages/form/slider/slider.js
+++ b/miniprogram/packageComponent/pages/form/slider/slider.js
@@ -15,12 +15,12 @@ const pageData = {
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/switch/switch.js b/miniprogram/packageComponent/pages/form/switch/switch.js
index e62bdf64..ae2d5e06 100644
--- a/miniprogram/packageComponent/pages/form/switch/switch.js
+++ b/miniprogram/packageComponent/pages/form/switch/switch.js
@@ -23,12 +23,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/form/textarea/textarea.js b/miniprogram/packageComponent/pages/form/textarea/textarea.js
index 9a7cc173..9f58017b 100644
--- a/miniprogram/packageComponent/pages/form/textarea/textarea.js
+++ b/miniprogram/packageComponent/pages/form/textarea/textarea.js
@@ -21,12 +21,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/map/map/map.js b/miniprogram/packageComponent/pages/map/map/map.js
index ae98a5af..8351789c 100644
--- a/miniprogram/packageComponent/pages/map/map/map.js
+++ b/miniprogram/packageComponent/pages/map/map/map.js
@@ -96,12 +96,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/media/camera/camera.js b/miniprogram/packageComponent/pages/media/camera/camera.js
index 47f5e1ec..f3dab07b 100644
--- a/miniprogram/packageComponent/pages/media/camera/camera.js
+++ b/miniprogram/packageComponent/pages/media/camera/camera.js
@@ -111,14 +111,11 @@ function createRenderer(canvas, width, height) {
return (arrayBuffer, width, height) => {
gl.bindTexture(gl.TEXTURE_2D, texture)
- gl.texImage2D(
- gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, arrayBuffer
- )
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, arrayBuffer)
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0)
}
}
-
Page({
onShareAppMessage() {
return {
@@ -232,12 +229,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/media/channel-live/channel-live.js b/miniprogram/packageComponent/pages/media/channel-live/channel-live.js
index 14e69279..e135a045 100644
--- a/miniprogram/packageComponent/pages/media/channel-live/channel-live.js
+++ b/miniprogram/packageComponent/pages/media/channel-live/channel-live.js
@@ -2,11 +2,11 @@ const app = getApp()
Page({
data: {
- feedId: 'export/UzFfAgtgekIEAQAAAAAAQ3s56WvdaQAAAAstQy6ubaLX4KHWvLEZgBPEjYMcaThvAvSDzNPgMJpU00S4DKmOC1N5VwE8t9F-'
+ feedId: 'export/UzFfAgtgekIEAQAAAAAAQ3s56WvdaQAAAAstQy6ubaLX4KHWvLEZgBPEjYMcaThvAvSDzNPgMJpU00S4DKmOC1N5VwE8t9F-'
},
onLoad() {
- // this.getliveinfo()
- // this.openlive()
+ // this.getliveinfo()
+ // this.openlive()
console.log('代码片段是一种迷你、可分享的小程序或小游戏项目,可用于分享小程序和小游戏的开发经验、展示组件和 API 的使用、复现开发问题和 Bug 等。可点击以下链接查看代码片段的详细文档:')
console.log('https://mp.weixin.qq.com/debug/wxadoc/dev/devtools/devtools.html')
},
diff --git a/miniprogram/packageComponent/pages/media/channel-video/channel-video.js b/miniprogram/packageComponent/pages/media/channel-video/channel-video.js
index 0b0feada..0cad242f 100644
--- a/miniprogram/packageComponent/pages/media/channel-video/channel-video.js
+++ b/miniprogram/packageComponent/pages/media/channel-video/channel-video.js
@@ -5,7 +5,7 @@ Page({
* 页面的初始数据
*/
data: {
- feedId: 'export/UzFfAgtgekIEAQAAAAAAQ3s56WvdaQAAAAstQy6ubaLX4KHWvLEZgBPEjYMcaThvAvSDzNPgMJpU00S4DKmOC1N5VwE8t9F-'
+ feedId: 'export/UzFfAgtgekIEAQAAAAAAQ3s56WvdaQAAAAstQy6ubaLX4KHWvLEZgBPEjYMcaThvAvSDzNPgMJpU00S4DKmOC1N5VwE8t9F-'
},
/**
@@ -63,4 +63,4 @@ Page({
onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/media/image/image.js b/miniprogram/packageComponent/pages/media/image/image.js
index fbf48206..d7c73e18 100644
--- a/miniprogram/packageComponent/pages/media/image/image.js
+++ b/miniprogram/packageComponent/pages/media/image/image.js
@@ -1,4 +1,3 @@
-
Page({
onShareAppMessage() {
return {
@@ -13,12 +12,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
wx.cloud.getTempFileURL({
diff --git a/miniprogram/packageComponent/pages/media/live-player/live-player.js b/miniprogram/packageComponent/pages/media/live-player/live-player.js
index d257e6e8..d35eab2e 100644
--- a/miniprogram/packageComponent/pages/media/live-player/live-player.js
+++ b/miniprogram/packageComponent/pages/media/live-player/live-player.js
@@ -15,7 +15,7 @@ Page({
handleScanQRCode() {
wx.scanCode({
complete: (res) => {
- const {result} = res
+ const { result } = res
this.setData({
videoSrc: result
})
@@ -90,12 +90,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/media/live-pusher/live-pusher.js b/miniprogram/packageComponent/pages/media/live-pusher/live-pusher.js
index 07cf04a8..fec24df3 100644
--- a/miniprogram/packageComponent/pages/media/live-pusher/live-pusher.js
+++ b/miniprogram/packageComponent/pages/media/live-pusher/live-pusher.js
@@ -31,7 +31,7 @@ Page({
handleScanQRCode() {
wx.scanCode({
complete: (res) => {
- const {result} = res
+ const { result } = res
this.setData({
videoSrc: result
})
@@ -90,12 +90,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/media/video/picture-in-picture.js b/miniprogram/packageComponent/pages/media/video/picture-in-picture.js
index d18aff8d..a7faab3d 100644
--- a/miniprogram/packageComponent/pages/media/video/picture-in-picture.js
+++ b/miniprogram/packageComponent/pages/media/video/picture-in-picture.js
@@ -9,15 +9,14 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
-
},
onReady() {
diff --git a/miniprogram/packageComponent/pages/media/video/video.js b/miniprogram/packageComponent/pages/media/video/video.js
index 4f6cd7ad..7a79ccb7 100644
--- a/miniprogram/packageComponent/pages/media/video/video.js
+++ b/miniprogram/packageComponent/pages/media/video/video.js
@@ -93,12 +93,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/nav/navigator/navigate.js b/miniprogram/packageComponent/pages/nav/navigator/navigate.js
index 87a5e0e4..fea3fc29 100644
--- a/miniprogram/packageComponent/pages/nav/navigator/navigate.js
+++ b/miniprogram/packageComponent/pages/nav/navigator/navigate.js
@@ -15,12 +15,12 @@ Page({
},
onLoad(options) {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/nav/navigator/navigator.js b/miniprogram/packageComponent/pages/nav/navigator/navigator.js
index d90e8905..e5b301d2 100644
--- a/miniprogram/packageComponent/pages/nav/navigator/navigator.js
+++ b/miniprogram/packageComponent/pages/nav/navigator/navigator.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/nav/navigator/redirect.js b/miniprogram/packageComponent/pages/nav/navigator/redirect.js
index 94202e81..cff3bc03 100644
--- a/miniprogram/packageComponent/pages/nav/navigator/redirect.js
+++ b/miniprogram/packageComponent/pages/nav/navigator/redirect.js
@@ -15,12 +15,12 @@ Page({
},
onLoad(options) {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
console.log(options)
diff --git a/miniprogram/packageComponent/pages/obstacle-free/aria-component/aria-component.js b/miniprogram/packageComponent/pages/obstacle-free/aria-component/aria-component.js
index 139be091..2d3fa45d 100644
--- a/miniprogram/packageComponent/pages/obstacle-free/aria-component/aria-component.js
+++ b/miniprogram/packageComponent/pages/obstacle-free/aria-component/aria-component.js
@@ -16,12 +16,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/official-account/official-account.js b/miniprogram/packageComponent/pages/official-account/official-account.js
index d2c55547..0b22cab6 100644
--- a/miniprogram/packageComponent/pages/official-account/official-account.js
+++ b/miniprogram/packageComponent/pages/official-account/official-account.js
@@ -12,22 +12,16 @@ Page({
/**
* 生命周期函数--监听页面加载
*/
- onUnload() {
- if (wx.offThemeChange) {
- wx.offThemeChange()
- }
- },
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
-
},
/**
@@ -55,7 +49,9 @@ Page({
* 生命周期函数--监听页面卸载
*/
onUnload() {
-
+ if (wx.offThemeChange) {
+ wx.offThemeChange()
+ }
},
/**
diff --git a/miniprogram/packageComponent/pages/open/ad/ad.js b/miniprogram/packageComponent/pages/open/ad/ad.js
index 1f675868..125b25cd 100644
--- a/miniprogram/packageComponent/pages/open/ad/ad.js
+++ b/miniprogram/packageComponent/pages/open/ad/ad.js
@@ -20,36 +20,36 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
const res = wx.getExptInfoSync(['expt_args_2'])
if (res.expt_args_2 === undefined) {
- // 返回空对象;未命中实验、实验待发布(白名单除外)或者实验结束后会命中该分支
- /* 业务逻辑,可对齐线上 */
+ // 返回空对象;未命中实验、实验待发布(白名单除外)或者实验结束后会命中该分支
+ /* 业务逻辑,可对齐线上 */
} else if (res.expt_args_2 == '0') {
- /* 对照组业务逻辑 */
- this.setData({
- index: 1
- })
+ /* 对照组业务逻辑 */
+ this.setData({
+ index: 1
+ })
} else if (res.expt_args_2 == '1') {
- /* 实验组1业务逻辑 */
- this.setData({
- index: 2
- })
+ /* 实验组1业务逻辑 */
+ this.setData({
+ index: 2
+ })
} else if (res.expt_args_2 == '2') {
- /* 实验组2业务逻辑 */
- this.setData({
- index: 3
- })
+ /* 实验组2业务逻辑 */
+ this.setData({
+ index: 3
+ })
} else {
- /* 异常分支逻辑 */
- console.log('error')
- }
+ /* 异常分支逻辑 */
+ console.log('error')
+ }
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/open/open-data/open-data.js b/miniprogram/packageComponent/pages/open/open-data/open-data.js
index 33966b40..5c718e9b 100644
--- a/miniprogram/packageComponent/pages/open/open-data/open-data.js
+++ b/miniprogram/packageComponent/pages/open/open-data/open-data.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/open/web-view/web-view.js b/miniprogram/packageComponent/pages/open/web-view/web-view.js
index 14bae8ee..ec119030 100644
--- a/miniprogram/packageComponent/pages/open/web-view/web-view.js
+++ b/miniprogram/packageComponent/pages/open/web-view/web-view.js
@@ -15,12 +15,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/view/cover-view/cover-view.js b/miniprogram/packageComponent/pages/view/cover-view/cover-view.js
index 9937a1d2..e0773595 100644
--- a/miniprogram/packageComponent/pages/view/cover-view/cover-view.js
+++ b/miniprogram/packageComponent/pages/view/cover-view/cover-view.js
@@ -18,12 +18,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/view/grid-view/demo-1/demo-1.js b/miniprogram/packageComponent/pages/view/grid-view/demo-1/demo-1.js
index 2ba43565..8ef26191 100644
--- a/miniprogram/packageComponent/pages/view/grid-view/demo-1/demo-1.js
+++ b/miniprogram/packageComponent/pages/view/grid-view/demo-1/demo-1.js
@@ -67,4 +67,4 @@ Page({
onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/view/grid-view/demo-2/demo-2.js b/miniprogram/packageComponent/pages/view/grid-view/demo-2/demo-2.js
index 2ab17152..df27e831 100644
--- a/miniprogram/packageComponent/pages/view/grid-view/demo-2/demo-2.js
+++ b/miniprogram/packageComponent/pages/view/grid-view/demo-2/demo-2.js
@@ -68,4 +68,4 @@ Page({
onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/view/grid-view/grid-view.js b/miniprogram/packageComponent/pages/view/grid-view/grid-view.js
index fa4e8c34..6b90f6bc 100644
--- a/miniprogram/packageComponent/pages/view/grid-view/grid-view.js
+++ b/miniprogram/packageComponent/pages/view/grid-view/grid-view.js
@@ -10,16 +10,14 @@ Page({
go1() {
wx.navigateTo({
- url: './demo-1/demo-1',
- })
+ url: './demo-1/demo-1',
+ })
},
-
goGrid1() {
wx.navigateTo({
- url: './demo-2/demo-2',
+ url: './demo-2/demo-2',
})
},
-
})
diff --git a/miniprogram/packageComponent/pages/view/match-media/match-media.js b/miniprogram/packageComponent/pages/view/match-media/match-media.js
index 51826421..1eaf2515 100644
--- a/miniprogram/packageComponent/pages/view/match-media/match-media.js
+++ b/miniprogram/packageComponent/pages/view/match-media/match-media.js
@@ -16,12 +16,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/view/movable-view/movable-view.js b/miniprogram/packageComponent/pages/view/movable-view/movable-view.js
index 2c46d624..44560fc7 100644
--- a/miniprogram/packageComponent/pages/view/movable-view/movable-view.js
+++ b/miniprogram/packageComponent/pages/view/movable-view/movable-view.js
@@ -40,12 +40,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/view/page-container/page-container.js b/miniprogram/packageComponent/pages/view/page-container/page-container.js
index 69fbcab3..873e6024 100644
--- a/miniprogram/packageComponent/pages/view/page-container/page-container.js
+++ b/miniprogram/packageComponent/pages/view/page-container/page-container.js
@@ -22,12 +22,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
@@ -51,10 +51,10 @@ Page({
})
},
changeRound() {
- this.setData({round: !this.data.round})
+ this.setData({ round: !this.data.round })
},
changeOverlay() {
- this.setData({overlay: !this.data.overlay, show: true})
+ this.setData({ overlay: !this.data.overlay, show: true })
},
changeOverlayStyle(e) {
let overlayStyle = ''
@@ -69,10 +69,10 @@ Page({
case 'blur':
overlayStyle = 'background-color: rgba(0, 0, 0, 0.7); filter: blur(4px);'
}
- this.setData({overlayStyle, show: true})
+ this.setData({ overlayStyle, show: true })
},
exit() {
- this.setData({show: false})
+ this.setData({ show: false })
},
onBeforeEnter(res) {
console.log(res)
diff --git a/miniprogram/packageComponent/pages/view/root-portal/root-portal.js b/miniprogram/packageComponent/pages/view/root-portal/root-portal.js
index 29f2ac9b..ca05090c 100644
--- a/miniprogram/packageComponent/pages/view/root-portal/root-portal.js
+++ b/miniprogram/packageComponent/pages/view/root-portal/root-portal.js
@@ -13,7 +13,7 @@ Page({
// const b = Math.floor(255 * Math.random())
// item.bg = `background-color: rgb(${r}, ${g}, ${b})`
- const r = Math.floor(Math.random() * (229 - 105) + 105);//生成固定灰色
+ const r = Math.floor(Math.random() * (229 - 105) + 105)// 生成固定灰色
item.bg = `background-color: rgb(${r}, ${r}, ${r})`
items.push(item)
}
diff --git a/miniprogram/packageComponent/pages/view/scroll-view/scroll-view.js b/miniprogram/packageComponent/pages/view/scroll-view/scroll-view.js
index d0d8fbcc..5ebbcfcb 100644
--- a/miniprogram/packageComponent/pages/view/scroll-view/scroll-view.js
+++ b/miniprogram/packageComponent/pages/view/scroll-view/scroll-view.js
@@ -11,12 +11,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
this.animate('#scroll-sample-object1', [{
diff --git a/miniprogram/packageComponent/pages/view/sticky/sticky-header/sticky-header.js b/miniprogram/packageComponent/pages/view/sticky/sticky-header/sticky-header.js
index cb4b31d9..8d0f7910 100644
--- a/miniprogram/packageComponent/pages/view/sticky/sticky-header/sticky-header.js
+++ b/miniprogram/packageComponent/pages/view/sticky/sticky-header/sticky-header.js
@@ -1,7 +1,6 @@
// demo-1/index.js
import { generateList } from '../../../../../util/util'
-
Page({
/**
@@ -70,4 +69,4 @@ Page({
onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/view/sticky/sticky-section/sticky-section.js b/miniprogram/packageComponent/pages/view/sticky/sticky-section/sticky-section.js
index 6fe027bd..6a4c6532 100644
--- a/miniprogram/packageComponent/pages/view/sticky/sticky-section/sticky-section.js
+++ b/miniprogram/packageComponent/pages/view/sticky/sticky-section/sticky-section.js
@@ -9,7 +9,7 @@ Page({
data: {
list: generateList(20),
},
-
+
back() {
wx.navigateBack({})
},
@@ -69,4 +69,4 @@ Page({
onShareAppMessage() {
}
-})
\ No newline at end of file
+})
diff --git a/miniprogram/packageComponent/pages/view/sticky/sticky.js b/miniprogram/packageComponent/pages/view/sticky/sticky.js
index 3b276f80..5a992f4f 100644
--- a/miniprogram/packageComponent/pages/view/sticky/sticky.js
+++ b/miniprogram/packageComponent/pages/view/sticky/sticky.js
@@ -10,16 +10,14 @@ Page({
go1() {
wx.navigateTo({
- url: './sticky-header/sticky-header',
- })
+ url: './sticky-header/sticky-header',
+ })
},
-
goGrid1() {
wx.navigateTo({
- url: './sticky-section/sticky-section',
+ url: './sticky-section/sticky-section',
})
},
-
})
diff --git a/miniprogram/packageComponent/pages/view/swiper/swiper.js b/miniprogram/packageComponent/pages/view/swiper/swiper.js
index 782b7bd8..ac8bc5f7 100644
--- a/miniprogram/packageComponent/pages/view/swiper/swiper.js
+++ b/miniprogram/packageComponent/pages/view/swiper/swiper.js
@@ -6,7 +6,7 @@ Page({
}
},
- data: {
+ data: {
theme: 'light',
background: ['A', 'B', 'C'],
indicatorDots: true,
@@ -46,12 +46,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
}
diff --git a/miniprogram/packageComponent/pages/view/view/view.js b/miniprogram/packageComponent/pages/view/view/view.js
index 4087a1c6..def223f4 100644
--- a/miniprogram/packageComponent/pages/view/view/view.js
+++ b/miniprogram/packageComponent/pages/view/view/view.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageExtend/base/CustomPage.js b/miniprogram/packageExtend/base/CustomPage.js
index 18a47b36..9193e35c 100644
--- a/miniprogram/packageExtend/base/CustomPage.js
+++ b/miniprogram/packageExtend/base/CustomPage.js
@@ -2,7 +2,8 @@ import themeMixin from './behaviors/theme'
const CustomPage = function (options) {
return Page(
- Object.assign({}, options, {
+ {
+ ...options,
behaviors: [themeMixin].concat(options.behaviors || []),
onLoad(query) {
const app = getApp()
@@ -18,17 +19,17 @@ const CustomPage = function (options) {
app.unWatchThemeChange && app.unWatchThemeChange(this.themeChanged)
options.onUnload && options.onUnload.call(this)
}
- },
- onShareAppMessage() {
- const route = this.route
- const segments = route.split('/')
- const title = segments[segments.length - 1]
- return {
- title: title,
- path: route,
- }
- },
- })
+ },
+ onShareAppMessage() {
+ const route = this.route
+ const segments = route.split('/')
+ const title = segments[segments.length - 1]
+ return {
+ title,
+ path: route,
+ }
+ },
+ }
)
}
diff --git a/miniprogram/packageExtend/components/actionsheet/actionsheet.js b/miniprogram/packageExtend/components/actionsheet/actionsheet.js
index 4bb51d7f..d17c8959 100644
--- a/miniprogram/packageExtend/components/actionsheet/actionsheet.js
+++ b/miniprogram/packageExtend/components/actionsheet/actionsheet.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
diff --git a/miniprogram/packageExtend/components/badge/badge.js b/miniprogram/packageExtend/components/badge/badge.js
index e7a33704..983182ef 100644
--- a/miniprogram/packageExtend/components/badge/badge.js
+++ b/miniprogram/packageExtend/components/badge/badge.js
@@ -1,5 +1,3 @@
-
-
Component({
options: {
},
diff --git a/miniprogram/packageExtend/components/cell/cell.js b/miniprogram/packageExtend/components/cell/cell.js
index 1bfb92f5..9fd8b2ed 100644
--- a/miniprogram/packageExtend/components/cell/cell.js
+++ b/miniprogram/packageExtend/components/cell/cell.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -206,4 +206,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/cells/cells.js b/miniprogram/packageExtend/components/cells/cells.js
index c6aea93f..c5bba1b5 100644
--- a/miniprogram/packageExtend/components/cells/cells.js
+++ b/miniprogram/packageExtend/components/cells/cells.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -167,4 +167,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/checkbox-group/checkbox-group.js b/miniprogram/packageExtend/components/checkbox-group/checkbox-group.js
index 6a7a95c0..e8ec8538 100644
--- a/miniprogram/packageExtend/components/checkbox-group/checkbox-group.js
+++ b/miniprogram/packageExtend/components/checkbox-group/checkbox-group.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -159,7 +159,7 @@ module.exports =
vals.push(item.data.value)
}
})
- this.triggerEvent('change', {value: vals})
+ this.triggerEvent('change', { value: vals })
} else {
let val = ''
this.data.targetList.forEach(function (item) {
@@ -171,7 +171,7 @@ module.exports =
})
}
})
- this.triggerEvent('change', {value: val}, {})
+ this.triggerEvent('change', { value: val }, {})
}
},
setParentCellsClass: function setParentCellsClass() {
@@ -193,4 +193,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/checkbox/checkbox.js b/miniprogram/packageExtend/components/checkbox/checkbox.js
index 7980ab66..44583b55 100644
--- a/miniprogram/packageExtend/components/checkbox/checkbox.js
+++ b/miniprogram/packageExtend/components/checkbox/checkbox.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -155,10 +155,10 @@ module.exports =
this.data.group.checkedChange(_checked, this)
}
}
- this.triggerEvent('change', {value: this.data.value, checked: this.data.checked})
+ this.triggerEvent('change', { value: this.data.value, checked: this.data.checked })
}
}
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/col/index.js b/miniprogram/packageExtend/components/col/index.js
index 4e3e1cce..c2456f68 100644
--- a/miniprogram/packageExtend/components/col/index.js
+++ b/miniprogram/packageExtend/components/col/index.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -206,4 +206,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/dialog/dialog.js b/miniprogram/packageExtend/components/dialog/dialog.js
index f8d13708..7a9387bb 100644
--- a/miniprogram/packageExtend/components/dialog/dialog.js
+++ b/miniprogram/packageExtend/components/dialog/dialog.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -164,4 +164,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/emoji/emoji.js b/miniprogram/packageExtend/components/emoji/emoji.js
index 096bdbde..b9829f4e 100644
--- a/miniprogram/packageExtend/components/emoji/emoji.js
+++ b/miniprogram/packageExtend/components/emoji/emoji.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -86,7 +86,7 @@ module.exports =
/** *** */ }([
/* 0 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
exports.default = [{
id: 0, cn: '[微笑]', hk: '[微笑]', us: '[Smile]', code: '/::)', web_code: '/微笑', style: 'smiley_0'
}, {
@@ -370,7 +370,7 @@ module.exports =
/* 1 */,
/* 2 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const emoji_data_1 = __webpack_require__(0)
const emoji_panel_data_1 = __webpack_require__(3)
const parser_1 = __webpack_require__(4)
@@ -455,8 +455,8 @@ module.exports =
const idx = evt.currentTarget.dataset.idx
const emotionName = data.emotions[idx].cn
this.LRUCache(data.history, data.perLine, idx)
- this.setData({history: data.history})
- this.triggerEvent('insertemoji', {emotionName})
+ this.setData({ history: data.history })
+ this.triggerEvent('insertemoji', { emotionName })
},
deleteEmoji() {
this.triggerEvent('delemoji')
@@ -480,12 +480,12 @@ module.exports =
/***/ }),
/* 3 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
exports.default = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 54, 55, 56, 57, 60, 62, 63, 64, 65, 66, 67, 68, 70, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 89, 92, 93, 94, 95, 300, 301, 302, 303, 304, 305, 306, 307, 204, 205, 202, 206, 212, 211, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 308, 309, 310, 311, 312, 209]
/***/ }),
/* 4 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const emoji_data_1 = __webpack_require__(0)
const emotionMap = {}
emoji_data_1.default.forEach(function (item, index) {
@@ -500,7 +500,7 @@ module.exports =
for (const k in emotionMap) {
let idx = content.indexOf(k)
while (idx >= 0) {
- emojiIndexList.push({idx, code: k, type: 2})
+ emojiIndexList.push({ idx, code: k, type: 2 })
idx = content.indexOf(k, idx + k.length)
}
}
diff --git a/miniprogram/packageExtend/components/form-page/form-page.js b/miniprogram/packageExtend/components/form-page/form-page.js
index 237854cb..1bb9b4db 100644
--- a/miniprogram/packageExtend/components/form-page/form-page.js
+++ b/miniprogram/packageExtend/components/form-page/form-page.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -121,4 +121,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/form/form.js b/miniprogram/packageExtend/components/form/form.js
index 206fb2d7..7c0861e2 100644
--- a/miniprogram/packageExtend/components/form/form.js
+++ b/miniprogram/packageExtend/components/form/form.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -86,7 +86,7 @@ module.exports =
/** *** */ }([
/* 0 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
exports.diff = function (old, newVal) {
if (!old && newVal || old && !newVal) return true
for (const k in newVal) {
@@ -122,7 +122,7 @@ module.exports =
/* 3 */,
/* 4 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const form_validator_1 = __webpack_require__(5)
const object_1 = __webpack_require__(0)
function linked(target) {
@@ -189,7 +189,7 @@ module.exports =
newRules[rule.name] = rule.rules || []
}
})
- this.setData({newRules})
+ this.setData({ newRules })
return newRules
},
_modelChange: function _modelChange(newVal, oldVal, path) {
@@ -222,7 +222,7 @@ module.exports =
_loop(k)
}
_this._showErrors(diffObj, errorMap)
- _this.triggerEvent(isValid ? 'success' : 'fail', isValid ? {trigger: 'change'} : {errors, trigger: 'change'})
+ _this.triggerEvent(isValid ? 'success' : 'fail', isValid ? { trigger: 'change' } : { errors, trigger: 'change' })
}())
}
return newVal
@@ -256,7 +256,7 @@ module.exports =
return this.formValidator.validate(function (isValid, errors) {
_this2._showAllErrors(errors)
const handleError = _this2.handleErrors(errors)
- _this2.triggerEvent(isValid ? 'success' : 'fail', isValid ? {trigger: 'validate'} : {errors: handleError, trigger: 'validate'})
+ _this2.triggerEvent(isValid ? 'success' : 'fail', isValid ? { trigger: 'validate' } : { errors: handleError, trigger: 'validate' })
cb && cb(isValid, handleError)
})
},
@@ -270,7 +270,7 @@ module.exports =
return this.formValidator.validateField(name, value, function (isValid, errors) {
_this3._showError(name, errors)
const handleError = _this3.handleErrors(errors)
- _this3.triggerEvent(isValid ? 'success' : 'fail', isValid ? {trigger: 'validate'} : {errors: handleError, trigger: 'validate'})
+ _this3.triggerEvent(isValid ? 'success' : 'fail', isValid ? { trigger: 'validate' } : { errors: handleError, trigger: 'validate' })
cb && cb(isValid, handleError)
})
},
@@ -298,7 +298,7 @@ module.exports =
/***/ (function (module, exports, __webpack_require__) {
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function') } }
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const validator_1 = __webpack_require__(6)
const object_1 = __webpack_require__(0)
const toString = Object.prototype.toString
@@ -361,7 +361,7 @@ module.exports =
keys.forEach(function (key) {
if (!errors[key]) delete errors[key]
})
- resolve({isValid: !failCount, errors: failCount ? errors : undefined})
+ resolve({ isValid: !failCount, errors: failCount ? errors : undefined })
cb && cb(!failCount, failCount ? errors : undefined)
})
}
@@ -377,7 +377,7 @@ module.exports =
_this2._innerValidateField(name, value, function (valid, error) {
const errObj = {}
errObj[name] = error
- resolve({valid, error: valid ? undefined : error})
+ resolve({ valid, error: valid ? undefined : error })
cb(valid, valid ? undefined : errObj)
const oldError = _this2.errors[name]
const errorChanged = object_1.diff(oldError, error)
@@ -412,7 +412,7 @@ module.exports =
const resMessage = validateSingleRule(rule, value || models[name], rule.param, models)
if (resMessage && !isFail) {
isFail = true
- const error = resMessage ? {message: resMessage, rule} : undefined
+ const error = resMessage ? { message: resMessage, rule } : undefined
cb(false, error)
}
})
@@ -423,7 +423,7 @@ module.exports =
const rule = rules
rule.name = name
const resMessage = validateSingleRule(rule, value || models[name], rule.param, models)
- const error = resMessage ? {message: resMessage, rule} : undefined
+ const error = resMessage ? { message: resMessage, rule } : undefined
if (resMessage) {
isFail = true
}
@@ -450,7 +450,7 @@ module.exports =
/***/ }),
/* 6 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const string_1 = __webpack_require__(7)
const defaultMessage = {
required: '%s必填',
@@ -528,7 +528,7 @@ module.exports =
/***/ }),
/* 7 */
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
exports.sprintf = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key]
diff --git a/miniprogram/packageExtend/components/gallery/gallery.js b/miniprogram/packageExtend/components/gallery/gallery.js
index 8bbccd47..ce38813f 100644
--- a/miniprogram/packageExtend/components/gallery/gallery.js
+++ b/miniprogram/packageExtend/components/gallery/gallery.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -95,7 +95,7 @@ module.exports =
type: Array,
value: [],
observer: function observer(newVal, oldVal, changedPath) {
- this.setData({currentImgs: newVal})
+ this.setData({ currentImgs: newVal })
}
},
showDelete: {
@@ -172,4 +172,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/grids/grids.js b/miniprogram/packageExtend/components/grids/grids.js
index b8707060..7ec5d30b 100644
--- a/miniprogram/packageExtend/components/grids/grids.js
+++ b/miniprogram/packageExtend/components/grids/grids.js
@@ -1,4 +1,3 @@
-
/** *** */ (function (modules) { // webpackBootstrap
/** *** */ // The module cache
/** *** */ const installedModules = {}
@@ -15,7 +14,7 @@
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +36,16 @@
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +59,7 @@
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -132,7 +131,7 @@
attached() {
if (this.data.grids) {
this.setData({
- innerGrids: this.data.grids.map(grid => Object.assign({}, this.data._defaultGridProps, grid))
+ innerGrids: this.data.grids.map(grid => ({ ...this.data._defaultGridProps, ...grid }))
})
}
}
@@ -141,4 +140,4 @@
})
/***/ })
-/** *** */}))
+/** *** */ }))
diff --git a/miniprogram/packageExtend/components/icon/icon.js b/miniprogram/packageExtend/components/icon/icon.js
index 714a3721..fc4ab659 100644
--- a/miniprogram/packageExtend/components/icon/icon.js
+++ b/miniprogram/packageExtend/components/icon/icon.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -91,7 +91,7 @@ module.exports =
const _icondata = _interopRequireDefault(__webpack_require__(12))
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj} }
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj } }
const getFixedIconType = function (type) {
// 兼容旧版本 typo
@@ -153,7 +153,7 @@ module.exports =
/***/ 11:
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
const b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
const cb_encode = function cb_encode(ccc) {
const padlen = [0, 2, 1][ccc.length % 3]
@@ -199,90 +199,90 @@ module.exports =
/***/ 12:
/***/ (function (module, exports, __webpack_require__) {
- Object.defineProperty(exports, '__esModule', {value: true})
+ Object.defineProperty(exports, '__esModule', { value: true })
exports.default = {
- 'add-friends': {outline: '', field: ''},
- add: {outline: '', field: ''},
- add2: {outline: '', field: ''},
- album: {outline: '', field: ''},
- arrow: {outline: '', field: ''},
- at: {outline: '', field: ''},
- back: {outline: '', field: ''},
- back2: {outline: '', field: ''},
- 'bellring-off': {outline: '', field: ''},
- 'bellring-on': {outline: '', field: ''},
- camera: {outline: '', field: ''},
- cellphone: {outline: '', field: ''},
- clip: {outline: '', field: ''},
- close: {outline: '', field: ''},
- close2: {outline: '', field: ''},
- comment: {outline: '', field: ''},
- contacts: {outline: '', field: ''},
- copy: {outline: '', field: ''},
- 'delete-on': {outline: '', field: ''},
- delete: {outline: '', field: ''},
- discover: {outline: '', field: ''},
- display: {outline: '', field: ''},
- done: {outline: '', field: ''},
- done2: {outline: '', field: ''},
- download: {outline: '', field: ''},
- email: {outline: '', field: ''},
- error: {outline: '', field: ''},
- 'eyes-off': {outline: '', field: ''},
- 'eyes-on': {outline: '', field: ''},
- folder: {outline: '', field: ''},
- 'group-detail': {outline: '', field: ''},
- help: {outline: '', field: ''},
- home: {outline: '', field: ''},
- imac: {outline: '', field: ''},
- info: {outline: '', field: ''},
- keyboard: {outline: '', field: ''},
- like: {outline: '', field: ''},
- link: {outline: '', field: ''},
- location: {outline: '', field: ''},
- lock: {outline: '', field: ''},
- 'max-window': {outline: '', field: ''},
- me: {outline: '', field: ''},
- mike: {outline: '', field: ''},
- mike2: {outline: '', field: ''},
- 'mobile-contacts': {outline: '', field: ''},
- more: {outline: '', field: ''},
- more2: {outline: '', field: ''},
- mosaic: {outline: '', field: ''},
- 'music-off': {outline: '', field: ''},
- music: {outline: '', field: ''},
- note: {outline: '', field: ''},
- pad: {outline: '', field: ''},
- pause: {outline: '', field: ''},
- pencil: {outline: '', field: ''},
- 'photo-wall': {outline: '', field: ''},
- play: {outline: '', field: ''},
- play2: {outline: '', field: ''},
- previous: {outline: '', field: ''},
- previous2: {outline: '', field: ''},
- 'qr-code': {outline: '', field: ''},
- refresh: {outline: '', field: ''},
- 'report-problem': {outline: '', field: ''},
- search: {outline: '', field: ''},
- sending: {outline: '', field: ''},
- setting: {outline: '', field: ''},
- share: {outline: '', field: ''},
- shop: {outline: '', field: ''},
- star: {outline: '', field: ''},
- sticker: {outline: '', field: ''},
- tag: {outline: '', field: ''},
- text: {outline: '', field: ''},
- time: {outline: '', field: ''},
- 'transfer-text': {outline: '', field: ''},
- transfer2: {outline: '', field: ''},
- translate: {outline: '', field: ''},
- tv: {outline: '', field: ''},
- 'video-call': {outline: '', field: ''},
- voice: {outline: '', field: ''},
- 'volume-down': {outline: '', field: ''},
- 'volume-off': {outline: '', field: ''},
- 'volume-up': {outline: '', field: ''}
+ 'add-friends': { outline: '', field: '' },
+ add: { outline: '', field: '' },
+ add2: { outline: '', field: '' },
+ album: { outline: '', field: '' },
+ arrow: { outline: '', field: '' },
+ at: { outline: '', field: '' },
+ back: { outline: '', field: '' },
+ back2: { outline: '', field: '' },
+ 'bellring-off': { outline: '', field: '' },
+ 'bellring-on': { outline: '', field: '' },
+ camera: { outline: '', field: '' },
+ cellphone: { outline: '', field: '' },
+ clip: { outline: '', field: '' },
+ close: { outline: '', field: '' },
+ close2: { outline: '', field: '' },
+ comment: { outline: '', field: '' },
+ contacts: { outline: '', field: '' },
+ copy: { outline: '', field: '' },
+ 'delete-on': { outline: '', field: '' },
+ delete: { outline: '', field: '' },
+ discover: { outline: '', field: '' },
+ display: { outline: '', field: '' },
+ done: { outline: '', field: '' },
+ done2: { outline: '', field: '' },
+ download: { outline: '', field: '' },
+ email: { outline: '', field: '' },
+ error: { outline: '', field: '' },
+ 'eyes-off': { outline: '', field: '' },
+ 'eyes-on': { outline: '', field: '' },
+ folder: { outline: '', field: '' },
+ 'group-detail': { outline: '', field: '' },
+ help: { outline: '', field: '' },
+ home: { outline: '', field: '' },
+ imac: { outline: '', field: '' },
+ info: { outline: '', field: '' },
+ keyboard: { outline: '', field: '' },
+ like: { outline: '', field: '' },
+ link: { outline: '', field: '' },
+ location: { outline: '', field: '' },
+ lock: { outline: '', field: '' },
+ 'max-window': { outline: '', field: '' },
+ me: { outline: '', field: '' },
+ mike: { outline: '', field: '' },
+ mike2: { outline: '', field: '' },
+ 'mobile-contacts': { outline: '', field: '' },
+ more: { outline: '', field: '' },
+ more2: { outline: '', field: '' },
+ mosaic: { outline: '', field: '' },
+ 'music-off': { outline: '', field: '' },
+ music: { outline: '', field: '' },
+ note: { outline: '', field: '' },
+ pad: { outline: '', field: '' },
+ pause: { outline: '', field: '' },
+ pencil: { outline: '', field: '' },
+ 'photo-wall': { outline: '', field: '' },
+ play: { outline: '', field: '' },
+ play2: { outline: '', field: '' },
+ previous: { outline: '', field: '' },
+ previous2: { outline: '', field: '' },
+ 'qr-code': { outline: '', field: '' },
+ refresh: { outline: '', field: '' },
+ 'report-problem': { outline: '', field: '' },
+ search: { outline: '', field: '' },
+ sending: { outline: '', field: '' },
+ setting: { outline: '', field: '' },
+ share: { outline: '', field: '' },
+ shop: { outline: '', field: '' },
+ star: { outline: '', field: '' },
+ sticker: { outline: '', field: '' },
+ tag: { outline: '', field: '' },
+ text: { outline: '', field: '' },
+ time: { outline: '', field: '' },
+ 'transfer-text': { outline: '', field: '' },
+ transfer2: { outline: '', field: '' },
+ translate: { outline: '', field: '' },
+ tv: { outline: '', field: '' },
+ 'video-call': { outline: '', field: '' },
+ voice: { outline: '', field: '' },
+ 'volume-down': { outline: '', field: '' },
+ 'volume-off': { outline: '', field: '' },
+ 'volume-up': { outline: '', field: '' }
}
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/index-list/index-list.js b/miniprogram/packageExtend/components/index-list/index-list.js
index 98c118e4..05c43b25 100644
--- a/miniprogram/packageExtend/components/index-list/index-list.js
+++ b/miniprogram/packageExtend/components/index-list/index-list.js
@@ -85,13 +85,13 @@ Component({
const _wx$getSystemInfoSync = wx.getSystemInfoSync(); const
windowHeight = _wx$getSystemInfoSync.windowHeight
- this.setData({windowHeight})
+ this.setData({ windowHeight })
},
},
methods: {
choose(e) {
const item = e.target.dataset.item
- this.triggerEvent('choose', {item})
+ this.triggerEvent('choose', { item })
},
scrollTo(e) {
this.__scrollTo(e)
@@ -101,7 +101,7 @@ Component({
const clientY = e.changedTouches[0].clientY
const index = Math.floor((clientY - data._anchorTop) / data._anchorItemH)
const current = data.alphabet[index]
- this.setData({current, intoView: current, touching: true})
+ this.setData({ current, intoView: current, touching: true })
if (data.vibrated) wx.vibrateShort()
},
computedSize() {
@@ -126,7 +126,7 @@ Component({
const _this2 = this
setTimeout(function () {
- _this2.setData({touching: false})
+ _this2.setData({ touching: false })
}, 150)
},
onScroll: function onScroll(e) {
@@ -149,7 +149,7 @@ Component({
}
}
if (!current) current = alphabet[alphabet.length - 1]
- this.setData({current})
+ this.setData({ current })
}
}
})
diff --git a/miniprogram/packageExtend/components/index.js b/miniprogram/packageExtend/components/index.js
index c9c4a06c..3fa84d71 100644
--- a/miniprogram/packageExtend/components/index.js
+++ b/miniprogram/packageExtend/components/index.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -90,4 +90,4 @@ module.exports =
exports.__esModule = true
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/loading/loading.js b/miniprogram/packageExtend/components/loading/loading.js
index 1ec6ebce..af6c9592 100644
--- a/miniprogram/packageExtend/components/loading/loading.js
+++ b/miniprogram/packageExtend/components/loading/loading.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -176,4 +176,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/msg/msg.js b/miniprogram/packageExtend/components/msg/msg.js
index 1ee50300..67b34189 100644
--- a/miniprogram/packageExtend/components/msg/msg.js
+++ b/miniprogram/packageExtend/components/msg/msg.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -123,4 +123,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/navigation-bar/navigation-bar.js b/miniprogram/packageExtend/components/navigation-bar/navigation-bar.js
index 1e3d5eaa..fe62968b 100644
--- a/miniprogram/packageExtend/components/navigation-bar/navigation-bar.js
+++ b/miniprogram/packageExtend/components/navigation-bar/navigation-bar.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -184,4 +184,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/row/index.js b/miniprogram/packageExtend/components/row/index.js
index 9f41d15c..c6e778b3 100644
--- a/miniprogram/packageExtend/components/row/index.js
+++ b/miniprogram/packageExtend/components/row/index.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -103,4 +103,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/searchbar/searchbar.js b/miniprogram/packageExtend/components/searchbar/searchbar.js
index a3af1ce9..c888a8a5 100644
--- a/miniprogram/packageExtend/components/searchbar/searchbar.js
+++ b/miniprogram/packageExtend/components/searchbar/searchbar.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -214,4 +214,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/select-text/select-text.js b/miniprogram/packageExtend/components/select-text/select-text.js
index 97725244..b8b4e22f 100644
--- a/miniprogram/packageExtend/components/select-text/select-text.js
+++ b/miniprogram/packageExtend/components/select-text/select-text.js
@@ -1,4 +1,3 @@
-
Component({
/**
* 组件的属性列表
diff --git a/miniprogram/packageExtend/components/slideview/slideview.js b/miniprogram/packageExtend/components/slideview/slideview.js
index 663f2169..568e059c 100644
--- a/miniprogram/packageExtend/components/slideview/slideview.js
+++ b/miniprogram/packageExtend/components/slideview/slideview.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -195,4 +195,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/sticky/sticky.js b/miniprogram/packageExtend/components/sticky/sticky.js
index 9af6afa2..bc81f1d5 100644
--- a/miniprogram/packageExtend/components/sticky/sticky.js
+++ b/miniprogram/packageExtend/components/sticky/sticky.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -231,7 +231,7 @@ module.exports =
scrollTop: top,
isFixed: fixed
})
- this.setData({fixed})
+ this.setData({ fixed })
}
}
})
@@ -271,4 +271,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/tabbar/tabbar.js b/miniprogram/packageExtend/components/tabbar/tabbar.js
index 4754b573..de30eb37 100644
--- a/miniprogram/packageExtend/components/tabbar/tabbar.js
+++ b/miniprogram/packageExtend/components/tabbar/tabbar.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -125,4 +125,4 @@ module.exports =
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/tabs/tabs.js b/miniprogram/packageExtend/components/tabs/tabs.js
index 32b36f56..a3b9560e 100644
--- a/miniprogram/packageExtend/components/tabs/tabs.js
+++ b/miniprogram/packageExtend/components/tabs/tabs.js
@@ -1,23 +1,22 @@
-
Component({
options: {
pureDataPattern: /^_/,
multipleSlots: true
},
properties: {
- tabs: {type: Array, value: []},
- tabClass: {type: String, value: ''},
- swiperClass: {type: String, value: ''},
- activeClass: {type: String, value: ''},
- tabUnderlineColor: {type: String, value: '#07c160'},
- tabActiveTextColor: {type: String, value: '#000000'},
- tabInactiveTextColor: {type: String, value: '#000000'},
- tabBackgroundColor: {type: String, value: '#ffffff'},
- activeTab: {type: Number, value: 0},
- swipeable: {type: Boolean, value: true},
- animation: {type: Boolean, value: true},
- duration: {type: Number, value: 500},
- theme: {type: String, value: 'light'} // light dark
+ tabs: { type: Array, value: [] },
+ tabClass: { type: String, value: '' },
+ swiperClass: { type: String, value: '' },
+ activeClass: { type: String, value: '' },
+ tabUnderlineColor: { type: String, value: '#07c160' },
+ tabActiveTextColor: { type: String, value: '#000000' },
+ tabInactiveTextColor: { type: String, value: '#000000' },
+ tabBackgroundColor: { type: String, value: '#ffffff' },
+ activeTab: { type: Number, value: 0 },
+ swipeable: { type: Boolean, value: true },
+ animation: { type: Boolean, value: true },
+ duration: { type: Number, value: 500 },
+ theme: { type: String, value: 'light' } // light dark
},
data: {
currentView: 0
@@ -29,7 +28,7 @@ Component({
let currentView = _activeTab - 1
if (currentView < 0) currentView = 0
if (currentView > len - 1) currentView = len - 1
- this.setData({currentView})
+ this.setData({ currentView })
}
},
lifetimes: {
@@ -38,13 +37,13 @@ Component({
methods: {
handleTabClick: function handleTabClick(e) {
const index = e.currentTarget.dataset.index
- this.setData({activeTab: index})
- this.triggerEvent('tabclick', {index})
+ this.setData({ activeTab: index })
+ this.triggerEvent('tabclick', { index })
},
handleSwiperChange: function handleSwiperChange(e) {
const index = e.detail.current
- this.setData({activeTab: index})
- this.triggerEvent('change', {index})
+ this.setData({ activeTab: index })
+ this.triggerEvent('change', { index })
}
}
})
diff --git a/miniprogram/packageExtend/components/toptips/toptips.js b/miniprogram/packageExtend/components/toptips/toptips.js
index 6f3f54b5..050c70ac 100644
--- a/miniprogram/packageExtend/components/toptips/toptips.js
+++ b/miniprogram/packageExtend/components/toptips/toptips.js
@@ -1,4 +1,3 @@
-
Component({
options: {
},
diff --git a/miniprogram/packageExtend/components/uploader/uploader.js b/miniprogram/packageExtend/components/uploader/uploader.js
index 1fcdf67c..1c773502 100644
--- a/miniprogram/packageExtend/components/uploader/uploader.js
+++ b/miniprogram/packageExtend/components/uploader/uploader.js
@@ -15,7 +15,7 @@ module.exports =
/** *** */ i: moduleId,
/** *** */ l: false,
/** *** */ exports: {}
- /** *** */}
+ /** *** */ }
/** *** */
/** *** */ // Execute the module function
/** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__)
@@ -37,16 +37,16 @@ module.exports =
/** *** */ // define getter function for harmony exports
/** *** */ __webpack_require__.d = function (exports, name, getter) {
/** *** */ if (!__webpack_require__.o(exports, name)) {
- /** *** */ Object.defineProperty(exports, name, {enumerable: true, get: getter})
+ /** *** */ Object.defineProperty(exports, name, { enumerable: true, get: getter })
/** *** */ }
/** *** */ }
/** *** */
/** *** */ // define __esModule on exports
/** *** */ __webpack_require__.r = function (exports) {
/** *** */ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
- /** *** */ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'})
+ /** *** */ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
/** *** */ }
- /** *** */ Object.defineProperty(exports, '__esModule', {value: true})
+ /** *** */ Object.defineProperty(exports, '__esModule', { value: true })
/** *** */ }
/** *** */
/** *** */ // create a fake namespace object
@@ -60,7 +60,7 @@ module.exports =
/** *** */ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value
/** *** */ const ns = Object.create(null)
/** *** */ __webpack_require__.r(ns)
- /** *** */ Object.defineProperty(ns, 'default', {enumerable: true, value})
+ /** *** */ Object.defineProperty(ns, 'default', { enumerable: true, value })
/** *** */ if (mode & 2 && typeof value !== 'string') for (const key in value) __webpack_require__.d(ns, key, function (key) { return value[key] }.bind(null, key))
/** *** */ return ns
/** *** */ }
@@ -193,16 +193,16 @@ module.exports =
const fileContent = mgr.readFileSync(item)
return fileContent
})
- const obj = {tempFilePaths: res.tempFilePaths, tempFiles: res.tempFiles, contents}
+ const obj = { tempFilePaths: res.tempFilePaths, tempFiles: res.tempFiles, contents }
_this.triggerEvent('select', obj, {})
const files = res.tempFilePaths.map(function (item, i) {
- return {loading: true, url: 'data:image/jpg;base64,' + wx.arrayBufferToBase64(contents[i])}
+ return { loading: true, url: 'data:image/jpg;base64,' + wx.arrayBufferToBase64(contents[i]) }
})
if (!files || !files.length) return
if (typeof _this.data.upload === 'function') {
const len = _this.data.files.length
const newFiles = _this.data.files.concat(files)
- _this.setData({files: newFiles, currentFiles: newFiles})
+ _this.setData({ files: newFiles, currentFiles: newFiles })
_this.loading = true
_this.data.upload(obj).then(function (json) {
_this.loading = false
@@ -212,10 +212,10 @@ module.exports =
oldFiles[len + index].url = url
oldFiles[len + index].loading = false
})
- _this.setData({files: oldFiles, currentFiles: newFiles})
+ _this.setData({ files: oldFiles, currentFiles: newFiles })
_this.triggerEvent('success', json, {})
} else {
- _this.triggerEvent('fail', {type: 3, errMsg: 'upload file fail, urls not found'}, {})
+ _this.triggerEvent('fail', { type: 3, errMsg: 'upload file fail, urls not found' }, {})
}
}).catch(function (err) {
_this.loading = false
@@ -224,8 +224,8 @@ module.exports =
oldFiles[len + index].error = true
oldFiles[len + index].loading = false
})
- _this.setData({files: oldFiles, currentFiles: newFiles})
- _this.triggerEvent('fail', {type: 3, errMsg: 'upload file fail', error: err}, {})
+ _this.setData({ files: oldFiles, currentFiles: newFiles })
+ _this.triggerEvent('fail', { type: 3, errMsg: 'upload file fail', error: err }, {})
})
}
},
@@ -247,10 +247,10 @@ module.exports =
files,
currentFiles: files
})
- this.triggerEvent('delete', {index, item: file[0]})
+ this.triggerEvent('delete', { index, item: file[0] })
}
}
})
/***/ })
- /** *** */}))
+ /** *** */ }))
diff --git a/miniprogram/packageExtend/components/video-swiper/video-swiper.js b/miniprogram/packageExtend/components/video-swiper/video-swiper.js
index eba9d75a..74a6fc36 100644
--- a/miniprogram/packageExtend/components/video-swiper/video-swiper.js
+++ b/miniprogram/packageExtend/components/video-swiper/video-swiper.js
@@ -71,7 +71,7 @@ Component({
if (diff === 0) return
this.data._last = current
this.playCurrent(current)
- this.triggerEvent('change', {activeId: curQueue[current].id})
+ this.triggerEvent('change', { activeId: curQueue[current].id })
const direction = diff === 1 || diff === -2 ? 'up' : 'down'
if (direction === 'up') {
console.log(this.data)
@@ -157,9 +157,7 @@ Component({
const detail = e.detail
const activeId = e.target.dataset.id
- this.triggerEvent(
- type, Object.assign(Object.assign(Object.assign({}, detail), {activeId}), ext)
- )
+ this.triggerEvent(type, { ...detail, activeId, ...ext })
}
},
})
diff --git a/miniprogram/packageExtend/components/vtabs-content/vtabs-content.js b/miniprogram/packageExtend/components/vtabs-content/vtabs-content.js
index b8efabb0..2418e034 100644
--- a/miniprogram/packageExtend/components/vtabs-content/vtabs-content.js
+++ b/miniprogram/packageExtend/components/vtabs-content/vtabs-content.js
@@ -1,5 +1,3 @@
-
-
Component({
options: {
multipleSlots: true
diff --git a/miniprogram/packageExtend/components/vtabs/vtabs.js b/miniprogram/packageExtend/components/vtabs/vtabs.js
index 7f5796fe..7fcdef2a 100644
--- a/miniprogram/packageExtend/components/vtabs/vtabs.js
+++ b/miniprogram/packageExtend/components/vtabs/vtabs.js
@@ -1,21 +1,19 @@
-
-
Component({
options: {
pureDataPattern: /^_/,
multipleSlots: true
},
properties: {
- vtabs: {type: Array, value: []},
- tabBarClass: {type: String, value: ''},
- activeClass: {type: String, value: ''},
- tabBarLineColor: {type: String, value: '#07c160'},
- tabBarInactiveTextColor: {type: String, value: '#000000'},
- tabBarActiveTextColor: {type: String, value: '#07c160'},
- tabBarInactiveBgColor: {type: String, value: '#eeeeee'},
- tabBarActiveBgColor: {type: String, value: '#ffffff'},
- activeTab: {type: Number, value: 0},
- animation: {type: Boolean, value: true}
+ vtabs: { type: Array, value: [] },
+ tabBarClass: { type: String, value: '' },
+ activeClass: { type: String, value: '' },
+ tabBarLineColor: { type: String, value: '#07c160' },
+ tabBarInactiveTextColor: { type: String, value: '#000000' },
+ tabBarActiveTextColor: { type: String, value: '#07c160' },
+ tabBarInactiveBgColor: { type: String, value: '#eeeeee' },
+ tabBarActiveBgColor: { type: String, value: '#ffffff' },
+ activeTab: { type: Number, value: 0 },
+ animation: { type: Boolean, value: true }
},
data: {
currentView: 0,
@@ -69,13 +67,13 @@ Component({
if (len === 0) return
let currentView = index < 6 ? 0 : index - 5
if (currentView >= len) currentView = len - 1
- this.setData({currentView})
+ this.setData({ currentView })
},
handleTabClick: function handleTabClick(e) {
const _heightRecords = this.data._heightRecords
const index = e.currentTarget.dataset.index
const contentScrollTop = _heightRecords[index - 1] || 0
- this.triggerEvent('tabclick', {index})
+ this.triggerEvent('tabclick', { index })
this.setData({
activeTab: index,
contentScrollTop
@@ -96,8 +94,8 @@ Component({
}
}
if (index !== this.data.activeTab) {
- this.triggerEvent('change', {index})
- this.setData({activeTab: index})
+ this.triggerEvent('change', { index })
+ this.setData({ activeTab: index })
}
}
}
diff --git a/miniprogram/packageExtend/pages/adapt/freelayout/freelayout.js b/miniprogram/packageExtend/pages/adapt/freelayout/freelayout.js
index 61d8892b..cbe4eda6 100644
--- a/miniprogram/packageExtend/pages/adapt/freelayout/freelayout.js
+++ b/miniprogram/packageExtend/pages/adapt/freelayout/freelayout.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageExtend/pages/adapt/horizontalexpansion/horizontalexpansion.js b/miniprogram/packageExtend/pages/adapt/horizontalexpansion/horizontalexpansion.js
index 3363cf85..74120659 100644
--- a/miniprogram/packageExtend/pages/adapt/horizontalexpansion/horizontalexpansion.js
+++ b/miniprogram/packageExtend/pages/adapt/horizontalexpansion/horizontalexpansion.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageExtend/pages/adapt/layeredpresentation/layeredpresentation.js b/miniprogram/packageExtend/pages/adapt/layeredpresentation/layeredpresentation.js
index 7c482657..37edc10e 100644
--- a/miniprogram/packageExtend/pages/adapt/layeredpresentation/layeredpresentation.js
+++ b/miniprogram/packageExtend/pages/adapt/layeredpresentation/layeredpresentation.js
@@ -2,8 +2,7 @@ Page({
data: {
theme: 'light',
hide1: false,
- hide2: false,
- theme: 'light'
+ hide2: false
},
onUnload() {
if (wx.offThemeChange) {
@@ -12,17 +11,17 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
onClick(e) {
- this.setData({[e.target.dataset.set]: true})
+ this.setData({ [e.target.dataset.set]: true })
},
onShareAppMessage() {
return {
diff --git a/miniprogram/packageExtend/pages/adapt/linebreak/linebreak.js b/miniprogram/packageExtend/pages/adapt/linebreak/linebreak.js
index 9dc8305d..2ab7b330 100644
--- a/miniprogram/packageExtend/pages/adapt/linebreak/linebreak.js
+++ b/miniprogram/packageExtend/pages/adapt/linebreak/linebreak.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageExtend/pages/adapt/pagination/pagination.js b/miniprogram/packageExtend/pages/adapt/pagination/pagination.js
index 515f4861..f334f6ed 100644
--- a/miniprogram/packageExtend/pages/adapt/pagination/pagination.js
+++ b/miniprogram/packageExtend/pages/adapt/pagination/pagination.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
diff --git a/miniprogram/packageExtend/pages/adapt/sidenavigation/sidenavigation.js b/miniprogram/packageExtend/pages/adapt/sidenavigation/sidenavigation.js
index f7af59dd..c6862aa0 100644
--- a/miniprogram/packageExtend/pages/adapt/sidenavigation/sidenavigation.js
+++ b/miniprogram/packageExtend/pages/adapt/sidenavigation/sidenavigation.js
@@ -10,20 +10,20 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
},
show() {
- this.setData({show: true})
+ this.setData({ show: true })
},
hide() {
- this.setData({show: false})
+ this.setData({ show: false })
},
onShareAppMessage() {
return {
diff --git a/miniprogram/packageExtend/pages/adapt/telescopic/telescopic.js b/miniprogram/packageExtend/pages/adapt/telescopic/telescopic.js
index 1a50d4af..d1e643c9 100644
--- a/miniprogram/packageExtend/pages/adapt/telescopic/telescopic.js
+++ b/miniprogram/packageExtend/pages/adapt/telescopic/telescopic.js
@@ -9,12 +9,12 @@ Page({
},
onLoad() {
this.setData({
- theme: wx.getSystemInfoSync().theme || 'light'
+ theme: getApp().globalData.theme || 'light'
})
if (wx.onThemeChange) {
- wx.onThemeChange(({theme}) => {
- this.setData({theme})
+ wx.onThemeChange(({ theme }) => {
+ this.setData({ theme })
})
}
// wx.showModal({
diff --git a/miniprogram/packageExtend/pages/base/gallery/gallery.js b/miniprogram/packageExtend/pages/base/gallery/gallery.js
index ac3b0b72..1b306365 100644
--- a/miniprogram/packageExtend/pages/base/gallery/gallery.js
+++ b/miniprogram/packageExtend/pages/base/gallery/gallery.js
@@ -8,10 +8,10 @@ CustomPage({
'https://res.wx.qq.com/op_res/0TZreUFL8sWsS1cFx5_f7MF5aY767_cWsd9JiKdHxL9Ktu6O6JLAJwvF-jLVxpB3'
],
show: true
- },
- openGallery() {
- this.setData({ show: true })
- },
+ },
+ openGallery() {
+ this.setData({ show: true })
+ },
change(e) {
console.log('current index has changed', e.detail)
},
diff --git a/miniprogram/packageExtend/pages/base/grid/grid.js b/miniprogram/packageExtend/pages/base/grid/grid.js
index bde3ce40..c3ce27de 100644
--- a/miniprogram/packageExtend/pages/base/grid/grid.js
+++ b/miniprogram/packageExtend/pages/base/grid/grid.js
@@ -1,6 +1,6 @@
import CustomPage from '../../../base/CustomPage'
-const {GRID_DEMO_URL} = getApp().globalData
+const { GRID_DEMO_URL } = getApp().globalData
const app = getApp()
CustomPage({
diff --git a/miniprogram/packageExtend/pages/extend/barrage/barrage.js b/miniprogram/packageExtend/pages/extend/barrage/barrage.js
index aaef7333..666a2e92 100644
--- a/miniprogram/packageExtend/pages/extend/barrage/barrage.js
+++ b/miniprogram/packageExtend/pages/extend/barrage/barrage.js
@@ -1,6 +1,6 @@
import CustomPage from '../../../base/CustomPage'
-const {mockData} = require('./utils')
+const { mockData } = require('./utils')
CustomPage({
onShareAppMessage() {
@@ -43,7 +43,7 @@ CustomPage({
})
setTimeout(() => {
if (this.barrage) this.barrage.close()
- this.setData({toggle: true})
+ this.setData({ toggle: true })
this.addBarrage()
}, 1000)
},
diff --git a/miniprogram/packageExtend/pages/extend/emoji/emoji.js b/miniprogram/packageExtend/pages/extend/emoji/emoji.js
index 54e931d5..f1086cdf 100644
--- a/miniprogram/packageExtend/pages/extend/emoji/emoji.js
+++ b/miniprogram/packageExtend/pages/extend/emoji/emoji.js
@@ -1,5 +1,5 @@
import CustomPage from '../../../base/CustomPage'
-import {compareVersion} from '../../../../util/util'
+import { compareVersion } from '../../../../util/util'
CustomPage({
onShareAppMessage() {
@@ -44,7 +44,7 @@ CustomPage({
},
onReady() {
// 解决基础库小于 2.9.2 的兼容问题
- const {SDKVersion} = wx.getSystemInfoSync()
+ const { SDKVersion } = wx.getSystemInfoSync()
if (compareVersion(SDKVersion, '2.9.1') < 0) {
this.setData({
canIUse: false,
@@ -52,7 +52,7 @@ CustomPage({
}
},
onkeyboardHeightChange(e) {
- const {height} = e.detail
+ const { height } = e.detail
if (height === 0) {
this.data._keyboardShow = false
@@ -108,7 +108,7 @@ CustomPage({
},
insertEmoji(evt) {
const emotionName = evt.detail.emotionName
- const {cursor, comment} = this.data
+ const { cursor, comment } = this.data
const newComment =
comment.slice(0, cursor) + emotionName + comment.slice(cursor)
this.setData({
diff --git a/miniprogram/packageExtend/pages/extend/index-list/index-list.js b/miniprogram/packageExtend/pages/extend/index-list/index-list.js
index 8f30d90c..c5494808 100644
--- a/miniprogram/packageExtend/pages/extend/index-list/index-list.js
+++ b/miniprogram/packageExtend/pages/extend/index-list/index-list.js
@@ -1,4 +1,3 @@
-
import CustomPage from '../../../base/CustomPage'
CustomPage({
@@ -34,7 +33,7 @@ CustomPage({
for (const city of cities) {
const alpha = city.pinyin[0].charAt(0).toUpperCase()
if (!map.has(alpha)) map.set(alpha, [])
- map.get(alpha).push({name: city.fullname})
+ map.get(alpha).push({ name: city.fullname })
}
const keys = []
@@ -51,7 +50,7 @@ CustomPage({
})
}
- _this.setData({list})
+ _this.setData({ list })
}
})
}
diff --git a/miniprogram/packageExtend/pages/extend/tabs/tabs.js b/miniprogram/packageExtend/pages/extend/tabs/tabs.js
index a4b56677..f690f820 100644
--- a/miniprogram/packageExtend/pages/extend/tabs/tabs.js
+++ b/miniprogram/packageExtend/pages/extend/tabs/tabs.js
@@ -45,7 +45,7 @@ CustomPage({
desc: '微信小程序应用开发赛',
},
]
- this.setData({tabs})
+ this.setData({ tabs })
},
onTabClick(e) {
diff --git a/miniprogram/packageExtend/pages/extend/vtabs/vtabs.js b/miniprogram/packageExtend/pages/extend/vtabs/vtabs.js
index 69aefe7d..8038b5f5 100644
--- a/miniprogram/packageExtend/pages/extend/vtabs/vtabs.js
+++ b/miniprogram/packageExtend/pages/extend/vtabs/vtabs.js
@@ -45,7 +45,7 @@ CustomPage({
desc: '微信小程序应用开发赛',
},
]
- this.setData({vtabs: tabs})
+ this.setData({ vtabs: tabs })
},
onTabClick(e) {
diff --git a/miniprogram/packageExtend/pages/extend/wxml-to-canvas/demo.js b/miniprogram/packageExtend/pages/extend/wxml-to-canvas/demo.js
index 29ba63de..5b3cd1d2 100644
--- a/miniprogram/packageExtend/pages/extend/wxml-to-canvas/demo.js
+++ b/miniprogram/packageExtend/pages/extend/wxml-to-canvas/demo.js
@@ -1,4 +1,3 @@
-
const wxml = (url) => `
diff --git a/miniprogram/packageExtend/pages/extend/wxml-to-canvas/wxml-to-canvas.js b/miniprogram/packageExtend/pages/extend/wxml-to-canvas/wxml-to-canvas.js
index 591451e7..c1fe5f9c 100644
--- a/miniprogram/packageExtend/pages/extend/wxml-to-canvas/wxml-to-canvas.js
+++ b/miniprogram/packageExtend/pages/extend/wxml-to-canvas/wxml-to-canvas.js
@@ -1,4 +1,4 @@
-const {wxml, style} = require('./demo.js')
+const { wxml, style } = require('./demo.js')
Page({
onShareAppMessage() {
@@ -26,7 +26,7 @@ Page({
},
renderToCanvas() {
console.log(wxml(this.url))
- const p1 = this.widget.renderToCanvas({wxml: wxml(this.url), style})
+ const p1 = this.widget.renderToCanvas({ wxml: wxml(this.url), style })
p1.then((re) => {
console.log('container', re.layoutBox)
this.data.showCanvas = true
diff --git a/miniprogram/packageExtend/pages/form/cell/cell.js b/miniprogram/packageExtend/pages/form/cell/cell.js
index 2ce9f3d4..532a3ddf 100644
--- a/miniprogram/packageExtend/pages/form/cell/cell.js
+++ b/miniprogram/packageExtend/pages/form/cell/cell.js
@@ -3,25 +3,25 @@ import CustomPage from '../../../base/CustomPage'
const base64 = require('../../images/base64')
CustomPage({
- onLoad() {
- this.setData({
- icon: base64.icon20,
- slideButtons: [{
- text: '普通',
- src: global.isDemo ? '/page/weui/example/cell/icon_love.svg' : '/example/cell/icon_love.svg', // icon的路径
- }, {
- text: '普通',
- extClass: 'test',
- src: global.isDemo ? '/page/weui/example/cell/icon_star.svg' : '/example/cell/icon_star.svg', // icon的路径
- }, {
- type: 'warn',
- text: '警示',
- extClass: 'test',
- src: global.isDemo ? '/page/weui/example/cell/icon_del.svg' : '/example/cell/icon_del.svg', // icon的路径
- }],
- })
-},
-slideButtonTap(e) {
- console.log('slide button tap', e.detail)
-}
+ onLoad() {
+ this.setData({
+ icon: base64.icon20,
+ slideButtons: [{
+ text: '普通',
+ src: global.isDemo ? '/page/weui/example/cell/icon_love.svg' : '/example/cell/icon_love.svg', // icon的路径
+ }, {
+ text: '普通',
+ extClass: 'test',
+ src: global.isDemo ? '/page/weui/example/cell/icon_star.svg' : '/example/cell/icon_star.svg', // icon的路径
+ }, {
+ type: 'warn',
+ text: '警示',
+ extClass: 'test',
+ src: global.isDemo ? '/page/weui/example/cell/icon_del.svg' : '/example/cell/icon_del.svg', // icon的路径
+ }],
+ })
+ },
+ slideButtonTap(e) {
+ console.log('slide button tap', e.detail)
+ }
})
diff --git a/miniprogram/packageExtend/pages/form/form/form.js b/miniprogram/packageExtend/pages/form/form/form.js
index b18068da..a5327701 100644
--- a/miniprogram/packageExtend/pages/form/form/form.js
+++ b/miniprogram/packageExtend/pages/form/form/form.js
@@ -5,20 +5,20 @@ CustomPage({
showTopTips: false,
radioItems: [
- {name: 'cell standard', value: '0', checked: true},
- {name: 'cell standard', value: '1'}
+ { name: 'cell standard', value: '0', checked: true },
+ { name: 'cell standard', value: '1' }
],
checkboxItems: [
- {name: 'standard is dealt for u.', value: '0', checked: true},
- {name: 'standard is dealicient for u.', value: '1'}
+ { name: 'standard is dealt for u.', value: '0', checked: true },
+ { name: 'standard is dealicient for u.', value: '1' }
],
items: [
- {name: 'USA', value: '美国'},
- {name: 'CHN', value: '中国', checked: 'true'},
- {name: 'BRA', value: '巴西'},
- {name: 'JPN', value: '日本'},
- {name: 'ENG', value: '英国'},
- {name: 'TUR', value: '法国'},
+ { name: 'USA', value: '美国' },
+ { name: 'CHN', value: '中国', checked: 'true' },
+ { name: 'BRA', value: '巴西' },
+ { name: 'JPN', value: '日本' },
+ { name: 'ENG', value: '英国' },
+ { name: 'TUR', value: '法国' },
],
date: '2016-09-01',
@@ -39,22 +39,22 @@ CustomPage({
},
rules: [{
name: 'radio',
- rules: {required: false, message: '单选列表是必选项'},
+ rules: { required: false, message: '单选列表是必选项' },
}, {
name: 'checkbox',
- rules: {required: true, message: '多选列表是必选项'},
+ rules: { required: true, message: '多选列表是必选项' },
}, {
name: 'name',
- rules: {required: true, message: '请输入姓名'},
+ rules: { required: true, message: '请输入姓名' },
}, {
name: 'qq',
- rules: {required: true, message: 'qq必填'},
+ rules: { required: true, message: 'qq必填' },
}, {
name: 'mobile',
- rules: [{required: true, message: 'mobile必填'}, {mobile: true, message: 'mobile格式不对'}],
+ rules: [{ required: true, message: 'mobile必填' }, { mobile: true, message: 'mobile格式不对' }],
}, {
name: 'vcode',
- rules: {required: true, message: '验证码必填'},
+ rules: { required: true, message: '验证码必填' },
}, {
name: 'idcard',
rules: {
@@ -108,7 +108,7 @@ CustomPage({
})
},
formInputChange(e) {
- const {field} = e.currentTarget.dataset
+ const { field } = e.currentTarget.dataset
this.setData({
[`formData.${field}`]: e.detail.value
})
diff --git a/miniprogram/packageExtend/pages/navigation/navigation/navigation.js b/miniprogram/packageExtend/pages/navigation/navigation/navigation.js
index 76dfaa1f..b5c127f9 100644
--- a/miniprogram/packageExtend/pages/navigation/navigation/navigation.js
+++ b/miniprogram/packageExtend/pages/navigation/navigation/navigation.js
@@ -1,41 +1,41 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- data: {
- loading: false,
- show: true,
- animated: false,
- title: 'UI组件库'
- },
- toggleLoading() {
- this.setData({
- loading: !this.data.loading
- })
- },
- changeTitle() {
- this.setData({
- title: '修改标题内容之后的标题长这个样子'
- })
- },
- changeColor() {
- this.setData({
- color: '#07C160'
- })
- },
- changeBgColor() {
- this.setData({
- background: '#adadad'
- })
- },
- toggleShow() {
- this.setData({
- show: !this.data.show
- })
- },
- toggleAnimated() {
- this.setData({
- animated: !this.data.animated,
- show: !this.data.show
- })
- }
+ data: {
+ loading: false,
+ show: true,
+ animated: false,
+ title: 'UI组件库'
+ },
+ toggleLoading() {
+ this.setData({
+ loading: !this.data.loading
+ })
+ },
+ changeTitle() {
+ this.setData({
+ title: '修改标题内容之后的标题长这个样子'
+ })
+ },
+ changeColor() {
+ this.setData({
+ color: '#07C160'
+ })
+ },
+ changeBgColor() {
+ this.setData({
+ background: '#adadad'
+ })
+ },
+ toggleShow() {
+ this.setData({
+ show: !this.data.show
+ })
+ },
+ toggleAnimated() {
+ this.setData({
+ animated: !this.data.animated,
+ show: !this.data.show
+ })
+ }
})
diff --git a/miniprogram/packageExtend/pages/navigation/tabbar/tabbar.js b/miniprogram/packageExtend/pages/navigation/tabbar/tabbar.js
index e7e2dfa2..3f6373e8 100644
--- a/miniprogram/packageExtend/pages/navigation/tabbar/tabbar.js
+++ b/miniprogram/packageExtend/pages/navigation/tabbar/tabbar.js
@@ -3,35 +3,35 @@ import CustomPage from '../../../base/CustomPage'
const app = getApp()
CustomPage({
- data: {
- list: [
- {
- text: '微信',
- iconPath: app.globalData.iconTabbar,
- selectedIconPath: app.globalData.iconTabbar,
- badge: '8',
- ariaLabel: '8个新通知'
- },
- {
- text: '通讯录',
- iconPath: app.globalData.iconTabbar,
- selectedIconPath: app.globalData.iconTabbar
- },
- {
- text: '发现',
- iconPath: app.globalData.iconTabbar,
- selectedIconPath: app.globalData.iconTabbar,
- dot: true,
- ariaLabel: '未读'
- },
- {
- text: '我',
- iconPath: app.globalData.iconTabbar,
- selectedIconPath: app.globalData.iconTabbar
- }
- ]
- },
- tabChange(e) {
- console.log('tab change', e)
- }
-})
\ No newline at end of file
+ data: {
+ list: [
+ {
+ text: '微信',
+ iconPath: app.globalData.iconTabbar,
+ selectedIconPath: app.globalData.iconTabbar,
+ badge: '8',
+ ariaLabel: '8个新通知'
+ },
+ {
+ text: '通讯录',
+ iconPath: app.globalData.iconTabbar,
+ selectedIconPath: app.globalData.iconTabbar
+ },
+ {
+ text: '发现',
+ iconPath: app.globalData.iconTabbar,
+ selectedIconPath: app.globalData.iconTabbar,
+ dot: true,
+ ariaLabel: '未读'
+ },
+ {
+ text: '我',
+ iconPath: app.globalData.iconTabbar,
+ selectedIconPath: app.globalData.iconTabbar
+ }
+ ]
+ },
+ tabChange(e) {
+ console.log('tab change', e)
+ }
+})
diff --git a/miniprogram/packageExtend/pages/operate/actionsheet/actionsheet.js b/miniprogram/packageExtend/pages/operate/actionsheet/actionsheet.js
index 6612d3ea..9693d706 100644
--- a/miniprogram/packageExtend/pages/operate/actionsheet/actionsheet.js
+++ b/miniprogram/packageExtend/pages/operate/actionsheet/actionsheet.js
@@ -1,36 +1,36 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- open: function () {
- wx.showActionSheet({
- itemList: ['A', 'B', 'C'],
- success: function (res) {
- if (!res.cancel) {
- console.log(res.tapIndex)
- }
- }
- })
- },
- data: {
- showDialog: false,
- groups: [
- { text: '示例菜单', value: 1 },
- { text: '示例菜单', value: 2 },
- { text: '负向菜单', type: 'warn', value: 3 }
- ]
- },
- openDialog: function () {
- this.setData({
- showDialog: true
- })
- },
- closeDialog: function () {
- this.setData({
- showDialog: false
- })
- },
- btnClick(e) {
- console.log(e)
- this.closeDialog()
- }
+ open() {
+ wx.showActionSheet({
+ itemList: ['A', 'B', 'C'],
+ success(res) {
+ if (!res.cancel) {
+ console.log(res.tapIndex)
+ }
+ }
+ })
+ },
+ data: {
+ showDialog: false,
+ groups: [
+ { text: '示例菜单', value: 1 },
+ { text: '示例菜单', value: 2 },
+ { text: '负向菜单', type: 'warn', value: 3 }
+ ]
+ },
+ openDialog() {
+ this.setData({
+ showDialog: true
+ })
+ },
+ closeDialog() {
+ this.setData({
+ showDialog: false
+ })
+ },
+ btnClick(e) {
+ console.log(e)
+ this.closeDialog()
+ }
})
diff --git a/miniprogram/packageExtend/pages/operate/dialog/dialog.js b/miniprogram/packageExtend/pages/operate/dialog/dialog.js
index 19a32cb0..d396eba8 100644
--- a/miniprogram/packageExtend/pages/operate/dialog/dialog.js
+++ b/miniprogram/packageExtend/pages/operate/dialog/dialog.js
@@ -1,27 +1,26 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- data: {
- dialogShow: false,
- showOneButtonDialog: false,
- buttons: [{ text: '取消' }, { text: '确定' }],
- oneButton: [{ text: '确定' }]
- },
- openConfirm: function () {
- this.setData({
- dialogShow: true
- })
- },
- tapDialogButton(e) {
- this.setData({
- dialogShow: false,
- showOneButtonDialog: false
- })
- },
- tapOneDialogButton(e) {
- this.setData({
- showOneButtonDialog: true
- })
- }
+ data: {
+ dialogShow: false,
+ showOneButtonDialog: false,
+ buttons: [{ text: '取消' }, { text: '确定' }],
+ oneButton: [{ text: '确定' }]
+ },
+ openConfirm() {
+ this.setData({
+ dialogShow: true
+ })
+ },
+ tapDialogButton(e) {
+ this.setData({
+ dialogShow: false,
+ showOneButtonDialog: false
+ })
+ },
+ tapOneDialogButton(e) {
+ this.setData({
+ showOneButtonDialog: true
+ })
+ }
})
-
diff --git a/miniprogram/packageExtend/pages/operate/msg/msg.js b/miniprogram/packageExtend/pages/operate/msg/msg.js
index 7522c908..69d75030 100644
--- a/miniprogram/packageExtend/pages/operate/msg/msg.js
+++ b/miniprogram/packageExtend/pages/operate/msg/msg.js
@@ -1,24 +1,24 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- openSuccess: function () {
- wx.navigateTo({
- url: 'msg_success'
- })
- },
- openText: function () {
- wx.navigateTo({
- url: 'msg_text'
- })
- },
- openTextPrimary: function () {
- wx.navigateTo({
- url: 'msg_text_primary'
- })
- },
- openFail: function () {
- wx.navigateTo({
- url: 'msg_fail'
- })
- }
-});
+ openSuccess() {
+ wx.navigateTo({
+ url: 'msg_success'
+ })
+ },
+ openText() {
+ wx.navigateTo({
+ url: 'msg_text'
+ })
+ },
+ openTextPrimary() {
+ wx.navigateTo({
+ url: 'msg_text_primary'
+ })
+ },
+ openFail() {
+ wx.navigateTo({
+ url: 'msg_fail'
+ })
+ }
+})
diff --git a/miniprogram/packageExtend/pages/operate/msg/msg_text.js b/miniprogram/packageExtend/pages/operate/msg/msg_text.js
index ad63b245..828e7e4a 100644
--- a/miniprogram/packageExtend/pages/operate/msg/msg_text.js
+++ b/miniprogram/packageExtend/pages/operate/msg/msg_text.js
@@ -1,4 +1,3 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({})
-
diff --git a/miniprogram/packageExtend/pages/operate/toptips/toptips.js b/miniprogram/packageExtend/pages/operate/toptips/toptips.js
index a2a375f4..aefd36f8 100644
--- a/miniprogram/packageExtend/pages/operate/toptips/toptips.js
+++ b/miniprogram/packageExtend/pages/operate/toptips/toptips.js
@@ -1,24 +1,24 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- data: {
- show1: false,
- show2: false,
- show3: false
- },
- showToptips1() {
- this.setData({
- show1: true
- })
- },
- showToptips2() {
- this.setData({
- show2: true
- })
- },
- showToptips3() {
- this.setData({
- show3: true
- })
- }
+ data: {
+ show1: false,
+ show2: false,
+ show3: false
+ },
+ showToptips1() {
+ this.setData({
+ show1: true
+ })
+ },
+ showToptips2() {
+ this.setData({
+ show2: true
+ })
+ },
+ showToptips3() {
+ this.setData({
+ show3: true
+ })
+ }
})
diff --git a/miniprogram/packageExtend/pages/search/searchbar/searchbar.js b/miniprogram/packageExtend/pages/search/searchbar/searchbar.js
index 6ea2bacd..9e4390a9 100644
--- a/miniprogram/packageExtend/pages/search/searchbar/searchbar.js
+++ b/miniprogram/packageExtend/pages/search/searchbar/searchbar.js
@@ -1,34 +1,33 @@
import CustomPage from '../../../base/CustomPage'
CustomPage({
- data: {
- inputShowed: false,
- inputVal: "",
- i: 0
- },
- onLoad() {
- this.setData({
- search: this.search.bind(this)
- })
- },
- search: function (value) {
- return new Promise((resolve, reject) => {
- if (this.data.i % 2 === 0) {
- setTimeout(() => {
- resolve([{text: '搜索结果', value: 1}, {text: '搜索结果2', value: 2}])
- }, 200)
- } else {
- setTimeout(() => {
- resolve([])
- }, 200)
-
- }
- this.setData({
- i: this.data.i + 1
- })
- })
- },
- selectResult: function (e) {
- console.log('select result', e.detail)
- },
-});
+ data: {
+ inputShowed: false,
+ inputVal: '',
+ i: 0
+ },
+ onLoad() {
+ this.setData({
+ search: this.search.bind(this)
+ })
+ },
+ search(value) {
+ return new Promise((resolve, reject) => {
+ if (this.data.i % 2 === 0) {
+ setTimeout(() => {
+ resolve([{ text: '搜索结果', value: 1 }, { text: '搜索结果2', value: 2 }])
+ }, 200)
+ } else {
+ setTimeout(() => {
+ resolve([])
+ }, 200)
+ }
+ this.setData({
+ i: this.data.i + 1
+ })
+ })
+ },
+ selectResult(e) {
+ console.log('select result', e.detail)
+ },
+})
diff --git a/miniprogram/packageSkyline/common/custom-route/common.js b/miniprogram/packageSkyline/common/custom-route/common.js
index ef2ceab3..2cda64ec 100644
--- a/miniprogram/packageSkyline/common/custom-route/common.js
+++ b/miniprogram/packageSkyline/common/custom-route/common.js
@@ -29,7 +29,7 @@ export const AnimationStatus = {
export const Curves = {}
if (wx.worklet) {
- const {Easing} = wx.worklet
+ const { Easing } = wx.worklet
Object.assign(Curves, {
fastLinearToSlowEaseIn: Easing.bezier(0.18, 1.0, 0.04, 1.0).factory(),
linearToEaseOut: Easing.bezier(0.35, 0.91, 0.33, 0.97).factory(),
@@ -55,7 +55,7 @@ export const clamp = function (cur, lowerBound, upperBound) {
export function CurveAnimation({
animation, animationStatus, curve, reverseCurve
}) {
- const {derived} = wx.worklet
+ const { derived } = wx.worklet
return derived(() => {
'worklet'
diff --git a/miniprogram/packageSkyline/common/custom-route/cupertino-route.js b/miniprogram/packageSkyline/common/custom-route/cupertino-route.js
index b8036114..ed036046 100644
--- a/miniprogram/packageSkyline/common/custom-route/cupertino-route.js
+++ b/miniprogram/packageSkyline/common/custom-route/cupertino-route.js
@@ -1,5 +1,4 @@
-
-import {CurveAnimation, Curves} from './common'
+import { CurveAnimation, Curves } from './common'
/**
* 仿 iOS 返回自定义路由
@@ -11,7 +10,7 @@ export const CupertinoRouteBuilder = ({
secondaryAnimationStatus,
userGestureInProgress,
}) => {
- const {windowWidth} = wx.getSystemInfoSync()
+ const { windowWidth } = wx.getSystemInfoSync()
const _curvePrimaryAnimation = CurveAnimation({
animation: primaryAnimation,
@@ -35,7 +34,7 @@ export const CupertinoRouteBuilder = ({
// 页面从右至左推入
return {
- transform: [{translateX: windowWidth * (1 - t)}],
+ transform: [{ translateX: windowWidth * (1 - t) }],
}
}
@@ -56,7 +55,7 @@ export const CupertinoRouteBuilder = ({
// 下一个页面推入时,当前页面继续向左推入 1/3
return {
- transform: [{translateX: (-1 / 3) * windowWidth * t}],
+ transform: [{ translateX: (-1 / 3) * windowWidth * t }],
}
}
diff --git a/miniprogram/packageSkyline/common/custom-route/hafl-screen-route.js b/miniprogram/packageSkyline/common/custom-route/hafl-screen-route.js
index e5985587..b2ec3513 100644
--- a/miniprogram/packageSkyline/common/custom-route/hafl-screen-route.js
+++ b/miniprogram/packageSkyline/common/custom-route/hafl-screen-route.js
@@ -1,11 +1,11 @@
-import {CurveAnimation, Curves} from './common'
+import { CurveAnimation, Curves } from './common'
const HalfScreenDialogRouteBuilder = ({
primaryAnimation,
primaryAnimationStatus,
userGestureInProgress,
}) => {
- const {screenHeight} = getApp().globalData
+ const { screenHeight } = getApp().globalData
console.info('HalfScreenDialogRouteBuilder ', screenHeight)
const _curvePrimaryAnimation = CurveAnimation({
diff --git a/miniprogram/packageSkyline/common/custom-route/opacity-route.js b/miniprogram/packageSkyline/common/custom-route/opacity-route.js
index 4fc47558..4263cd95 100644
--- a/miniprogram/packageSkyline/common/custom-route/opacity-route.js
+++ b/miniprogram/packageSkyline/common/custom-route/opacity-route.js
@@ -1,6 +1,6 @@
-import {Curves} from './common'
+import { Curves } from './common'
-const OpacityTransitionRouteBuilder = ({primaryAnimation}) => {
+const OpacityTransitionRouteBuilder = ({ primaryAnimation }) => {
const handlePrimaryAnimation = () => {
'worklet'
diff --git a/miniprogram/packageSkyline/common/custom-route/scale-route.js b/miniprogram/packageSkyline/common/custom-route/scale-route.js
index 6655ff71..84144719 100644
--- a/miniprogram/packageSkyline/common/custom-route/scale-route.js
+++ b/miniprogram/packageSkyline/common/custom-route/scale-route.js
@@ -1,4 +1,4 @@
-import {CurveAnimation, Curves} from './common'
+import { CurveAnimation, Curves } from './common'
const ScaleTransitionRouteBuilder = ({
primaryAnimation,
@@ -7,8 +7,8 @@ const ScaleTransitionRouteBuilder = ({
secondaryAnimationStatus,
userGestureInProgress,
}) => {
- const {windowWidth} = getApp().globalData
- const {screenHeight} = getApp().globalData
+ const { windowWidth } = getApp().globalData
+ const { screenHeight } = getApp().globalData
console.info('ScaleTransitionRouteBuilder ', windowWidth)
const _curvePrimaryAnimation = CurveAnimation({
diff --git a/miniprogram/packageSkyline/common/custom-route/util.js b/miniprogram/packageSkyline/common/custom-route/util.js
index d6db2d47..2ad744cd 100644
--- a/miniprogram/packageSkyline/common/custom-route/util.js
+++ b/miniprogram/packageSkyline/common/custom-route/util.js
@@ -24,10 +24,9 @@ function compareVersion(v1, v2) {
return 0
}
-
export function isOfficialSkyline() {
if (!wx.getSkylineInfoSync) return false
- const {isSupported, version} = wx.getSkylineInfoSync()
+ const { isSupported, version } = wx.getSkylineInfoSync()
if (!isSupported) return false
return compareVersion(version, '1.0.1') >= 0
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageSkyline/common/tips.js b/miniprogram/packageSkyline/common/tips.js
index 79a3fcc1..f41200c8 100644
--- a/miniprogram/packageSkyline/common/tips.js
+++ b/miniprogram/packageSkyline/common/tips.js
@@ -1,7 +1,7 @@
-export function showTips () {
+export function showTips() {
wx.showToast({
title: '该版本暂不支持 Skyline',
icon: 'none',
duration: 3000
})
-}
\ No newline at end of file
+}
diff --git a/miniprogram/packageSkyline/common/types.js b/miniprogram/packageSkyline/common/types.js
index 2eaad9d0..9d6cbda4 100644
--- a/miniprogram/packageSkyline/common/types.js
+++ b/miniprogram/packageSkyline/common/types.js
@@ -21,4 +21,4 @@ export const IPointerEvent = {
tilt: 'number',
force: 'number',
timeStamp: 'number',
-};
+}
diff --git a/miniprogram/packageSkyline/common/worklet-api.js b/miniprogram/packageSkyline/common/worklet-api.js
index 5faa7637..1330fa5c 100644
--- a/miniprogram/packageSkyline/common/worklet-api.js
+++ b/miniprogram/packageSkyline/common/worklet-api.js
@@ -1,7 +1,7 @@
function foo() {}
function bar() {
- 'worklet';
+ 'worklet'
}
export const worklet = {
@@ -14,24 +14,24 @@ export const worklet = {
timing: bar,
decay: bar,
Easing: {},
-};
+}
export const router = {
addRouteBuilder: foo,
removeRouteBuilder: foo,
getRouteContext: foo,
-};
+}
if (wx.worklet) {
- Object.assign(worklet, wx.worklet);
+ Object.assign(worklet, wx.worklet)
}
if (wx.router) {
- Object.assign(router, wx.router);
+ Object.assign(router, wx.router)
}
export function supportWorklet() {
- return typeof wx.worklet === 'object' && typeof wx.worklet.shared === 'function';
+ return typeof wx.worklet === 'object' && typeof wx.worklet.shared === 'function'
}
export function shared(args) {
diff --git a/miniprogram/packageSkyline/pages/base.js b/miniprogram/packageSkyline/pages/base.js
index 02720c18..e7a6f7cd 100644
--- a/miniprogram/packageSkyline/pages/base.js
+++ b/miniprogram/packageSkyline/pages/base.js
@@ -5,6 +5,7 @@ export default Behavior({
created() {
runOnUI(() => {
'worklet'
+
if (!globalThis.temp) globalThis.temp = {}
if (!globalThis.eventBus) {
const eventBus = {
diff --git a/miniprogram/packageSkyline/pages/half-page/half-page/index.less b/miniprogram/packageSkyline/pages/half-page/half-page/index.less
index 31fe010e..cf130348 100644
--- a/miniprogram/packageSkyline/pages/half-page/half-page/index.less
+++ b/miniprogram/packageSkyline/pages/half-page/half-page/index.less
@@ -1,6 +1,15 @@
page {
padding: 15px 0;
}
+
+.comment-container {
+ width: 100%;
+ height: 100%;
+ padding-top: 40px;
+ display: flex;
+ flex-direction: column;
+}
+
.bottom-sheet {
position: relative;
display: flex;
@@ -9,6 +18,7 @@ page {
justify-content: center;
height: 50px;
}
+
.bottom-sheet .btn-wrp {
position: absolute;
left: 0;
@@ -18,6 +28,7 @@ page {
align-items: center;
justify-content: center;
}
+
.bottom-sheet .btn {
width: 24px;
height: 24px;
@@ -27,13 +38,16 @@ page {
align-items: center;
justify-content: center;
}
+
.bottom-sheet .icon {
width: 12px;
height: 12px;
}
+
.bottom-sheet .title {
font-size: 18px;
}
+
.comment-item {
// width: 100%;
// height: 60px;
@@ -42,6 +56,7 @@ page {
// flex-direction: row;
// align-items: center;
}
+
.avatar {
width: 40px;
height: 40px;
@@ -49,6 +64,7 @@ page {
border-radius: 50%;
background: #ccc;
}
+
/* .comment {
height: 40px;
flex-grow: 1;
@@ -74,7 +90,8 @@ page {
font-size: 13px;
line-height: 1.4;
- .main-comment, .sub-comment {
+ .main-comment,
+ .sub-comment {
width: 100%;
display: flex;
flex-direction: row;
diff --git a/miniprogram/packageSkyline/pages/half-page/half-page/index.wxml b/miniprogram/packageSkyline/pages/half-page/half-page/index.wxml
index 5feea3fb..4b268a8f 100644
--- a/miniprogram/packageSkyline/pages/half-page/half-page/index.wxml
+++ b/miniprogram/packageSkyline/pages/half-page/half-page/index.wxml
@@ -1,6 +1,6 @@
-
+