diff --git a/.eslintrc.js b/.eslintrc.js index 141fa110..e528da9b 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', @@ -64,7 +64,7 @@ module.exports = { '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..d906026d --- /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: 'wx622bee4f78fa4f5a', + 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..5b0909ce 100644 --- a/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js +++ b/cloudfunctions/ARDemo/cloud-functions-tools/cli/svrkit-utils-template.js @@ -1,12 +1,11 @@ - function generate(options) { if (!options) { throw new Error('options must be provided') } - const { serviceName, funcName, data } = 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') } @@ -64,7 +63,7 @@ function generateV2(options) { throw new Error('options must be provided') } - const { apiName, data } = options + const {apiName, data} = options const apiConfig = config.find(c => c.apiName === apiName) @@ -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/cloud-functions-tools/test/svrkit-utils/example/bundle.js b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/bundle.js index f0247d6e..95d6a4e5 100644 --- a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/bundle.js +++ b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/bundle.js @@ -1,17 +1,16 @@ -/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ -"use strict"; +/* eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars */ -var $protobuf = require("protobufjs/minimal"); +var $protobuf = require('protobufjs/minimal') // Common aliases -var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; +var $Reader = $protobuf.Reader; var $Writer = $protobuf.Writer; var + $util = $protobuf.util // Exported root namespace -var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); +var $root = $protobuf.roots.default || ($protobuf.roots.default = {}) -$root.GenWxaCloudTmpCodeReq = (function() { - - /** +$root.GenWxaCloudTmpCodeReq = (function () { + /** * Properties of a GenWxaCloudTmpCodeReq. * @exports IGenWxaCloudTmpCodeReq * @interface IGenWxaCloudTmpCodeReq @@ -20,7 +19,7 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @property {number|null} [UserUin] GenWxaCloudTmpCodeReq UserUin */ - /** + /** * Constructs a new GenWxaCloudTmpCodeReq. * @exports GenWxaCloudTmpCodeReq * @classdesc Represents a GenWxaCloudTmpCodeReq. @@ -28,38 +27,35 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @constructor * @param {IGenWxaCloudTmpCodeReq=} [properties] Properties to set */ - function GenWxaCloudTmpCodeReq(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function GenWxaCloudTmpCodeReq(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * GenWxaCloudTmpCodeReq CloudPlatform. * @member {number} CloudPlatform * @memberof GenWxaCloudTmpCodeReq * @instance */ - GenWxaCloudTmpCodeReq.prototype.CloudPlatform = 0; + GenWxaCloudTmpCodeReq.prototype.CloudPlatform = 0 - /** + /** * GenWxaCloudTmpCodeReq AppUin. * @member {number} AppUin * @memberof GenWxaCloudTmpCodeReq * @instance */ - GenWxaCloudTmpCodeReq.prototype.AppUin = 0; + GenWxaCloudTmpCodeReq.prototype.AppUin = 0 - /** + /** * GenWxaCloudTmpCodeReq UserUin. * @member {number} UserUin * @memberof GenWxaCloudTmpCodeReq * @instance */ - GenWxaCloudTmpCodeReq.prototype.UserUin = 0; + GenWxaCloudTmpCodeReq.prototype.UserUin = 0 - /** + /** * Creates a new GenWxaCloudTmpCodeReq instance using the specified properties. * @function create * @memberof GenWxaCloudTmpCodeReq @@ -67,11 +63,11 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {IGenWxaCloudTmpCodeReq=} [properties] Properties to set * @returns {GenWxaCloudTmpCodeReq} GenWxaCloudTmpCodeReq instance */ - GenWxaCloudTmpCodeReq.create = function create(properties) { - return new GenWxaCloudTmpCodeReq(properties); - }; + GenWxaCloudTmpCodeReq.create = function create(properties) { + return new GenWxaCloudTmpCodeReq(properties) + } - /** + /** * Encodes the specified GenWxaCloudTmpCodeReq message. Does not implicitly {@link GenWxaCloudTmpCodeReq.verify|verify} messages. * @function encode * @memberof GenWxaCloudTmpCodeReq @@ -80,19 +76,15 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GenWxaCloudTmpCodeReq.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.CloudPlatform != null && message.hasOwnProperty("CloudPlatform")) - writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.CloudPlatform); - if (message.AppUin != null && message.hasOwnProperty("AppUin")) - writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.AppUin); - if (message.UserUin != null && message.hasOwnProperty("UserUin")) - writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.UserUin); - return writer; - }; - - /** + GenWxaCloudTmpCodeReq.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.CloudPlatform != null && message.hasOwnProperty('CloudPlatform')) writer.uint32(/* id 1, wireType 0 = */8).uint32(message.CloudPlatform) + if (message.AppUin != null && message.hasOwnProperty('AppUin')) writer.uint32(/* id 2, wireType 0 = */16).uint32(message.AppUin) + if (message.UserUin != null && message.hasOwnProperty('UserUin')) writer.uint32(/* id 3, wireType 0 = */24).uint32(message.UserUin) + return writer + } + + /** * Encodes the specified GenWxaCloudTmpCodeReq message, length delimited. Does not implicitly {@link GenWxaCloudTmpCodeReq.verify|verify} messages. * @function encodeDelimited * @memberof GenWxaCloudTmpCodeReq @@ -101,11 +93,11 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GenWxaCloudTmpCodeReq.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + GenWxaCloudTmpCodeReq.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a GenWxaCloudTmpCodeReq message from the specified reader or buffer. * @function decode * @memberof GenWxaCloudTmpCodeReq @@ -116,31 +108,31 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GenWxaCloudTmpCodeReq.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.GenWxaCloudTmpCodeReq(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.CloudPlatform = reader.uint32(); - break; - case 2: - message.AppUin = reader.uint32(); - break; - case 3: - message.UserUin = reader.uint32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** + GenWxaCloudTmpCodeReq.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.GenWxaCloudTmpCodeReq() + while (reader.pos < end) { + var tag = reader.uint32() + switch (tag >>> 3) { + case 1: + message.CloudPlatform = reader.uint32() + break + case 2: + message.AppUin = reader.uint32() + break + case 3: + message.UserUin = reader.uint32() + break + default: + reader.skipType(tag & 7) + break + } + } + return message + } + + /** * Decodes a GenWxaCloudTmpCodeReq message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof GenWxaCloudTmpCodeReq @@ -150,13 +142,12 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GenWxaCloudTmpCodeReq.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + GenWxaCloudTmpCodeReq.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a GenWxaCloudTmpCodeReq message. * @function verify * @memberof GenWxaCloudTmpCodeReq @@ -164,22 +155,15 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GenWxaCloudTmpCodeReq.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.CloudPlatform != null && message.hasOwnProperty("CloudPlatform")) - if (!$util.isInteger(message.CloudPlatform)) - return "CloudPlatform: integer expected"; - if (message.AppUin != null && message.hasOwnProperty("AppUin")) - if (!$util.isInteger(message.AppUin)) - return "AppUin: integer expected"; - if (message.UserUin != null && message.hasOwnProperty("UserUin")) - if (!$util.isInteger(message.UserUin)) - return "UserUin: integer expected"; - return null; - }; - - /** + GenWxaCloudTmpCodeReq.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.CloudPlatform != null && message.hasOwnProperty('CloudPlatform')) if (!$util.isInteger(message.CloudPlatform)) return 'CloudPlatform: integer expected' + if (message.AppUin != null && message.hasOwnProperty('AppUin')) if (!$util.isInteger(message.AppUin)) return 'AppUin: integer expected' + if (message.UserUin != null && message.hasOwnProperty('UserUin')) if (!$util.isInteger(message.UserUin)) return 'UserUin: integer expected' + return null + } + + /** * Creates a GenWxaCloudTmpCodeReq message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof GenWxaCloudTmpCodeReq @@ -187,20 +171,16 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {Object.} object Plain object * @returns {GenWxaCloudTmpCodeReq} GenWxaCloudTmpCodeReq */ - GenWxaCloudTmpCodeReq.fromObject = function fromObject(object) { - if (object instanceof $root.GenWxaCloudTmpCodeReq) - return object; - var message = new $root.GenWxaCloudTmpCodeReq(); - if (object.CloudPlatform != null) - message.CloudPlatform = object.CloudPlatform >>> 0; - if (object.AppUin != null) - message.AppUin = object.AppUin >>> 0; - if (object.UserUin != null) - message.UserUin = object.UserUin >>> 0; - return message; - }; - - /** + GenWxaCloudTmpCodeReq.fromObject = function fromObject(object) { + if (object instanceof $root.GenWxaCloudTmpCodeReq) return object + var message = new $root.GenWxaCloudTmpCodeReq() + if (object.CloudPlatform != null) message.CloudPlatform = object.CloudPlatform >>> 0 + if (object.AppUin != null) message.AppUin = object.AppUin >>> 0 + if (object.UserUin != null) message.UserUin = object.UserUin >>> 0 + return message + } + + /** * Creates a plain object from a GenWxaCloudTmpCodeReq message. Also converts values to other types if specified. * @function toObject * @memberof GenWxaCloudTmpCodeReq @@ -209,48 +189,43 @@ $root.GenWxaCloudTmpCodeReq = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GenWxaCloudTmpCodeReq.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.CloudPlatform = 0; - object.AppUin = 0; - object.UserUin = 0; - } - if (message.CloudPlatform != null && message.hasOwnProperty("CloudPlatform")) - object.CloudPlatform = message.CloudPlatform; - if (message.AppUin != null && message.hasOwnProperty("AppUin")) - object.AppUin = message.AppUin; - if (message.UserUin != null && message.hasOwnProperty("UserUin")) - object.UserUin = message.UserUin; - return object; - }; - - /** + GenWxaCloudTmpCodeReq.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.CloudPlatform = 0 + object.AppUin = 0 + object.UserUin = 0 + } + if (message.CloudPlatform != null && message.hasOwnProperty('CloudPlatform')) object.CloudPlatform = message.CloudPlatform + if (message.AppUin != null && message.hasOwnProperty('AppUin')) object.AppUin = message.AppUin + if (message.UserUin != null && message.hasOwnProperty('UserUin')) object.UserUin = message.UserUin + return object + } + + /** * Converts this GenWxaCloudTmpCodeReq to JSON. * @function toJSON * @memberof GenWxaCloudTmpCodeReq * @instance * @returns {Object.} JSON object */ - GenWxaCloudTmpCodeReq.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GenWxaCloudTmpCodeReq; -})(); + GenWxaCloudTmpCodeReq.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.GenWxaCloudTmpCodeResp = (function() { + return GenWxaCloudTmpCodeReq +}()) - /** +$root.GenWxaCloudTmpCodeResp = (function () { + /** * Properties of a GenWxaCloudTmpCodeResp. * @exports IGenWxaCloudTmpCodeResp * @interface IGenWxaCloudTmpCodeResp * @property {string|null} [TmpCode] GenWxaCloudTmpCodeResp TmpCode */ - /** + /** * Constructs a new GenWxaCloudTmpCodeResp. * @exports GenWxaCloudTmpCodeResp * @classdesc Represents a GenWxaCloudTmpCodeResp. @@ -258,22 +233,19 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @constructor * @param {IGenWxaCloudTmpCodeResp=} [properties] Properties to set */ - function GenWxaCloudTmpCodeResp(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function GenWxaCloudTmpCodeResp(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * GenWxaCloudTmpCodeResp TmpCode. * @member {string} TmpCode * @memberof GenWxaCloudTmpCodeResp * @instance */ - GenWxaCloudTmpCodeResp.prototype.TmpCode = ""; + GenWxaCloudTmpCodeResp.prototype.TmpCode = '' - /** + /** * Creates a new GenWxaCloudTmpCodeResp instance using the specified properties. * @function create * @memberof GenWxaCloudTmpCodeResp @@ -281,11 +253,11 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {IGenWxaCloudTmpCodeResp=} [properties] Properties to set * @returns {GenWxaCloudTmpCodeResp} GenWxaCloudTmpCodeResp instance */ - GenWxaCloudTmpCodeResp.create = function create(properties) { - return new GenWxaCloudTmpCodeResp(properties); - }; + GenWxaCloudTmpCodeResp.create = function create(properties) { + return new GenWxaCloudTmpCodeResp(properties) + } - /** + /** * Encodes the specified GenWxaCloudTmpCodeResp message. Does not implicitly {@link GenWxaCloudTmpCodeResp.verify|verify} messages. * @function encode * @memberof GenWxaCloudTmpCodeResp @@ -294,15 +266,13 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GenWxaCloudTmpCodeResp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.TmpCode != null && message.hasOwnProperty("TmpCode")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.TmpCode); - return writer; - }; + GenWxaCloudTmpCodeResp.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.TmpCode != null && message.hasOwnProperty('TmpCode')) writer.uint32(/* id 1, wireType 2 = */10).string(message.TmpCode) + return writer + } - /** + /** * Encodes the specified GenWxaCloudTmpCodeResp message, length delimited. Does not implicitly {@link GenWxaCloudTmpCodeResp.verify|verify} messages. * @function encodeDelimited * @memberof GenWxaCloudTmpCodeResp @@ -311,11 +281,11 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GenWxaCloudTmpCodeResp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + GenWxaCloudTmpCodeResp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a GenWxaCloudTmpCodeResp message from the specified reader or buffer. * @function decode * @memberof GenWxaCloudTmpCodeResp @@ -326,25 +296,25 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GenWxaCloudTmpCodeResp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.GenWxaCloudTmpCodeResp(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.TmpCode = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** + GenWxaCloudTmpCodeResp.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.GenWxaCloudTmpCodeResp() + while (reader.pos < end) { + var tag = reader.uint32() + switch (tag >>> 3) { + case 1: + message.TmpCode = reader.string() + break + default: + reader.skipType(tag & 7) + break + } + } + return message + } + + /** * Decodes a GenWxaCloudTmpCodeResp message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof GenWxaCloudTmpCodeResp @@ -354,13 +324,12 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GenWxaCloudTmpCodeResp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + GenWxaCloudTmpCodeResp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a GenWxaCloudTmpCodeResp message. * @function verify * @memberof GenWxaCloudTmpCodeResp @@ -368,16 +337,13 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GenWxaCloudTmpCodeResp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.TmpCode != null && message.hasOwnProperty("TmpCode")) - if (!$util.isString(message.TmpCode)) - return "TmpCode: string expected"; - return null; - }; + GenWxaCloudTmpCodeResp.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.TmpCode != null && message.hasOwnProperty('TmpCode')) if (!$util.isString(message.TmpCode)) return 'TmpCode: string expected' + return null + } - /** + /** * Creates a GenWxaCloudTmpCodeResp message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof GenWxaCloudTmpCodeResp @@ -385,16 +351,14 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {Object.} object Plain object * @returns {GenWxaCloudTmpCodeResp} GenWxaCloudTmpCodeResp */ - GenWxaCloudTmpCodeResp.fromObject = function fromObject(object) { - if (object instanceof $root.GenWxaCloudTmpCodeResp) - return object; - var message = new $root.GenWxaCloudTmpCodeResp(); - if (object.TmpCode != null) - message.TmpCode = String(object.TmpCode); - return message; - }; + GenWxaCloudTmpCodeResp.fromObject = function fromObject(object) { + if (object instanceof $root.GenWxaCloudTmpCodeResp) return object + var message = new $root.GenWxaCloudTmpCodeResp() + if (object.TmpCode != null) message.TmpCode = String(object.TmpCode) + return message + } - /** + /** * Creates a plain object from a GenWxaCloudTmpCodeResp message. Also converts values to other types if specified. * @function toObject * @memberof GenWxaCloudTmpCodeResp @@ -403,34 +367,30 @@ $root.GenWxaCloudTmpCodeResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GenWxaCloudTmpCodeResp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.TmpCode = ""; - if (message.TmpCode != null && message.hasOwnProperty("TmpCode")) - object.TmpCode = message.TmpCode; - return object; - }; - - /** + GenWxaCloudTmpCodeResp.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) object.TmpCode = '' + if (message.TmpCode != null && message.hasOwnProperty('TmpCode')) object.TmpCode = message.TmpCode + return object + } + + /** * Converts this GenWxaCloudTmpCodeResp to JSON. * @function toJSON * @memberof GenWxaCloudTmpCodeResp * @instance * @returns {Object.} JSON object */ - GenWxaCloudTmpCodeResp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GenWxaCloudTmpCodeResp; -})(); + GenWxaCloudTmpCodeResp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.GetWeAppMemberByUserReq = (function() { + return GenWxaCloudTmpCodeResp +}()) - /** +$root.GetWeAppMemberByUserReq = (function () { + /** * Properties of a GetWeAppMemberByUserReq. * @exports IGetWeAppMemberByUserReq * @interface IGetWeAppMemberByUserReq @@ -439,7 +399,7 @@ $root.GetWeAppMemberByUserReq = (function() { * @property {number|null} [status] GetWeAppMemberByUserReq status */ - /** + /** * Constructs a new GetWeAppMemberByUserReq. * @exports GetWeAppMemberByUserReq * @classdesc Represents a GetWeAppMemberByUserReq. @@ -447,38 +407,35 @@ $root.GetWeAppMemberByUserReq = (function() { * @constructor * @param {IGetWeAppMemberByUserReq=} [properties] Properties to set */ - function GetWeAppMemberByUserReq(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function GetWeAppMemberByUserReq(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * GetWeAppMemberByUserReq useruin. * @member {number} useruin * @memberof GetWeAppMemberByUserReq * @instance */ - GetWeAppMemberByUserReq.prototype.useruin = 0; + GetWeAppMemberByUserReq.prototype.useruin = 0 - /** + /** * GetWeAppMemberByUserReq type. * @member {number} type * @memberof GetWeAppMemberByUserReq * @instance */ - GetWeAppMemberByUserReq.prototype.type = 0; + GetWeAppMemberByUserReq.prototype.type = 0 - /** + /** * GetWeAppMemberByUserReq status. * @member {number} status * @memberof GetWeAppMemberByUserReq * @instance */ - GetWeAppMemberByUserReq.prototype.status = 0; + GetWeAppMemberByUserReq.prototype.status = 0 - /** + /** * Creates a new GetWeAppMemberByUserReq instance using the specified properties. * @function create * @memberof GetWeAppMemberByUserReq @@ -486,11 +443,11 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {IGetWeAppMemberByUserReq=} [properties] Properties to set * @returns {GetWeAppMemberByUserReq} GetWeAppMemberByUserReq instance */ - GetWeAppMemberByUserReq.create = function create(properties) { - return new GetWeAppMemberByUserReq(properties); - }; + GetWeAppMemberByUserReq.create = function create(properties) { + return new GetWeAppMemberByUserReq(properties) + } - /** + /** * Encodes the specified GetWeAppMemberByUserReq message. Does not implicitly {@link GetWeAppMemberByUserReq.verify|verify} messages. * @function encode * @memberof GetWeAppMemberByUserReq @@ -499,19 +456,15 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetWeAppMemberByUserReq.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.useruin != null && message.hasOwnProperty("useruin")) - writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.useruin); - if (message.type != null && message.hasOwnProperty("type")) - writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.type); - if (message.status != null && message.hasOwnProperty("status")) - writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.status); - return writer; - }; - - /** + GetWeAppMemberByUserReq.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.useruin != null && message.hasOwnProperty('useruin')) writer.uint32(/* id 1, wireType 0 = */8).uint32(message.useruin) + if (message.type != null && message.hasOwnProperty('type')) writer.uint32(/* id 2, wireType 0 = */16).uint32(message.type) + if (message.status != null && message.hasOwnProperty('status')) writer.uint32(/* id 3, wireType 0 = */24).uint32(message.status) + return writer + } + + /** * Encodes the specified GetWeAppMemberByUserReq message, length delimited. Does not implicitly {@link GetWeAppMemberByUserReq.verify|verify} messages. * @function encodeDelimited * @memberof GetWeAppMemberByUserReq @@ -520,11 +473,11 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetWeAppMemberByUserReq.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + GetWeAppMemberByUserReq.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a GetWeAppMemberByUserReq message from the specified reader or buffer. * @function decode * @memberof GetWeAppMemberByUserReq @@ -535,31 +488,31 @@ $root.GetWeAppMemberByUserReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetWeAppMemberByUserReq.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.GetWeAppMemberByUserReq(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.useruin = reader.uint32(); - break; - case 2: - message.type = reader.uint32(); - break; - case 3: - message.status = reader.uint32(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** + GetWeAppMemberByUserReq.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.GetWeAppMemberByUserReq() + while (reader.pos < end) { + var tag = reader.uint32() + switch (tag >>> 3) { + case 1: + message.useruin = reader.uint32() + break + case 2: + message.type = reader.uint32() + break + case 3: + message.status = reader.uint32() + break + default: + reader.skipType(tag & 7) + break + } + } + return message + } + + /** * Decodes a GetWeAppMemberByUserReq message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof GetWeAppMemberByUserReq @@ -569,13 +522,12 @@ $root.GetWeAppMemberByUserReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetWeAppMemberByUserReq.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + GetWeAppMemberByUserReq.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a GetWeAppMemberByUserReq message. * @function verify * @memberof GetWeAppMemberByUserReq @@ -583,22 +535,15 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetWeAppMemberByUserReq.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.useruin != null && message.hasOwnProperty("useruin")) - if (!$util.isInteger(message.useruin)) - return "useruin: integer expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isInteger(message.type)) - return "type: integer expected"; - if (message.status != null && message.hasOwnProperty("status")) - if (!$util.isInteger(message.status)) - return "status: integer expected"; - return null; - }; - - /** + GetWeAppMemberByUserReq.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.useruin != null && message.hasOwnProperty('useruin')) if (!$util.isInteger(message.useruin)) return 'useruin: integer expected' + if (message.type != null && message.hasOwnProperty('type')) if (!$util.isInteger(message.type)) return 'type: integer expected' + if (message.status != null && message.hasOwnProperty('status')) if (!$util.isInteger(message.status)) return 'status: integer expected' + return null + } + + /** * Creates a GetWeAppMemberByUserReq message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof GetWeAppMemberByUserReq @@ -606,20 +551,16 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {Object.} object Plain object * @returns {GetWeAppMemberByUserReq} GetWeAppMemberByUserReq */ - GetWeAppMemberByUserReq.fromObject = function fromObject(object) { - if (object instanceof $root.GetWeAppMemberByUserReq) - return object; - var message = new $root.GetWeAppMemberByUserReq(); - if (object.useruin != null) - message.useruin = object.useruin >>> 0; - if (object.type != null) - message.type = object.type >>> 0; - if (object.status != null) - message.status = object.status >>> 0; - return message; - }; - - /** + GetWeAppMemberByUserReq.fromObject = function fromObject(object) { + if (object instanceof $root.GetWeAppMemberByUserReq) return object + var message = new $root.GetWeAppMemberByUserReq() + if (object.useruin != null) message.useruin = object.useruin >>> 0 + if (object.type != null) message.type = object.type >>> 0 + if (object.status != null) message.status = object.status >>> 0 + return message + } + + /** * Creates a plain object from a GetWeAppMemberByUserReq message. Also converts values to other types if specified. * @function toObject * @memberof GetWeAppMemberByUserReq @@ -628,41 +569,36 @@ $root.GetWeAppMemberByUserReq = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetWeAppMemberByUserReq.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.useruin = 0; - object.type = 0; - object.status = 0; - } - if (message.useruin != null && message.hasOwnProperty("useruin")) - object.useruin = message.useruin; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.status != null && message.hasOwnProperty("status")) - object.status = message.status; - return object; - }; - - /** + GetWeAppMemberByUserReq.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.useruin = 0 + object.type = 0 + object.status = 0 + } + if (message.useruin != null && message.hasOwnProperty('useruin')) object.useruin = message.useruin + if (message.type != null && message.hasOwnProperty('type')) object.type = message.type + if (message.status != null && message.hasOwnProperty('status')) object.status = message.status + return object + } + + /** * Converts this GetWeAppMemberByUserReq to JSON. * @function toJSON * @memberof GetWeAppMemberByUserReq * @instance * @returns {Object.} JSON object */ - GetWeAppMemberByUserReq.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GetWeAppMemberByUserReq; -})(); + GetWeAppMemberByUserReq.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.WeAppMemberInfo = (function() { + return GetWeAppMemberByUserReq +}()) - /** +$root.WeAppMemberInfo = (function () { + /** * Properties of a WeAppMemberInfo. * @exports IWeAppMemberInfo * @interface IWeAppMemberInfo @@ -675,7 +611,7 @@ $root.WeAppMemberInfo = (function() { * @property {string|null} [ticket] WeAppMemberInfo ticket */ - /** + /** * Constructs a new WeAppMemberInfo. * @exports WeAppMemberInfo * @classdesc Represents a WeAppMemberInfo. @@ -683,70 +619,67 @@ $root.WeAppMemberInfo = (function() { * @constructor * @param {IWeAppMemberInfo=} [properties] Properties to set */ - function WeAppMemberInfo(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function WeAppMemberInfo(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * WeAppMemberInfo type. * @member {number} type * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.type = 0; + WeAppMemberInfo.prototype.type = 0 - /** + /** * WeAppMemberInfo weappuin. * @member {number} weappuin * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.weappuin = 0; + WeAppMemberInfo.prototype.weappuin = 0 - /** + /** * WeAppMemberInfo useruin. * @member {number} useruin * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.useruin = 0; + WeAppMemberInfo.prototype.useruin = 0 - /** + /** * WeAppMemberInfo status. * @member {number} status * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.status = 0; + WeAppMemberInfo.prototype.status = 0 - /** + /** * WeAppMemberInfo createtime. * @member {number} createtime * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.createtime = 0; + WeAppMemberInfo.prototype.createtime = 0 - /** + /** * WeAppMemberInfo updatetime. * @member {number} updatetime * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.updatetime = 0; + WeAppMemberInfo.prototype.updatetime = 0 - /** + /** * WeAppMemberInfo ticket. * @member {string} ticket * @memberof WeAppMemberInfo * @instance */ - WeAppMemberInfo.prototype.ticket = ""; + WeAppMemberInfo.prototype.ticket = '' - /** + /** * Creates a new WeAppMemberInfo instance using the specified properties. * @function create * @memberof WeAppMemberInfo @@ -754,11 +687,11 @@ $root.WeAppMemberInfo = (function() { * @param {IWeAppMemberInfo=} [properties] Properties to set * @returns {WeAppMemberInfo} WeAppMemberInfo instance */ - WeAppMemberInfo.create = function create(properties) { - return new WeAppMemberInfo(properties); - }; + WeAppMemberInfo.create = function create(properties) { + return new WeAppMemberInfo(properties) + } - /** + /** * Encodes the specified WeAppMemberInfo message. Does not implicitly {@link WeAppMemberInfo.verify|verify} messages. * @function encode * @memberof WeAppMemberInfo @@ -767,27 +700,19 @@ $root.WeAppMemberInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WeAppMemberInfo.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.type != null && message.hasOwnProperty("type")) - writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.type); - if (message.weappuin != null && message.hasOwnProperty("weappuin")) - writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.weappuin); - if (message.useruin != null && message.hasOwnProperty("useruin")) - writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.useruin); - if (message.status != null && message.hasOwnProperty("status")) - writer.uint32(/* id 4, wireType 0 =*/32).uint32(message.status); - if (message.createtime != null && message.hasOwnProperty("createtime")) - writer.uint32(/* id 5, wireType 0 =*/40).uint32(message.createtime); - if (message.updatetime != null && message.hasOwnProperty("updatetime")) - writer.uint32(/* id 6, wireType 0 =*/48).uint32(message.updatetime); - if (message.ticket != null && message.hasOwnProperty("ticket")) - writer.uint32(/* id 7, wireType 2 =*/58).string(message.ticket); - return writer; - }; - - /** + WeAppMemberInfo.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.type != null && message.hasOwnProperty('type')) writer.uint32(/* id 1, wireType 0 = */8).uint32(message.type) + if (message.weappuin != null && message.hasOwnProperty('weappuin')) writer.uint32(/* id 2, wireType 0 = */16).uint32(message.weappuin) + if (message.useruin != null && message.hasOwnProperty('useruin')) writer.uint32(/* id 3, wireType 0 = */24).uint32(message.useruin) + if (message.status != null && message.hasOwnProperty('status')) writer.uint32(/* id 4, wireType 0 = */32).uint32(message.status) + if (message.createtime != null && message.hasOwnProperty('createtime')) writer.uint32(/* id 5, wireType 0 = */40).uint32(message.createtime) + if (message.updatetime != null && message.hasOwnProperty('updatetime')) writer.uint32(/* id 6, wireType 0 = */48).uint32(message.updatetime) + if (message.ticket != null && message.hasOwnProperty('ticket')) writer.uint32(/* id 7, wireType 2 = */58).string(message.ticket) + return writer + } + + /** * Encodes the specified WeAppMemberInfo message, length delimited. Does not implicitly {@link WeAppMemberInfo.verify|verify} messages. * @function encodeDelimited * @memberof WeAppMemberInfo @@ -796,11 +721,11 @@ $root.WeAppMemberInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WeAppMemberInfo.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + WeAppMemberInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a WeAppMemberInfo message from the specified reader or buffer. * @function decode * @memberof WeAppMemberInfo @@ -811,43 +736,43 @@ $root.WeAppMemberInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WeAppMemberInfo.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.WeAppMemberInfo(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - message.type = reader.uint32(); - break; - case 2: - message.weappuin = reader.uint32(); - break; - case 3: - message.useruin = reader.uint32(); - break; - case 4: - message.status = reader.uint32(); - break; - case 5: - message.createtime = reader.uint32(); - break; - case 6: - message.updatetime = reader.uint32(); - break; - case 7: - message.ticket = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** + WeAppMemberInfo.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.WeAppMemberInfo() + while (reader.pos < end) { + var tag = reader.uint32() + switch (tag >>> 3) { + case 1: + message.type = reader.uint32() + break + case 2: + message.weappuin = reader.uint32() + break + case 3: + message.useruin = reader.uint32() + break + case 4: + message.status = reader.uint32() + break + case 5: + message.createtime = reader.uint32() + break + case 6: + message.updatetime = reader.uint32() + break + case 7: + message.ticket = reader.string() + break + default: + reader.skipType(tag & 7) + break + } + } + return message + } + + /** * Decodes a WeAppMemberInfo message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof WeAppMemberInfo @@ -857,13 +782,12 @@ $root.WeAppMemberInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WeAppMemberInfo.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + WeAppMemberInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a WeAppMemberInfo message. * @function verify * @memberof WeAppMemberInfo @@ -871,34 +795,19 @@ $root.WeAppMemberInfo = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - WeAppMemberInfo.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isInteger(message.type)) - return "type: integer expected"; - if (message.weappuin != null && message.hasOwnProperty("weappuin")) - if (!$util.isInteger(message.weappuin)) - return "weappuin: integer expected"; - if (message.useruin != null && message.hasOwnProperty("useruin")) - if (!$util.isInteger(message.useruin)) - return "useruin: integer expected"; - if (message.status != null && message.hasOwnProperty("status")) - if (!$util.isInteger(message.status)) - return "status: integer expected"; - if (message.createtime != null && message.hasOwnProperty("createtime")) - if (!$util.isInteger(message.createtime)) - return "createtime: integer expected"; - if (message.updatetime != null && message.hasOwnProperty("updatetime")) - if (!$util.isInteger(message.updatetime)) - return "updatetime: integer expected"; - if (message.ticket != null && message.hasOwnProperty("ticket")) - if (!$util.isString(message.ticket)) - return "ticket: string expected"; - return null; - }; - - /** + WeAppMemberInfo.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.type != null && message.hasOwnProperty('type')) if (!$util.isInteger(message.type)) return 'type: integer expected' + if (message.weappuin != null && message.hasOwnProperty('weappuin')) if (!$util.isInteger(message.weappuin)) return 'weappuin: integer expected' + if (message.useruin != null && message.hasOwnProperty('useruin')) if (!$util.isInteger(message.useruin)) return 'useruin: integer expected' + if (message.status != null && message.hasOwnProperty('status')) if (!$util.isInteger(message.status)) return 'status: integer expected' + if (message.createtime != null && message.hasOwnProperty('createtime')) if (!$util.isInteger(message.createtime)) return 'createtime: integer expected' + if (message.updatetime != null && message.hasOwnProperty('updatetime')) if (!$util.isInteger(message.updatetime)) return 'updatetime: integer expected' + if (message.ticket != null && message.hasOwnProperty('ticket')) if (!$util.isString(message.ticket)) return 'ticket: string expected' + return null + } + + /** * Creates a WeAppMemberInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof WeAppMemberInfo @@ -906,28 +815,20 @@ $root.WeAppMemberInfo = (function() { * @param {Object.} object Plain object * @returns {WeAppMemberInfo} WeAppMemberInfo */ - WeAppMemberInfo.fromObject = function fromObject(object) { - if (object instanceof $root.WeAppMemberInfo) - return object; - var message = new $root.WeAppMemberInfo(); - if (object.type != null) - message.type = object.type >>> 0; - if (object.weappuin != null) - message.weappuin = object.weappuin >>> 0; - if (object.useruin != null) - message.useruin = object.useruin >>> 0; - if (object.status != null) - message.status = object.status >>> 0; - if (object.createtime != null) - message.createtime = object.createtime >>> 0; - if (object.updatetime != null) - message.updatetime = object.updatetime >>> 0; - if (object.ticket != null) - message.ticket = String(object.ticket); - return message; - }; - - /** + WeAppMemberInfo.fromObject = function fromObject(object) { + if (object instanceof $root.WeAppMemberInfo) return object + var message = new $root.WeAppMemberInfo() + if (object.type != null) message.type = object.type >>> 0 + if (object.weappuin != null) message.weappuin = object.weappuin >>> 0 + if (object.useruin != null) message.useruin = object.useruin >>> 0 + if (object.status != null) message.status = object.status >>> 0 + if (object.createtime != null) message.createtime = object.createtime >>> 0 + if (object.updatetime != null) message.updatetime = object.updatetime >>> 0 + if (object.ticket != null) message.ticket = String(object.ticket) + return message + } + + /** * Creates a plain object from a WeAppMemberInfo message. Also converts values to other types if specified. * @function toObject * @memberof WeAppMemberInfo @@ -936,60 +837,51 @@ $root.WeAppMemberInfo = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WeAppMemberInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.type = 0; - object.weappuin = 0; - object.useruin = 0; - object.status = 0; - object.createtime = 0; - object.updatetime = 0; - object.ticket = ""; - } - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.weappuin != null && message.hasOwnProperty("weappuin")) - object.weappuin = message.weappuin; - if (message.useruin != null && message.hasOwnProperty("useruin")) - object.useruin = message.useruin; - if (message.status != null && message.hasOwnProperty("status")) - object.status = message.status; - if (message.createtime != null && message.hasOwnProperty("createtime")) - object.createtime = message.createtime; - if (message.updatetime != null && message.hasOwnProperty("updatetime")) - object.updatetime = message.updatetime; - if (message.ticket != null && message.hasOwnProperty("ticket")) - object.ticket = message.ticket; - return object; - }; - - /** + WeAppMemberInfo.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.type = 0 + object.weappuin = 0 + object.useruin = 0 + object.status = 0 + object.createtime = 0 + object.updatetime = 0 + object.ticket = '' + } + if (message.type != null && message.hasOwnProperty('type')) object.type = message.type + if (message.weappuin != null && message.hasOwnProperty('weappuin')) object.weappuin = message.weappuin + if (message.useruin != null && message.hasOwnProperty('useruin')) object.useruin = message.useruin + if (message.status != null && message.hasOwnProperty('status')) object.status = message.status + if (message.createtime != null && message.hasOwnProperty('createtime')) object.createtime = message.createtime + if (message.updatetime != null && message.hasOwnProperty('updatetime')) object.updatetime = message.updatetime + if (message.ticket != null && message.hasOwnProperty('ticket')) object.ticket = message.ticket + return object + } + + /** * Converts this WeAppMemberInfo to JSON. * @function toJSON * @memberof WeAppMemberInfo * @instance * @returns {Object.} JSON object */ - WeAppMemberInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return WeAppMemberInfo; -})(); + WeAppMemberInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.WeAppMemberInfoList = (function() { + return WeAppMemberInfo +}()) - /** +$root.WeAppMemberInfoList = (function () { + /** * Properties of a WeAppMemberInfoList. * @exports IWeAppMemberInfoList * @interface IWeAppMemberInfoList * @property {Array.|null} [infos] WeAppMemberInfoList infos */ - /** + /** * Constructs a new WeAppMemberInfoList. * @exports WeAppMemberInfoList * @classdesc Represents a WeAppMemberInfoList. @@ -997,23 +889,20 @@ $root.WeAppMemberInfoList = (function() { * @constructor * @param {IWeAppMemberInfoList=} [properties] Properties to set */ - function WeAppMemberInfoList(properties) { - this.infos = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function WeAppMemberInfoList(properties) { + this.infos = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * WeAppMemberInfoList infos. * @member {Array.} infos * @memberof WeAppMemberInfoList * @instance */ - WeAppMemberInfoList.prototype.infos = $util.emptyArray; + WeAppMemberInfoList.prototype.infos = $util.emptyArray - /** + /** * Creates a new WeAppMemberInfoList instance using the specified properties. * @function create * @memberof WeAppMemberInfoList @@ -1021,11 +910,11 @@ $root.WeAppMemberInfoList = (function() { * @param {IWeAppMemberInfoList=} [properties] Properties to set * @returns {WeAppMemberInfoList} WeAppMemberInfoList instance */ - WeAppMemberInfoList.create = function create(properties) { - return new WeAppMemberInfoList(properties); - }; + WeAppMemberInfoList.create = function create(properties) { + return new WeAppMemberInfoList(properties) + } - /** + /** * Encodes the specified WeAppMemberInfoList message. Does not implicitly {@link WeAppMemberInfoList.verify|verify} messages. * @function encode * @memberof WeAppMemberInfoList @@ -1034,16 +923,13 @@ $root.WeAppMemberInfoList = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WeAppMemberInfoList.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.infos != null && message.infos.length) - for (var i = 0; i < message.infos.length; ++i) - $root.WeAppMemberInfo.encode(message.infos[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; + WeAppMemberInfoList.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.infos != null && message.infos.length) for (var i = 0; i < message.infos.length; ++i) $root.WeAppMemberInfo.encode(message.infos[i], writer.uint32(/* id 1, wireType 2 = */10).fork()).ldelim() + return writer + } - /** + /** * Encodes the specified WeAppMemberInfoList message, length delimited. Does not implicitly {@link WeAppMemberInfoList.verify|verify} messages. * @function encodeDelimited * @memberof WeAppMemberInfoList @@ -1052,11 +938,11 @@ $root.WeAppMemberInfoList = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WeAppMemberInfoList.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + WeAppMemberInfoList.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a WeAppMemberInfoList message from the specified reader or buffer. * @function decode * @memberof WeAppMemberInfoList @@ -1067,27 +953,26 @@ $root.WeAppMemberInfoList = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WeAppMemberInfoList.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.WeAppMemberInfoList(); - while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (!(message.infos && message.infos.length)) - message.infos = []; - message.infos.push($root.WeAppMemberInfo.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - - /** + WeAppMemberInfoList.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.WeAppMemberInfoList() + while (reader.pos < end) { + var tag = reader.uint32() + switch (tag >>> 3) { + case 1: + if (!(message.infos && message.infos.length)) message.infos = [] + message.infos.push($root.WeAppMemberInfo.decode(reader, reader.uint32())) + break + default: + reader.skipType(tag & 7) + break + } + } + return message + } + + /** * Decodes a WeAppMemberInfoList message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof WeAppMemberInfoList @@ -1097,13 +982,12 @@ $root.WeAppMemberInfoList = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WeAppMemberInfoList.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + WeAppMemberInfoList.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a WeAppMemberInfoList message. * @function verify * @memberof WeAppMemberInfoList @@ -1111,22 +995,19 @@ $root.WeAppMemberInfoList = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - WeAppMemberInfoList.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.infos != null && message.hasOwnProperty("infos")) { - if (!Array.isArray(message.infos)) - return "infos: array expected"; - for (var i = 0; i < message.infos.length; ++i) { - var error = $root.WeAppMemberInfo.verify(message.infos[i]); - if (error) - return "infos." + error; - } - } - return null; - }; - - /** + WeAppMemberInfoList.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.infos != null && message.hasOwnProperty('infos')) { + if (!Array.isArray(message.infos)) return 'infos: array expected' + for (var i = 0; i < message.infos.length; ++i) { + var error = $root.WeAppMemberInfo.verify(message.infos[i]) + if (error) return 'infos.' + error + } + } + return null + } + + /** * Creates a WeAppMemberInfoList message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof WeAppMemberInfoList @@ -1134,24 +1015,21 @@ $root.WeAppMemberInfoList = (function() { * @param {Object.} object Plain object * @returns {WeAppMemberInfoList} WeAppMemberInfoList */ - WeAppMemberInfoList.fromObject = function fromObject(object) { - if (object instanceof $root.WeAppMemberInfoList) - return object; - var message = new $root.WeAppMemberInfoList(); - if (object.infos) { - if (!Array.isArray(object.infos)) - throw TypeError(".WeAppMemberInfoList.infos: array expected"); - message.infos = []; - for (var i = 0; i < object.infos.length; ++i) { - if (typeof object.infos[i] !== "object") - throw TypeError(".WeAppMemberInfoList.infos: object expected"); - message.infos[i] = $root.WeAppMemberInfo.fromObject(object.infos[i]); - } - } - return message; - }; - - /** + WeAppMemberInfoList.fromObject = function fromObject(object) { + if (object instanceof $root.WeAppMemberInfoList) return object + var message = new $root.WeAppMemberInfoList() + if (object.infos) { + if (!Array.isArray(object.infos)) throw TypeError('.WeAppMemberInfoList.infos: array expected') + message.infos = [] + for (var i = 0; i < object.infos.length; ++i) { + if (typeof object.infos[i] !== 'object') throw TypeError('.WeAppMemberInfoList.infos: object expected') + message.infos[i] = $root.WeAppMemberInfo.fromObject(object.infos[i]) + } + } + return message + } + + /** * Creates a plain object from a WeAppMemberInfoList message. Also converts values to other types if specified. * @function toObject * @memberof WeAppMemberInfoList @@ -1160,32 +1038,29 @@ $root.WeAppMemberInfoList = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WeAppMemberInfoList.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.infos = []; - if (message.infos && message.infos.length) { - object.infos = []; - for (var j = 0; j < message.infos.length; ++j) - object.infos[j] = $root.WeAppMemberInfo.toObject(message.infos[j], options); - } - return object; - }; - - /** + WeAppMemberInfoList.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.infos = [] + if (message.infos && message.infos.length) { + object.infos = [] + for (var j = 0; j < message.infos.length; ++j) object.infos[j] = $root.WeAppMemberInfo.toObject(message.infos[j], options) + } + return object + } + + /** * Converts this WeAppMemberInfoList to JSON. * @function toJSON * @memberof WeAppMemberInfoList * @instance * @returns {Object.} JSON object */ - WeAppMemberInfoList.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + WeAppMemberInfoList.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - return WeAppMemberInfoList; -})(); + return WeAppMemberInfoList +}()) -module.exports = $root; +module.exports = $root diff --git a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/proto-utils.js b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/proto-utils.js index 3ffcfc26..9f4fffb4 100644 --- a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/proto-utils.js +++ b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/proto-utils.js @@ -6,9 +6,9 @@ function generate(options) { throw new Error('options must be provided') } - const { serviceName, funcName, data } = 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') } diff --git a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit-utils.js b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit-utils.js index 19eb07da..af32e299 100644 --- a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit-utils.js +++ b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit-utils.js @@ -1,4 +1,3 @@ - const config = require('./svrkit.config.js') const proto = require('./svrkit-utils.static.js') const protoJSON = require('./svrkit-utils.static.json') @@ -8,9 +7,9 @@ function generate(options) { throw new Error('options must be provided') } - const { serviceName, funcName, data } = 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') } @@ -42,7 +41,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') } @@ -68,7 +67,7 @@ function generateV2(options) { throw new Error('options must be provided') } - const { apiName, data } = options + const {apiName, data} = options const apiConfig = config.find(c => c.apiName === apiName) @@ -95,7 +94,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') } @@ -116,4 +115,3 @@ module.exports = { generate, generateV2, } - diff --git a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit.config.js b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit.config.js index c509bd24..89ee02d4 100644 --- a/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit.config.js +++ b/cloudfunctions/ARDemo/cloud-functions-tools/test/svrkit-utils/example/svrkit.config.js @@ -29,4 +29,4 @@ module.exports = [ }, } }, -] \ No newline at end of file +] 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..db0cd453 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) { @@ -25,7 +25,7 @@ function generate(options) { throw new Error('options must be provided') } - const { serviceName, funcName, data } = options + const {serviceName, funcName, data} = options const serviceConfig = config.find(c => c.serviceName === serviceName) if (!serviceConfig) { @@ -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) { @@ -85,7 +85,7 @@ function generateV2(options) { throw new Error('options must be provided') } - const { apiName, data } = options + const {apiName, data} = options const apiConfig = config.find(c => c.apiName === apiName) @@ -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/cloudfunctions/ARDemo/wx-server-sdk-wxg-service/index.js b/cloudfunctions/ARDemo/wx-server-sdk-wxg-service/index.js index 0f7b43da..36111071 100644 --- a/cloudfunctions/ARDemo/wx-server-sdk-wxg-service/index.js +++ b/cloudfunctions/ARDemo/wx-server-sdk-wxg-service/index.js @@ -1,835 +1,776 @@ module.exports = -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // 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 }); -/******/ } -/******/ }; -/******/ -/******/ // 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, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = "./src/api/inner/index.ts"); -/******/ }) -/************************************************************************/ -/******/ ({ - -/***/ "./src/api/inner/api/api.ts": -/*!**********************************!*\ +/** *** */ (function (modules) { // webpackBootstrap + /** *** */ // The module cache + /** *** */ const installedModules = {} + /** *** */ + /** *** */ // The require function + /** *** */ function __webpack_require__(moduleId) { + /** *** */ + /** *** */ // Check if module is in cache + /** *** */ if (installedModules[moduleId]) { + /** *** */ return installedModules[moduleId].exports + /** *** */ } + /** *** */ // Create a new module (and put it into the cache) + /** *** */ const module = installedModules[moduleId] = { + /** *** */ i: moduleId, + /** *** */ l: false, + /** *** */ exports: {} + /** *** */} + /** *** */ + /** *** */ // Execute the module function + /** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__) + /** *** */ + /** *** */ // Flag the module as loaded + /** *** */ module.l = true + /** *** */ + /** *** */ // Return the exports of the module + /** *** */ return module.exports + /** *** */ } + /** *** */ + /** *** */ + /** *** */ // expose the modules object (__webpack_modules__) + /** *** */ __webpack_require__.m = modules + /** *** */ + /** *** */ // expose the module cache + /** *** */ __webpack_require__.c = installedModules + /** *** */ + /** *** */ // 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}) + /** *** */ } + /** *** */ } + /** *** */ + /** *** */ // 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, '__esModule', {value: true}) + /** *** */ } + /** *** */ + /** *** */ // create a fake namespace object + /** *** */ // mode & 1: value is a module id, require it + /** *** */ // mode & 2: merge all properties of value into the ns + /** *** */ // mode & 4: return value when already ns object + /** *** */ // mode & 8|1: behave like require + /** *** */ __webpack_require__.t = function (value, mode) { + /** *** */ if (mode & 1) value = __webpack_require__(value) + /** *** */ if (mode & 8) return value + /** *** */ 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}) + /** *** */ 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 + /** *** */ } + /** *** */ + /** *** */ // getDefaultExport function for compatibility with non-harmony modules + /** *** */ __webpack_require__.n = function (module) { + /** *** */ const getter = module && module.__esModule + /** *** */ ? function getDefault() { return module.default } + /** *** */ : function getModuleExports() { return module } + /** *** */ __webpack_require__.d(getter, 'a', getter) + /** *** */ return getter + /** *** */ } + /** *** */ + /** *** */ // Object.prototype.hasOwnProperty.call + /** *** */ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property) } + /** *** */ + /** *** */ // __webpack_public_path__ + /** *** */ __webpack_require__.p = '' + /** *** */ + /** *** */ + /** *** */ // Load entry module and return exports + /** *** */ return __webpack_require__(__webpack_require__.s = './src/api/inner/index.ts') + /** *** */ }({ + + /***/ './src/api/inner/api/api.ts': + /*! **********************************!*\ !*** ./src/api/inner/api/api.ts ***! - \**********************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAPIs = void 0; -const callWXInnerAPI_1 = __webpack_require__(/*! ./callWXInnerAPI */ "./src/api/inner/api/callWXInnerAPI.ts"); -const callWXSvrkit_1 = __webpack_require__(/*! ./callWXSvrkit */ "./src/api/inner/api/callWXSvrkit.ts"); -const callSvrkit_1 = __webpack_require__(/*! ./callSvrkit */ "./src/api/inner/api/callSvrkit.ts"); -const callTencentInnerAPI_1 = __webpack_require__(/*! ./callTencentInnerAPI */ "./src/api/inner/api/callTencentInnerAPI.ts"); -function getAPIs(cloud) { - return { - callWXInnerAPI: callWXInnerAPI_1.default(cloud), - callWXSvrkit: callWXSvrkit_1.default(cloud), - callSvrkit: callSvrkit_1.default(cloud), - callTencentInnerAPI: callTencentInnerAPI_1.default(cloud), - }; -} -exports.getAPIs = getAPIs; - - -/***/ }), + \********************************* */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.getAPIs = void 0 + const callWXInnerAPI_1 = __webpack_require__(/*! ./callWXInnerAPI */ './src/api/inner/api/callWXInnerAPI.ts') + const callWXSvrkit_1 = __webpack_require__(/*! ./callWXSvrkit */ './src/api/inner/api/callWXSvrkit.ts') + const callSvrkit_1 = __webpack_require__(/*! ./callSvrkit */ './src/api/inner/api/callSvrkit.ts') + const callTencentInnerAPI_1 = __webpack_require__(/*! ./callTencentInnerAPI */ './src/api/inner/api/callTencentInnerAPI.ts') + function getAPIs(cloud) { + return { + callWXInnerAPI: callWXInnerAPI_1.default(cloud), + callWXSvrkit: callWXSvrkit_1.default(cloud), + callSvrkit: callSvrkit_1.default(cloud), + callTencentInnerAPI: callTencentInnerAPI_1.default(cloud), + } + } + exports.getAPIs = getAPIs + /***/ }), -/***/ "./src/api/inner/api/callSvrkit.ts": -/*!*****************************************!*\ + /***/ './src/api/inner/api/callSvrkit.ts': + /*! *****************************************!*\ !*** ./src/api/inner/api/callSvrkit.ts ***! - \*****************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -// @deprecated kainniu api -Object.defineProperty(exports, "__esModule", { value: true }); -const error_1 = __webpack_require__(/*! utils/error */ "./src/utils/error.ts"); -const msg_1 = __webpack_require__(/*! utils/msg */ "./src/utils/msg.ts"); -const openapi_1 = __webpack_require__(/*! ../../../protobuf/openapi */ "./src/protobuf/openapi.js"); -const error_config_1 = __webpack_require__(/*! config/error.config */ "./src/config/error.config.ts"); -const API_NAME = 'callSvrkit'; -function getCallSvrkit(cloud) { - return function callSvrkit(options) { - return new Promise(async (resolve, reject) => { + \**************************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + // @deprecated kainniu api + Object.defineProperty(exports, '__esModule', {value: true}) + const error_1 = __webpack_require__(/*! utils/error */ './src/utils/error.ts') + const msg_1 = __webpack_require__(/*! utils/msg */ './src/utils/msg.ts') + const openapi_1 = __webpack_require__(/*! ../../../protobuf/openapi */ './src/protobuf/openapi.js') + const error_config_1 = __webpack_require__(/*! config/error.config */ './src/config/error.config.ts') + const API_NAME = 'callSvrkit' + function getCallSvrkit(cloud) { + return function callSvrkit(options) { + return new Promise(async (resolve, reject) => { if (!options) { - return reject(error_1.returnAsFinalCloudSDKError({ - errMsg: 'Params for callSvrkit must be an object instead of ' + typeof options, - }, API_NAME)); + return reject(error_1.returnAsFinalCloudSDKError({ + errMsg: 'Params for callSvrkit must be an object instead of ' + typeof options, + }, API_NAME)) } try { - if (!options.pbInstance) { - throw new Error('pbInstance must be provided'); - } - } - catch (e) { - return reject(error_1.returnAsFinalCloudSDKError(e, API_NAME)); + if (!options.pbInstance) { + throw new Error('pbInstance must be provided') + } + } catch (e) { + return reject(error_1.returnAsFinalCloudSDKError(e, API_NAME)) } try { - const svrkitData = { - apiName: options.pbInstance.data.apiName, - reqData: options.pbInstance.data.reqBodyBuffer, - }; - const pbMessage = openapi_1.CommApiData.encode({ - apiType: openapi_1.CommApiData.ApiType.SVRKIT_API, - svrkitData, - }).finish(); - const wxResp = await cloud.provider.api.callWXOpenAPI({ - api: API_NAME, - data: Buffer.from(pbMessage), - }, { - instance: cloud.instance, - }); - let svrkitResponse; - let svrkitResponseBuffer; - let svrkitErrCode = 0; - if (wxResp) { - if (wxResp.errorCode) { - // wx system error, for example: no permission - throw new error_1.CloudSDKError({ - errCode: error_config_1.ERR_CODE[error_config_1.ERR_CODE[wxResp.errorCode]] || wxResp.errorCode, - errMsg: `${error_config_1.ERR_CODE[error_config_1.ERR_CODE.WX_SYSTEM_ERROR]}: error code: ${wxResp.errorCode}` - }); + const svrkitData = { + apiName: options.pbInstance.data.apiName, + reqData: options.pbInstance.data.reqBodyBuffer, + } + const pbMessage = openapi_1.CommApiData.encode({ + apiType: openapi_1.CommApiData.ApiType.SVRKIT_API, + svrkitData, + }).finish() + const wxResp = await cloud.provider.api.callWXOpenAPI({ + api: API_NAME, + data: Buffer.from(pbMessage), + }, { + instance: cloud.instance, + }) + let svrkitResponse + let svrkitResponseBuffer + let svrkitErrCode = 0 + if (wxResp) { + if (wxResp.errorCode) { + // wx system error, for example: no permission + throw new error_1.CloudSDKError({ + errCode: error_config_1.ERR_CODE[error_config_1.ERR_CODE[wxResp.errorCode]] || wxResp.errorCode, + errMsg: `${error_config_1.ERR_CODE[error_config_1.ERR_CODE.WX_SYSTEM_ERROR]}: error code: ${wxResp.errorCode}` + }) + } else { + svrkitErrCode = wxResp.svrkitErrorCode + if (wxResp.svrkitErrorCode !== 0) { + throw { + errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, + errMsg: `internal svrkit error, code ${wxResp.svrkitErrorCode}`, } - else { - svrkitErrCode = wxResp.svrkitErrorCode; - if (wxResp.svrkitErrorCode !== 0) { - throw { - errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, - errMsg: `internal svrkit error, code ${wxResp.svrkitErrorCode}`, - }; - } - if (!wxResp.respData) { - throw { - errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, - errMsg: `internal svrkit error, empty respData`, - }; - } - svrkitResponseBuffer = wxResp.respData; - const pbRespMsg = options.pbInstance.resProto.decode(wxResp.respData); - if (options.convertResp && options.convertResp.bytes === false) { - if (!options.pbInstance.resProto) { - throw new Error('please ensure \'pbInstance\' is generated using @tencent/cloud-functions-tools whose version is greater or equal to 1.3.0'); - } - svrkitResponse = options.pbInstance.resProto.toObject(pbRespMsg, { - long: String - }); - } - else { - svrkitResponse = pbRespMsg.toJSON(); - } + } + if (!wxResp.respData) { + throw { + errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, + errMsg: 'internal svrkit error, empty respData', } + } + svrkitResponseBuffer = wxResp.respData + const pbRespMsg = options.pbInstance.resProto.decode(wxResp.respData) + if (options.convertResp && options.convertResp.bytes === false) { + if (!options.pbInstance.resProto) { + throw new Error('please ensure \'pbInstance\' is generated using @tencent/cloud-functions-tools whose version is greater or equal to 1.3.0') + } + svrkitResponse = options.pbInstance.resProto.toObject(pbRespMsg, { + long: String + }) + } else { + svrkitResponse = pbRespMsg.toJSON() + } } - resolve({ - svrkitErrCode, - svrkitResponse, - svrkitResponseBuffer, - errMsg: msg_1.apiSuccessMsg(API_NAME), - errCode: 0, - }); - } - catch (e) { - const error = error_1.returnAsFinalCloudSDKError(e, API_NAME); - return reject(error); + } + resolve({ + svrkitErrCode, + svrkitResponse, + svrkitResponseBuffer, + errMsg: msg_1.apiSuccessMsg(API_NAME), + errCode: 0, + }) + } catch (e) { + const error = error_1.returnAsFinalCloudSDKError(e, API_NAME) + return reject(error) } - }); - }; -} -exports.default = getCallSvrkit; - - -/***/ }), + }) + } + } + exports.default = getCallSvrkit + /***/ }), -/***/ "./src/api/inner/api/callTencentInnerAPI.ts": -/*!**************************************************!*\ + /***/ './src/api/inner/api/callTencentInnerAPI.ts': + /*! **************************************************!*\ !*** ./src/api/inner/api/callTencentInnerAPI.ts ***! - \**************************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __webpack_require__(/*! utils/assert */ "./src/utils/assert.ts"); -const error_1 = __webpack_require__(/*! utils/error */ "./src/utils/error.ts"); -const msg_1 = __webpack_require__(/*! utils/msg */ "./src/utils/msg.ts"); -const openapi_1 = __webpack_require__(/*! ../../../protobuf/openapi */ "./src/protobuf/openapi.js"); -const error_config_1 = __webpack_require__(/*! config/error.config */ "./src/config/error.config.ts"); -const utils_1 = __webpack_require__(/*! utils/utils */ "./src/utils/utils.ts"); -const getHTTPMethodNumber = (method) => { - switch (method.toLowerCase()) { - case 'get': { - return openapi_1.HTTP_METHODS.HTTP_GET; - } - case 'post': { - return openapi_1.HTTP_METHODS.HTTP_POST; - } - case 'put': { - return openapi_1.HTTP_METHODS.HTTP_PUT; - } - case 'patch': { - return openapi_1.HTTP_METHODS.HTTP_PATCH; + \************************************************* */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + const assert_1 = __webpack_require__(/*! utils/assert */ './src/utils/assert.ts') + const error_1 = __webpack_require__(/*! utils/error */ './src/utils/error.ts') + const msg_1 = __webpack_require__(/*! utils/msg */ './src/utils/msg.ts') + const openapi_1 = __webpack_require__(/*! ../../../protobuf/openapi */ './src/protobuf/openapi.js') + const error_config_1 = __webpack_require__(/*! config/error.config */ './src/config/error.config.ts') + const utils_1 = __webpack_require__(/*! utils/utils */ './src/utils/utils.ts') + const getHTTPMethodNumber = (method) => { + switch (method.toLowerCase()) { + case 'get': { + return openapi_1.HTTP_METHODS.HTTP_GET + } + case 'post': { + return openapi_1.HTTP_METHODS.HTTP_POST + } + case 'put': { + return openapi_1.HTTP_METHODS.HTTP_PUT + } + case 'patch': { + return openapi_1.HTTP_METHODS.HTTP_PATCH + } + case 'head': { + return openapi_1.HTTP_METHODS.HTTP_HEAD + } + case 'delete': { + return openapi_1.HTTP_METHODS.HTTP_DELETE + } + default: { + throw new Error(`unsupported HTTP method ${method}`) + } } - case 'head': { - return openapi_1.HTTP_METHODS.HTTP_HEAD; - } - case 'delete': { - return openapi_1.HTTP_METHODS.HTTP_DELETE; - } - default: { - throw new Error(`unsupported HTTP method ${method}`); - } - } -}; -const API_NAME = 'callTencentInnerAPI'; -function getCallTencentInnerAPI(cloud) { - return function callTencentInnerAPI(options) { - const apiName = 'callTencentInnerAPI'; - return new Promise(async (resolve, reject) => { + } + const API_NAME = 'callTencentInnerAPI' + function getCallTencentInnerAPI(cloud) { + return function callTencentInnerAPI(options) { + const apiName = 'callTencentInnerAPI' + return new Promise(async (resolve, reject) => { if (!options) { - return reject(error_1.returnAsFinalCloudSDKError({ - errMsg: 'Params for callTencentInnerAPI must be an object instead of ' + typeof options, - }, apiName)); + return reject(error_1.returnAsFinalCloudSDKError({ + errMsg: 'Params for callTencentInnerAPI must be an object instead of ' + typeof options, + }, apiName)) } try { + assert_1.assertType(options, { + modid: 'number', + cmdid: 'number', + path: 'string', + method: 'string', + }) + if (options.headers) { assert_1.assertType(options, { - modid: 'number', - cmdid: 'number', - path: 'string', - method: 'string', - }); - if (options.headers) { - assert_1.assertType(options, { - headers: 'object', - }); - } - } - catch (e) { - return reject(error_1.returnAsFinalCloudSDKError(e, apiName)); + headers: 'object', + }) + } + } catch (e) { + return reject(error_1.returnAsFinalCloudSDKError(e, apiName)) } try { - const innerData = { - modid: options.modid, - cmdid: options.cmdid, - url: options.path, - method: getHTTPMethodNumber(options.method), - useHttps: options.https, - headers: [], - }; - if (options.headers) { - for (const key in options.headers) { - innerData.headers.push(`${key.toLowerCase()}: ${options.headers[key]}`); + const innerData = { + modid: options.modid, + cmdid: options.cmdid, + url: options.path, + method: getHTTPMethodNumber(options.method), + useHttps: options.https, + headers: [], + } + if (options.headers) { + for (const key in options.headers) { + innerData.headers.push(`${key.toLowerCase()}: ${options.headers[key]}`) + } + } + if (options.body) { + // @ts-ignore + innerData.body = Buffer.from(options.body) + } + const pbMessage = openapi_1.CommApiData.encode({ + apiType: openapi_1.CommApiData.ApiType.INNER_API, + innerData, + }).finish() + const wxResp = await cloud.provider.api.callWXOpenAPI({ + api: API_NAME, + data: Buffer.from(pbMessage), + }, { + // this is the new protocol + instance: cloud.instance, + // @deprecated + // the following 2 lines are deprecated, for compatibility only + // to be deleted. + defaultConfig: utils_1.getServiceConfigFromDefaultConfig(cloud.config), + apiConfig: options.config, + // @ts-ignore + version: options.apiVersion || 'v2', + }) + let body + let contentType = '' + let statusCode + let rawHeaders = [] + let err + if (wxResp) { + if (options.autoParse) { + if (/application\/json/.test(wxResp.contentType)) { + // json response + try { + body = JSON.parse(wxResp.respData.toString()) + } catch (parseWXRespJSONError) { + // wx server says it's a json but instead it is not a valid json + throw new error_1.CloudSDKError({ + errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, + errMsg: msg_1.apiFailMsg(API_NAME, `response body is not a valid json: ${wxResp.respData.toString()}`) + }) } + } else if (/text\/plain/.test(wxResp.contentType)) { + // text response + body = wxResp.respData.toString() + } } - if (options.body) { - // @ts-ignore - innerData.body = Buffer.from(options.body); + if (!body) { + // buffer body + body = wxResp.respData } - const pbMessage = openapi_1.CommApiData.encode({ - apiType: openapi_1.CommApiData.ApiType.INNER_API, - innerData, - }).finish(); - const wxResp = await cloud.provider.api.callWXOpenAPI({ - api: API_NAME, - data: Buffer.from(pbMessage), - }, { - // this is the new protocol - instance: cloud.instance, - // @deprecated - // the following 2 lines are deprecated, for compatibility only - // to be deleted. - defaultConfig: utils_1.getServiceConfigFromDefaultConfig(cloud.config), - apiConfig: options.config, - // @ts-ignore - version: options.apiVersion || 'v2', - }); - let body; - let contentType = ''; - let statusCode; - let rawHeaders = []; - let err; - if (wxResp) { - if (options.autoParse) { - if (/application\/json/.test(wxResp.contentType)) { - // json response - try { - body = JSON.parse(wxResp.respData.toString()); - } - catch (parseWXRespJSONError) { - // wx server says it's a json but instead it is not a valid json - throw new error_1.CloudSDKError({ - errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, - errMsg: msg_1.apiFailMsg(API_NAME, `response body is not a valid json: ${wxResp.respData.toString()}`) - }); - } - } - else if (/text\/plain/.test(wxResp.contentType)) { - // text response - body = wxResp.respData.toString(); - } - } - if (!body) { - // buffer body - body = wxResp.respData; - } - if (wxResp.contentType) { - contentType = wxResp.contentType.trim(); - } - if (wxResp.httpCode) { - statusCode = wxResp.httpCode; - } - if (wxResp.headers) { - // @ts-ignore - rawHeaders = wxResp.headers; - } + if (wxResp.contentType) { + contentType = wxResp.contentType.trim() } - else { - throw { - errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, - errMsg: `internal server error, empty resp buffer`, - }; + if (wxResp.httpCode) { + statusCode = wxResp.httpCode } - if (err) { - reject(err); - return; + if (wxResp.headers) { + // @ts-ignore + rawHeaders = wxResp.headers } - resolve({ - body, - contentType, - statusCode, - rawHeaders, - errMsg: msg_1.apiSuccessMsg(API_NAME), - errCode: 0, - }); - } - catch (e) { - const error = error_1.returnAsFinalCloudSDKError(e, apiName); - return reject(error); + } else { + throw { + errCode: error_config_1.ERR_CODE.WX_SYSTEM_ERROR, + errMsg: 'internal server error, empty resp buffer', + } + } + if (err) { + reject(err) + return + } + resolve({ + body, + contentType, + statusCode, + rawHeaders, + errMsg: msg_1.apiSuccessMsg(API_NAME), + errCode: 0, + }) + } catch (e) { + const error = error_1.returnAsFinalCloudSDKError(e, apiName) + return reject(error) } - }); - }; -} -exports.default = getCallTencentInnerAPI; - - -/***/ }), + }) + } + } + exports.default = getCallTencentInnerAPI + /***/ }), -/***/ "./src/api/inner/api/callWXInnerAPI.ts": -/*!*********************************************!*\ + /***/ './src/api/inner/api/callWXInnerAPI.ts': + /*! *********************************************!*\ !*** ./src/api/inner/api/callWXInnerAPI.ts ***! - \*********************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __webpack_require__(/*! utils/assert */ "./src/utils/assert.ts"); -const error_1 = __webpack_require__(/*! utils/error */ "./src/utils/error.ts"); -const msg_1 = __webpack_require__(/*! utils/msg */ "./src/utils/msg.ts"); -function getCallWXInnerAPI(cloud) { - return function callWXInnerAPI(options) { - const apiName = 'callWXInnerAPI'; - return new Promise(async (resolve, reject) => { + \******************************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + const assert_1 = __webpack_require__(/*! utils/assert */ './src/utils/assert.ts') + const error_1 = __webpack_require__(/*! utils/error */ './src/utils/error.ts') + const msg_1 = __webpack_require__(/*! utils/msg */ './src/utils/msg.ts') + function getCallWXInnerAPI(cloud) { + return function callWXInnerAPI(options) { + const apiName = 'callWXInnerAPI' + return new Promise(async (resolve, reject) => { if (!options) { - return reject(error_1.returnAsFinalCloudSDKError({ - errMsg: 'Params for callWXInnerAPI must be an object instead of ' + typeof options, - }, apiName)); + return reject(error_1.returnAsFinalCloudSDKError({ + errMsg: 'Params for callWXInnerAPI must be an object instead of ' + typeof options, + }, apiName)) } try { - assert_1.assertType(options, { - cmdid: 'number' - }); - } - catch (e) { - return reject(error_1.returnAsFinalCloudSDKError(e, apiName)); + assert_1.assertType(options, { + cmdid: 'number' + }) + } catch (e) { + return reject(error_1.returnAsFinalCloudSDKError(e, apiName)) } try { - const result = await cloud.getAPIs().callOpenAPI({ - api: '/inner/wxtransfer', - data: { - cmdid: options.cmdid, - req_data: JSON.stringify(options.data || {}), - }, - config: options.config, - }); - let parsedResult = result.result; - try { - if (typeof parsedResult === 'string') { - parsedResult = JSON.parse(parsedResult); - } - } - catch (_) { - // no nothing + const result = await cloud.getAPIs().callOpenAPI({ + api: '/inner/wxtransfer', + data: { + cmdid: options.cmdid, + req_data: JSON.stringify(options.data || {}), + }, + config: options.config, + }) + let parsedResult = result.result + try { + if (typeof parsedResult === 'string') { + parsedResult = JSON.parse(parsedResult) } - return resolve({ - result: parsedResult, - errMsg: msg_1.apiSuccessMsg(apiName), - }); + } catch (_) { + // no nothing + } + return resolve({ + result: parsedResult, + errMsg: msg_1.apiSuccessMsg(apiName), + }) + } catch (e) { + const error = error_1.returnAsFinalCloudSDKError(e, apiName) + return reject(error) } - catch (e) { - const error = error_1.returnAsFinalCloudSDKError(e, apiName); - return reject(error); - } - }); - }; -} -exports.default = getCallWXInnerAPI; - - -/***/ }), + }) + } + } + exports.default = getCallWXInnerAPI + /***/ }), -/***/ "./src/api/inner/api/callWXSvrkit.ts": -/*!*******************************************!*\ + /***/ './src/api/inner/api/callWXSvrkit.ts': + /*! *******************************************!*\ !*** ./src/api/inner/api/callWXSvrkit.ts ***! - \*******************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const assert_1 = __webpack_require__(/*! utils/assert */ "./src/utils/assert.ts"); -const error_1 = __webpack_require__(/*! utils/error */ "./src/utils/error.ts"); -const msg_1 = __webpack_require__(/*! utils/msg */ "./src/utils/msg.ts"); -function getCallWXSvrkit(cloud) { - return function callWXSvrkit(options) { - const apiName = 'callWXSvrkit'; - return new Promise(async (resolve, reject) => { + \****************************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + const assert_1 = __webpack_require__(/*! utils/assert */ './src/utils/assert.ts') + const error_1 = __webpack_require__(/*! utils/error */ './src/utils/error.ts') + const msg_1 = __webpack_require__(/*! utils/msg */ './src/utils/msg.ts') + function getCallWXSvrkit(cloud) { + return function callWXSvrkit(options) { + const apiName = 'callWXSvrkit' + return new Promise(async (resolve, reject) => { if (!options) { - return reject(error_1.returnAsFinalCloudSDKError({ - errMsg: 'Params for callWXSvrkit must be an object instead of ' + typeof options, - }, apiName)); + return reject(error_1.returnAsFinalCloudSDKError({ + errMsg: 'Params for callWXSvrkit must be an object instead of ' + typeof options, + }, apiName)) } - const pbInstance = options.pbInstance; + const pbInstance = options.pbInstance if (pbInstance) { - options = Object.assign(Object.assign({}, options), pbInstance.data); - delete options.pbInstance; + options = {...options, ...pbInstance.data} + delete options.pbInstance } try { - assert_1.assertType(options, { - serviceName: 'string', - funcName: 'string', - magic: 'number', - cmdid: 'number', - }); - } - catch (e) { - return reject(error_1.returnAsFinalCloudSDKError(e, apiName)); + assert_1.assertType(options, { + serviceName: 'string', + funcName: 'string', + magic: 'number', + cmdid: 'number', + }) + } catch (e) { + return reject(error_1.returnAsFinalCloudSDKError(e, apiName)) } try { - const result = await cloud.getAPIs().callOpenAPI({ - api: '/inner/svrkitclientcall', - data: { - req_body_buffer: options.reqBodyBuffer.toString('base64'), - service_name: options.serviceName, - func_name: options.funcName, - magic: options.magic, - cmdid: options.cmdid, - headuin: options.headuin, - route_method: options.routeMethod, - idc_route_method: options.idcRouteMethod, - exist_resp: options.existResp, - }, - config: options.config, - timeout: options.timeout, - retryOptions: options.retryOptions, - }); - // @ts-ignore - let parsedResult = result.result; - if (parsedResult.baseresponse && parsedResult.baseresponse.errcode !== 0) { - parsedResult.ret = parsedResult.baseresponse.errcode; - } - if (parsedResult.ret === 0) { - parsedResult.respBodyBuffer = Buffer.from(parsedResult.resp_body_buffer, 'base64'); - delete parsedResult.resp_body_buffer; - if (pbInstance && options.existResp) { - const pbRespMsg = pbInstance.decode(parsedResult.respBodyBuffer); - if (options.convertResp && options.convertResp.bytes === false) { - if (!pbInstance.resProto) { - throw new Error('please ensure \'pbInstance\' is generated using @tencent/cloud-functions-tools whose version is greater or equal to 1.3.0'); - } - parsedResult.respBody = pbInstance.resProto.toObject(pbRespMsg, { - long: String - }); - } - else { - parsedResult.respBody = pbRespMsg.toJSON(); - } + const result = await cloud.getAPIs().callOpenAPI({ + api: '/inner/svrkitclientcall', + data: { + req_body_buffer: options.reqBodyBuffer.toString('base64'), + service_name: options.serviceName, + func_name: options.funcName, + magic: options.magic, + cmdid: options.cmdid, + headuin: options.headuin, + route_method: options.routeMethod, + idc_route_method: options.idcRouteMethod, + exist_resp: options.existResp, + }, + config: options.config, + timeout: options.timeout, + retryOptions: options.retryOptions, + }) + // @ts-ignore + const parsedResult = result.result + if (parsedResult.baseresponse && parsedResult.baseresponse.errcode !== 0) { + parsedResult.ret = parsedResult.baseresponse.errcode + } + if (parsedResult.ret === 0) { + parsedResult.respBodyBuffer = Buffer.from(parsedResult.resp_body_buffer, 'base64') + delete parsedResult.resp_body_buffer + if (pbInstance && options.existResp) { + const pbRespMsg = pbInstance.decode(parsedResult.respBodyBuffer) + if (options.convertResp && options.convertResp.bytes === false) { + if (!pbInstance.resProto) { + throw new Error('please ensure \'pbInstance\' is generated using @tencent/cloud-functions-tools whose version is greater or equal to 1.3.0') } + parsedResult.respBody = pbInstance.resProto.toObject(pbRespMsg, { + long: String + }) + } else { + parsedResult.respBody = pbRespMsg.toJSON() + } } - const returnValue = { - ret: parsedResult.ret, - result: parsedResult.result, - respBodyBuffer: parsedResult.respBodyBuffer, - respBody: parsedResult.respBody, - errMsg: msg_1.apiSuccessMsg(apiName), - }; - resolve(returnValue); - } - catch (e) { - const error = error_1.returnAsFinalCloudSDKError(e, apiName); - return reject(error); + } + const returnValue = { + ret: parsedResult.ret, + result: parsedResult.result, + respBodyBuffer: parsedResult.respBodyBuffer, + respBody: parsedResult.respBody, + errMsg: msg_1.apiSuccessMsg(apiName), + } + resolve(returnValue) + } catch (e) { + const error = error_1.returnAsFinalCloudSDKError(e, apiName) + return reject(error) } - }); - }; -} -exports.default = getCallWXSvrkit; - - -/***/ }), + }) + } + } + exports.default = getCallWXSvrkit + /***/ }), -/***/ "./src/api/inner/index.ts": -/*!********************************!*\ + /***/ './src/api/inner/index.ts': + /*! ********************************!*\ !*** ./src/api/inner/index.ts ***! - \********************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createService = exports.SERVICE_NAME = void 0; -const api_1 = __webpack_require__(/*! ./api/api */ "./src/api/inner/api/api.ts"); -exports.SERVICE_NAME = 'inner'; -function createService(cloud) { - return { - name: exports.SERVICE_NAME, - getAPIs: api_1.getAPIs.bind(null, cloud), - }; -} -exports.createService = createService; -exports.default = createService; - - -/***/ }), + \******************************* */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.createService = exports.SERVICE_NAME = void 0 + const api_1 = __webpack_require__(/*! ./api/api */ './src/api/inner/api/api.ts') + exports.SERVICE_NAME = 'inner' + function createService(cloud) { + return { + name: exports.SERVICE_NAME, + getAPIs: api_1.getAPIs.bind(null, cloud), + } + } + exports.createService = createService + exports.default = createService + /***/ }), -/***/ "./src/api/utils/api/signature.ts": -/*!****************************************!*\ + /***/ './src/api/utils/api/signature.ts': + /*! ****************************************!*\ !*** ./src/api/utils/api/signature.ts ***! - \****************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MidasSignature = exports.signature = void 0; -const crypto = __webpack_require__(/*! crypto */ "crypto"); -const utils_1 = __webpack_require__(/*! utils/utils */ "./src/utils/utils.ts"); -function signature(options) { - switch (options.type) { - case 'midas': { - return new MidasSignature(options); + \*************************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.MidasSignature = exports.signature = void 0 + const crypto = __webpack_require__(/*! crypto */ 'crypto') + const utils_1 = __webpack_require__(/*! utils/utils */ './src/utils/utils.ts') + function signature(options) { + switch (options.type) { + case 'midas': { + return new MidasSignature(options) + } } - } -} -exports.signature = signature; -class MidasSignature { - constructor(options) { - this.type = 'midas'; - if (!options.params || !Array.isArray(options.params)) { - throw new Error('options.params must be a string array'); - } - if (!options.secret) { - throw new Error('options.secret must be provided'); - } - this.params = options.params; - this.secret = options.secret; - } - compute(cgiPath, method, secret, paramValues) { + } + exports.signature = signature + class MidasSignature { + constructor(options) { + this.type = 'midas' + if (!options.params || !Array.isArray(options.params)) { + throw new Error('options.params must be a string array') + } + if (!options.secret) { + throw new Error('options.secret must be provided') + } + this.params = options.params + this.secret = options.secret + } + + compute(cgiPath, method, secret, paramValues) { // sort params by ascii - const paramNames = [...this.params].sort().map(name => utils_1.convertCase(name, { + const paramNames = [...this.params].sort().map(name => utils_1.convertCase(name, { from: 'camelcase', to: 'snakecase', - })); - // get params string - const paramStr = paramNames.map(paramName => { + })) + // get params string + const paramStr = paramNames.map(paramName => { if (!paramValues.hasOwnProperty(paramName)) { - throw new Error(`Cannot compute signature: lack of param '${paramName}'`); + throw new Error(`Cannot compute signature: lack of param '${paramName}'`) } - return `${paramName}=${paramValues[paramName]}`; - }).join('&'); - // concatenate params string, cgi path, and midas secret - const signSource = paramStr + `&org_loc=${cgiPath}&method=${method}&secret=${secret}`; - // sign - const signature = crypto.createHmac('sha256', secret).update(signSource).digest('hex'); - return signature; - } -} -exports.MidasSignature = MidasSignature; -exports.default = signature; - - -/***/ }), + return `${paramName}=${paramValues[paramName]}` + }).join('&') + // concatenate params string, cgi path, and midas secret + const signSource = paramStr + `&org_loc=${cgiPath}&method=${method}&secret=${secret}` + // sign + const signature = crypto.createHmac('sha256', secret).update(signSource).digest('hex') + return signature + } + } + exports.MidasSignature = MidasSignature + exports.default = signature + /***/ }), -/***/ "./src/config/error.config.ts": -/*!************************************!*\ + /***/ './src/config/error.config.ts': + /*! ************************************!*\ !*** ./src/config/error.config.ts ***! - \************************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TCB_ERR_CODE = exports.ERR_CODE = void 0; -exports.ERR_CODE = { - '-1': 'unknown error', - UNKNOWN_ERROR: -1, - // 以 6 开始的是由微信服务器侧产生的错误码 - // 以 5 开始的是由腾讯云侧产生的错误码 - // 以 4 开始的是本地 SDK 产生的错误 - // 接下来两位表示具体业务类型:01通用,02数据库,03文件,04云函数 - // 最后三位表示具体的错误 - // 小程序 SDK 云函数 - '-404001': 'empty call result', - SDK_FUNCTIONS_EMPTY_CALL_RESULT: -404001, - '-404002': 'empty event id', - SDK_FUNCTIONS_EMPTY_EVENT_ID: -404002, - '-404003': 'empty poll url', - SDK_FUNCTIONS_EMPTY_POLL_URL: -404003, - '-404004': 'empty poll result json', - SDK_FUNCTIONS_EMPTY_POLL_RESULT_JSON: -404004, - '-404005': 'exceed max poll retry', - SDK_FUNCTIONS_EXCEED_MAX_POLL_RETRY: -404005, - '-404006': 'empty poll result base resp', - SDK_FUNCTIONS_EMPTY_POLL_RESULT_BASE_RESP: -404006, - '-404007': 'error while polling for the result, poll result base resp ret %s', - SDK_FUNCTIONS_POLL_RESULT_BASE_RESP_RET_ABNORMAL: -404007, - '-404008': 'error while polling for the result, polling server return a status code of %s', - SDK_FUNCTIONS_POLL_RESULT_STATUS_CODE_ERROR: -404008, - '-404009': 'error while polling for the result: %s', - SDK_FUNCTIONS_POLL_ERROR: -404009, - // 微信服务器 - '-601001': 'system error', - WX_SYSTEM_ERROR: -601001, - '-601002': 'system args error', - WX_SYSTEM_ARGS_ERROR: -601002, - '-601003': 'system network error', - WX_SYSTEM_NETWORK_ERROR: -601003, - '-601004': 'api permission denied', - WX_API_PERMISSION_DENIED: -601004, - '-601005': 'invalid cloudID', - WX_INVALID_CLOUDID: -601005, - '-601006': 'cloudID expired', - WX_CLOUDID_EXPIRED: -601006, - '-601007': 'cloudID and calling user does not match', - WX_CLOUDID_USER_NOT_MATCH: -601007, - '-601008': 'server-side request timedout', - WX_SERVER_REQUEST_TIMEOUT: -601008, - '-601009': 'missing mobile phone', - WX_MISSING_MOBILE_PHONE: -601009, - '-601010': 'no write permission', - WX_NO_WRITE_PERMISSION: -601010, - '-601011': 'no privilege permission', - WX_NO_PRIVILEGE_PERMISSION: -601011, - '-601012': 'unauthorized env', - WX_UNAUTHORIZED_ENV: -601012, - '-601013': 'no multiend permission', - WX_NO_MULTIEND_PERMISSION: -601013, - '-601015': 'access denied (cloudfunction cloudbase_auth returns empty errCode)', - WX_CLOUDBASE_AUTH_RETURN_EMPTY_ERRCODE: -601015, - '-601016': 'missing env auth info', - WX_MISSING_ENV_AUTH_INFO: -601016, - '-601017': 'access denied (cloudbase_auth returns non-zero errCode)', - WX_CLOUDBASE_AUTH_RETURN_NON_ZERO_ERRCODE: -601017, - '-602018': 'unauthorized API', - WX_UNAUTHORIZED_API: -601018, - '-602001': 'database query result size exceed limit (1MB)', - WX_DATABASE_QUERY_SIZE_EXCEED_LIMIT: -602001, - '-604001': 'cloudfunction result size exceed limit (1MB)', - WX_CLOUDFUNCTION_RESULT_SIZE_EXCEED_LIMIT: -604001, - '-604100': 'API not found', - WX_FUNCTIONS_SERVER_OPENAPI_NOT_FOUND: -604100, - '-604101': 'function has no permission to call this API', - WX_FUNCTIONS_SERVER_OPENAPI_NO_PERMISSION: -604101, - '-604102': 'call open API timeout', - WX_FUNCTIONS_SERVER_OPENAPI_TIMEOUT: -604102, - '-604103': 'call open API system error', - WX_FUNCTIONS_SERVER_OPENAPI_SYSTEM_ERROR: -604103, - '-604104': 'illegal source of invocation', - WX_FUNCTIONS_SERVER_OPENAPI_ILLEGAL_INVOCATION_SOURCE: -604104, - // 腾讯云通用 - '-501001': 'resource system error', - TCB_RESOURCE_SYSTEM_ERROR: -501001, - '-501002': 'resource server timeout', - TCB_RESOURCE_SERVER_TIMEOUT: -501002, - '-501003': 'exceed request limit', - TCB_EXCEED_REQUEST_LIMIT: -501003, - '-501004': 'exceed concurrent request limit', - TCB_EXCEED_CONCURRENT_REQUEST_LIMIT: -501004, - '-501005': 'invalid env', - TCB_INVALID_ENV: -501005, - '-501006': 'invalid common parameters', - TCB_INVALID_COMMON_PARAM: -501006, - '-501007': 'invalid parameters', - TCB_INVALID_PARAM: -501007, - '-501008': 'invalid request source', - TCB_INVALID_REQUEST_SOURCE: -501008, - '-501009': 'resource not initialized', - TCB_RESOURCE_NOT_INITIALIZED: -501009, - // 腾讯云数据库 - '-502001': 'database request fail', - TCB_DB_REQUEST_FAIL: -502001, - '-502002': 'database invalid command', - TCB_DB_INVALID_COMMAND: -502002, - '-502003': 'database permission denied', - TCB_DB_PERMISSION_DENIED: -502003, - '-502004': 'database exceed collection limit', - TCB_DB_EXCEED_COLLECTION_LIMIT: -502004, - '-502005': 'database collection not exists', - TCB_DB_COLLECTION_NOT_EXISTS: -502005, - // 腾讯云文件管理 - '-503001': 'storage request fail', - TCB_STORAGE_REQUEST_FAIL: -503001, - '-503002': 'storage permission denied', - TCB_STORAGE_PERMISSION_DENIED: -503002, - '-503003': 'storage file not exists', - TCB_STORAGE_FILE_NOT_EXISTS: -503003, - '-503004': 'storage invalid sign parameter', - TCB_STORAGE_INVALID_SIGN_PARAM: -503004, - // 腾讯云云函数 - '-504001': 'functions request fail', - TCB_FUNCTIONS_REQUEST_FAIL: -504001, - '-504002': 'functions execute fail', - TCB_FUNCTIONS_EXEC_FAIL: -504002, -}; -exports.TCB_ERR_CODE = { - // 通用 - SUCCESS: 0, - SYS_ERR: -501001, - SERVER_TIMEOUT: -501002, - EXCEED_REQUEST_LIMIT: -501003, - EXCEED_CONCURRENT_REQUEST_LIMIT: -501004, - INVALIID_ENV: -501005, - INVALID_COMMON_PARAM: -501006, - INVALID_PARAM: -501007, - INVALID_REQUEST_SOURCE: -501008, - RESOURCE_NOT_INITIAL: -501009, - // 数据库 - DATABASE_REQUEST_FAILED: -502001, - DATABASE_INVALID_OPERRATOR: -502002, - DATABASE_PERMISSION_DENIED: -502003, - DATABASE_COLLECTION_EXCEED_LIMIT: -502004, - DATABASE_COLLECTION_NOT_EXIST: -502005, - // 文件 - STORAGE_REQUEST_FAIL: -503001, - STORAGE_EXCEED_AUTHORITY: -503002, - STORAGE_FILE_NONEXIST: -503003, - STORAGE_SIGN_PARAM_INVALID: -503004, - // 云函数 - FUNCTIONS_REQUEST_FAIL: -504001, - FUNCTIONS_EXECUTE_FAIL: -504002, -}; - - -/***/ }), - -/***/ "./src/protobuf/openapi.js": -/*!*********************************!*\ + \*********************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.TCB_ERR_CODE = exports.ERR_CODE = void 0 + exports.ERR_CODE = { + '-1': 'unknown error', + UNKNOWN_ERROR: -1, + // 以 6 开始的是由微信服务器侧产生的错误码 + // 以 5 开始的是由腾讯云侧产生的错误码 + // 以 4 开始的是本地 SDK 产生的错误 + // 接下来两位表示具体业务类型:01通用,02数据库,03文件,04云函数 + // 最后三位表示具体的错误 + // 小程序 SDK 云函数 + '-404001': 'empty call result', + SDK_FUNCTIONS_EMPTY_CALL_RESULT: -404001, + '-404002': 'empty event id', + SDK_FUNCTIONS_EMPTY_EVENT_ID: -404002, + '-404003': 'empty poll url', + SDK_FUNCTIONS_EMPTY_POLL_URL: -404003, + '-404004': 'empty poll result json', + SDK_FUNCTIONS_EMPTY_POLL_RESULT_JSON: -404004, + '-404005': 'exceed max poll retry', + SDK_FUNCTIONS_EXCEED_MAX_POLL_RETRY: -404005, + '-404006': 'empty poll result base resp', + SDK_FUNCTIONS_EMPTY_POLL_RESULT_BASE_RESP: -404006, + '-404007': 'error while polling for the result, poll result base resp ret %s', + SDK_FUNCTIONS_POLL_RESULT_BASE_RESP_RET_ABNORMAL: -404007, + '-404008': 'error while polling for the result, polling server return a status code of %s', + SDK_FUNCTIONS_POLL_RESULT_STATUS_CODE_ERROR: -404008, + '-404009': 'error while polling for the result: %s', + SDK_FUNCTIONS_POLL_ERROR: -404009, + // 微信服务器 + '-601001': 'system error', + WX_SYSTEM_ERROR: -601001, + '-601002': 'system args error', + WX_SYSTEM_ARGS_ERROR: -601002, + '-601003': 'system network error', + WX_SYSTEM_NETWORK_ERROR: -601003, + '-601004': 'api permission denied', + WX_API_PERMISSION_DENIED: -601004, + '-601005': 'invalid cloudID', + WX_INVALID_CLOUDID: -601005, + '-601006': 'cloudID expired', + WX_CLOUDID_EXPIRED: -601006, + '-601007': 'cloudID and calling user does not match', + WX_CLOUDID_USER_NOT_MATCH: -601007, + '-601008': 'server-side request timedout', + WX_SERVER_REQUEST_TIMEOUT: -601008, + '-601009': 'missing mobile phone', + WX_MISSING_MOBILE_PHONE: -601009, + '-601010': 'no write permission', + WX_NO_WRITE_PERMISSION: -601010, + '-601011': 'no privilege permission', + WX_NO_PRIVILEGE_PERMISSION: -601011, + '-601012': 'unauthorized env', + WX_UNAUTHORIZED_ENV: -601012, + '-601013': 'no multiend permission', + WX_NO_MULTIEND_PERMISSION: -601013, + '-601015': 'access denied (cloudfunction cloudbase_auth returns empty errCode)', + WX_CLOUDBASE_AUTH_RETURN_EMPTY_ERRCODE: -601015, + '-601016': 'missing env auth info', + WX_MISSING_ENV_AUTH_INFO: -601016, + '-601017': 'access denied (cloudbase_auth returns non-zero errCode)', + WX_CLOUDBASE_AUTH_RETURN_NON_ZERO_ERRCODE: -601017, + '-602018': 'unauthorized API', + WX_UNAUTHORIZED_API: -601018, + '-602001': 'database query result size exceed limit (1MB)', + WX_DATABASE_QUERY_SIZE_EXCEED_LIMIT: -602001, + '-604001': 'cloudfunction result size exceed limit (1MB)', + WX_CLOUDFUNCTION_RESULT_SIZE_EXCEED_LIMIT: -604001, + '-604100': 'API not found', + WX_FUNCTIONS_SERVER_OPENAPI_NOT_FOUND: -604100, + '-604101': 'function has no permission to call this API', + WX_FUNCTIONS_SERVER_OPENAPI_NO_PERMISSION: -604101, + '-604102': 'call open API timeout', + WX_FUNCTIONS_SERVER_OPENAPI_TIMEOUT: -604102, + '-604103': 'call open API system error', + WX_FUNCTIONS_SERVER_OPENAPI_SYSTEM_ERROR: -604103, + '-604104': 'illegal source of invocation', + WX_FUNCTIONS_SERVER_OPENAPI_ILLEGAL_INVOCATION_SOURCE: -604104, + // 腾讯云通用 + '-501001': 'resource system error', + TCB_RESOURCE_SYSTEM_ERROR: -501001, + '-501002': 'resource server timeout', + TCB_RESOURCE_SERVER_TIMEOUT: -501002, + '-501003': 'exceed request limit', + TCB_EXCEED_REQUEST_LIMIT: -501003, + '-501004': 'exceed concurrent request limit', + TCB_EXCEED_CONCURRENT_REQUEST_LIMIT: -501004, + '-501005': 'invalid env', + TCB_INVALID_ENV: -501005, + '-501006': 'invalid common parameters', + TCB_INVALID_COMMON_PARAM: -501006, + '-501007': 'invalid parameters', + TCB_INVALID_PARAM: -501007, + '-501008': 'invalid request source', + TCB_INVALID_REQUEST_SOURCE: -501008, + '-501009': 'resource not initialized', + TCB_RESOURCE_NOT_INITIALIZED: -501009, + // 腾讯云数据库 + '-502001': 'database request fail', + TCB_DB_REQUEST_FAIL: -502001, + '-502002': 'database invalid command', + TCB_DB_INVALID_COMMAND: -502002, + '-502003': 'database permission denied', + TCB_DB_PERMISSION_DENIED: -502003, + '-502004': 'database exceed collection limit', + TCB_DB_EXCEED_COLLECTION_LIMIT: -502004, + '-502005': 'database collection not exists', + TCB_DB_COLLECTION_NOT_EXISTS: -502005, + // 腾讯云文件管理 + '-503001': 'storage request fail', + TCB_STORAGE_REQUEST_FAIL: -503001, + '-503002': 'storage permission denied', + TCB_STORAGE_PERMISSION_DENIED: -503002, + '-503003': 'storage file not exists', + TCB_STORAGE_FILE_NOT_EXISTS: -503003, + '-503004': 'storage invalid sign parameter', + TCB_STORAGE_INVALID_SIGN_PARAM: -503004, + // 腾讯云云函数 + '-504001': 'functions request fail', + TCB_FUNCTIONS_REQUEST_FAIL: -504001, + '-504002': 'functions execute fail', + TCB_FUNCTIONS_EXEC_FAIL: -504002, + } + exports.TCB_ERR_CODE = { + // 通用 + SUCCESS: 0, + SYS_ERR: -501001, + SERVER_TIMEOUT: -501002, + EXCEED_REQUEST_LIMIT: -501003, + EXCEED_CONCURRENT_REQUEST_LIMIT: -501004, + INVALIID_ENV: -501005, + INVALID_COMMON_PARAM: -501006, + INVALID_PARAM: -501007, + INVALID_REQUEST_SOURCE: -501008, + RESOURCE_NOT_INITIAL: -501009, + // 数据库 + DATABASE_REQUEST_FAILED: -502001, + DATABASE_INVALID_OPERRATOR: -502002, + DATABASE_PERMISSION_DENIED: -502003, + DATABASE_COLLECTION_EXCEED_LIMIT: -502004, + DATABASE_COLLECTION_NOT_EXIST: -502005, + // 文件 + STORAGE_REQUEST_FAIL: -503001, + STORAGE_EXCEED_AUTHORITY: -503002, + STORAGE_FILE_NONEXIST: -503003, + STORAGE_SIGN_PARAM_INVALID: -503004, + // 云函数 + FUNCTIONS_REQUEST_FAIL: -504001, + FUNCTIONS_EXECUTE_FAIL: -504002, + } + /***/ }), + + /***/ './src/protobuf/openapi.js': + /*! *********************************!*\ !*** ./src/protobuf/openapi.js ***! - \*********************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { + \******************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + /* eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars */ -"use strict"; -/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ + var $protobuf = __webpack_require__(/*! protobufjs/minimal */ 'protobufjs/minimal') + // Common aliases + var $Reader = $protobuf.Reader; var $Writer = $protobuf.Writer; var + $util = $protobuf.util -var $protobuf = __webpack_require__(/*! protobufjs/minimal */ "protobufjs/minimal"); + // Exported root namespace + var $root = $protobuf.roots.default || ($protobuf.roots.default = {}) -// Common aliases -var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; - -// Exported root namespace -var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); - -$root.KeyValuePair = (function() { - - /** + $root.KeyValuePair = (function () { + /** * Properties of a KeyValuePair. * @exports IKeyValuePair * @interface IKeyValuePair @@ -839,7 +780,7 @@ $root.KeyValuePair = (function() { * @property {string|null} [filename] KeyValuePair filename */ - /** + /** * Constructs a new KeyValuePair. * @exports KeyValuePair * @classdesc Represents a KeyValuePair. @@ -847,46 +788,43 @@ $root.KeyValuePair = (function() { * @constructor * @param {IKeyValuePair=} [properties] Properties to set */ - function KeyValuePair(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function KeyValuePair(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * KeyValuePair key. * @member {string} key * @memberof KeyValuePair * @instance */ - KeyValuePair.prototype.key = ""; + KeyValuePair.prototype.key = '' - /** + /** * KeyValuePair value. * @member {Uint8Array} value * @memberof KeyValuePair * @instance */ - KeyValuePair.prototype.value = $util.newBuffer([]); + KeyValuePair.prototype.value = $util.newBuffer([]) - /** + /** * KeyValuePair contenttype. * @member {string} contenttype * @memberof KeyValuePair * @instance */ - KeyValuePair.prototype.contenttype = ""; + KeyValuePair.prototype.contenttype = '' - /** + /** * KeyValuePair filename. * @member {string} filename * @memberof KeyValuePair * @instance */ - KeyValuePair.prototype.filename = ""; + KeyValuePair.prototype.filename = '' - /** + /** * Creates a new KeyValuePair instance using the specified properties. * @function create * @memberof KeyValuePair @@ -894,11 +832,11 @@ $root.KeyValuePair = (function() { * @param {IKeyValuePair=} [properties] Properties to set * @returns {KeyValuePair} KeyValuePair instance */ - KeyValuePair.create = function create(properties) { - return new KeyValuePair(properties); - }; + KeyValuePair.create = function create(properties) { + return new KeyValuePair(properties) + } - /** + /** * Encodes the specified KeyValuePair message. Does not implicitly {@link KeyValuePair.verify|verify} messages. * @function encode * @memberof KeyValuePair @@ -907,21 +845,16 @@ $root.KeyValuePair = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - KeyValuePair.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.key != null && message.hasOwnProperty("key")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.key); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.value); - if (message.contenttype != null && message.hasOwnProperty("contenttype")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.contenttype); - if (message.filename != null && message.hasOwnProperty("filename")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.filename); - return writer; - }; - - /** + KeyValuePair.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.key != null && message.hasOwnProperty('key')) writer.uint32(/* id 1, wireType 2 = */10).string(message.key) + if (message.value != null && message.hasOwnProperty('value')) writer.uint32(/* id 2, wireType 2 = */18).bytes(message.value) + if (message.contenttype != null && message.hasOwnProperty('contenttype')) writer.uint32(/* id 3, wireType 2 = */26).string(message.contenttype) + if (message.filename != null && message.hasOwnProperty('filename')) writer.uint32(/* id 4, wireType 2 = */34).string(message.filename) + return writer + } + + /** * Encodes the specified KeyValuePair message, length delimited. Does not implicitly {@link KeyValuePair.verify|verify} messages. * @function encodeDelimited * @memberof KeyValuePair @@ -930,11 +863,11 @@ $root.KeyValuePair = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - KeyValuePair.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + KeyValuePair.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a KeyValuePair message from the specified reader or buffer. * @function decode * @memberof KeyValuePair @@ -945,34 +878,34 @@ $root.KeyValuePair = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - KeyValuePair.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.KeyValuePair(); - while (reader.pos < end) { - var tag = reader.uint32(); + KeyValuePair.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.KeyValuePair() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.key = reader.string(); - break; - case 2: - message.value = reader.bytes(); - break; - case 3: - message.contenttype = reader.string(); - break; - case 4: - message.filename = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.key = reader.string() + break + case 2: + message.value = reader.bytes() + break + case 3: + message.contenttype = reader.string() + break + case 4: + message.filename = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a KeyValuePair message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof KeyValuePair @@ -982,13 +915,12 @@ $root.KeyValuePair = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - KeyValuePair.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + KeyValuePair.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a KeyValuePair message. * @function verify * @memberof KeyValuePair @@ -996,25 +928,16 @@ $root.KeyValuePair = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - KeyValuePair.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.key != null && message.hasOwnProperty("key")) - if (!$util.isString(message.key)) - return "key: string expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!(message.value && typeof message.value.length === "number" || $util.isString(message.value))) - return "value: buffer expected"; - if (message.contenttype != null && message.hasOwnProperty("contenttype")) - if (!$util.isString(message.contenttype)) - return "contenttype: string expected"; - if (message.filename != null && message.hasOwnProperty("filename")) - if (!$util.isString(message.filename)) - return "filename: string expected"; - return null; - }; - - /** + KeyValuePair.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.key != null && message.hasOwnProperty('key')) if (!$util.isString(message.key)) return 'key: string expected' + if (message.value != null && message.hasOwnProperty('value')) if (!(message.value && typeof message.value.length === 'number' || $util.isString(message.value))) return 'value: buffer expected' + if (message.contenttype != null && message.hasOwnProperty('contenttype')) if (!$util.isString(message.contenttype)) return 'contenttype: string expected' + if (message.filename != null && message.hasOwnProperty('filename')) if (!$util.isString(message.filename)) return 'filename: string expected' + return null + } + + /** * Creates a KeyValuePair message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof KeyValuePair @@ -1022,25 +945,20 @@ $root.KeyValuePair = (function() { * @param {Object.} object Plain object * @returns {KeyValuePair} KeyValuePair */ - KeyValuePair.fromObject = function fromObject(object) { - if (object instanceof $root.KeyValuePair) - return object; - var message = new $root.KeyValuePair(); - if (object.key != null) - message.key = String(object.key); - if (object.value != null) - if (typeof object.value === "string") - $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0); - else if (object.value.length) - message.value = object.value; - if (object.contenttype != null) - message.contenttype = String(object.contenttype); - if (object.filename != null) - message.filename = String(object.filename); - return message; - }; - - /** + KeyValuePair.fromObject = function fromObject(object) { + if (object instanceof $root.KeyValuePair) return object + var message = new $root.KeyValuePair() + if (object.key != null) message.key = String(object.key) + if (object.value != null) { + if (typeof object.value === 'string') $util.base64.decode(object.value, message.value = $util.newBuffer($util.base64.length(object.value)), 0) + else if (object.value.length) message.value = object.value + } + if (object.contenttype != null) message.contenttype = String(object.contenttype) + if (object.filename != null) message.filename = String(object.filename) + return message + } + + /** * Creates a plain object from a KeyValuePair message. Also converts values to other types if specified. * @function toObject * @memberof KeyValuePair @@ -1049,57 +967,49 @@ $root.KeyValuePair = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - KeyValuePair.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.key = ""; - if (options.bytes === String) - object.value = ""; + KeyValuePair.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.key = '' + if (options.bytes === String) object.value = '' else { - object.value = []; - if (options.bytes !== Array) - object.value = $util.newBuffer(object.value); + object.value = [] + if (options.bytes !== Array) object.value = $util.newBuffer(object.value) } - object.contenttype = ""; - object.filename = ""; - } - if (message.key != null && message.hasOwnProperty("key")) - object.key = message.key; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value; - if (message.contenttype != null && message.hasOwnProperty("contenttype")) - object.contenttype = message.contenttype; - if (message.filename != null && message.hasOwnProperty("filename")) - object.filename = message.filename; - return object; - }; - - /** + object.contenttype = '' + object.filename = '' + } + if (message.key != null && message.hasOwnProperty('key')) object.key = message.key + if (message.value != null && message.hasOwnProperty('value')) object.value = options.bytes === String ? $util.base64.encode(message.value, 0, message.value.length) : options.bytes === Array ? Array.prototype.slice.call(message.value) : message.value + if (message.contenttype != null && message.hasOwnProperty('contenttype')) object.contenttype = message.contenttype + if (message.filename != null && message.hasOwnProperty('filename')) object.filename = message.filename + return object + } + + /** * Converts this KeyValuePair to JSON. * @function toJSON * @memberof KeyValuePair * @instance * @returns {Object.} JSON object */ - KeyValuePair.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return KeyValuePair; -})(); + KeyValuePair.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.OpenApiData = (function() { + return KeyValuePair + }()) - /** + $root.OpenApiData = (function () { + /** * Properties of an OpenApiData. * @exports IOpenApiData * @interface IOpenApiData * @property {Array.|null} [pairs] OpenApiData pairs */ - /** + /** * Constructs a new OpenApiData. * @exports OpenApiData * @classdesc Represents an OpenApiData. @@ -1107,23 +1017,20 @@ $root.OpenApiData = (function() { * @constructor * @param {IOpenApiData=} [properties] Properties to set */ - function OpenApiData(properties) { - this.pairs = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function OpenApiData(properties) { + this.pairs = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * OpenApiData pairs. * @member {Array.} pairs * @memberof OpenApiData * @instance */ - OpenApiData.prototype.pairs = $util.emptyArray; + OpenApiData.prototype.pairs = $util.emptyArray - /** + /** * Creates a new OpenApiData instance using the specified properties. * @function create * @memberof OpenApiData @@ -1131,11 +1038,11 @@ $root.OpenApiData = (function() { * @param {IOpenApiData=} [properties] Properties to set * @returns {OpenApiData} OpenApiData instance */ - OpenApiData.create = function create(properties) { - return new OpenApiData(properties); - }; + OpenApiData.create = function create(properties) { + return new OpenApiData(properties) + } - /** + /** * Encodes the specified OpenApiData message. Does not implicitly {@link OpenApiData.verify|verify} messages. * @function encode * @memberof OpenApiData @@ -1144,16 +1051,13 @@ $root.OpenApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - OpenApiData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.pairs != null && message.pairs.length) - for (var i = 0; i < message.pairs.length; ++i) - $root.KeyValuePair.encode(message.pairs[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; + OpenApiData.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.pairs != null && message.pairs.length) for (var i = 0; i < message.pairs.length; ++i) $root.KeyValuePair.encode(message.pairs[i], writer.uint32(/* id 1, wireType 2 = */10).fork()).ldelim() + return writer + } - /** + /** * Encodes the specified OpenApiData message, length delimited. Does not implicitly {@link OpenApiData.verify|verify} messages. * @function encodeDelimited * @memberof OpenApiData @@ -1162,11 +1066,11 @@ $root.OpenApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - OpenApiData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + OpenApiData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an OpenApiData message from the specified reader or buffer. * @function decode * @memberof OpenApiData @@ -1177,27 +1081,26 @@ $root.OpenApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OpenApiData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.OpenApiData(); - while (reader.pos < end) { - var tag = reader.uint32(); + OpenApiData.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.OpenApiData() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - if (!(message.pairs && message.pairs.length)) - message.pairs = []; - message.pairs.push($root.KeyValuePair.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + if (!(message.pairs && message.pairs.length)) message.pairs = [] + message.pairs.push($root.KeyValuePair.decode(reader, reader.uint32())) + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an OpenApiData message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof OpenApiData @@ -1207,13 +1110,12 @@ $root.OpenApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OpenApiData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + OpenApiData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an OpenApiData message. * @function verify * @memberof OpenApiData @@ -1221,22 +1123,19 @@ $root.OpenApiData = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - OpenApiData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.pairs != null && message.hasOwnProperty("pairs")) { - if (!Array.isArray(message.pairs)) - return "pairs: array expected"; + OpenApiData.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.pairs != null && message.hasOwnProperty('pairs')) { + if (!Array.isArray(message.pairs)) return 'pairs: array expected' for (var i = 0; i < message.pairs.length; ++i) { - var error = $root.KeyValuePair.verify(message.pairs[i]); - if (error) - return "pairs." + error; + var error = $root.KeyValuePair.verify(message.pairs[i]) + if (error) return 'pairs.' + error } + } + return null } - return null; - }; - /** + /** * Creates an OpenApiData message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof OpenApiData @@ -1244,24 +1143,21 @@ $root.OpenApiData = (function() { * @param {Object.} object Plain object * @returns {OpenApiData} OpenApiData */ - OpenApiData.fromObject = function fromObject(object) { - if (object instanceof $root.OpenApiData) - return object; - var message = new $root.OpenApiData(); - if (object.pairs) { - if (!Array.isArray(object.pairs)) - throw TypeError(".OpenApiData.pairs: array expected"); - message.pairs = []; + OpenApiData.fromObject = function fromObject(object) { + if (object instanceof $root.OpenApiData) return object + var message = new $root.OpenApiData() + if (object.pairs) { + if (!Array.isArray(object.pairs)) throw TypeError('.OpenApiData.pairs: array expected') + message.pairs = [] for (var i = 0; i < object.pairs.length; ++i) { - if (typeof object.pairs[i] !== "object") - throw TypeError(".OpenApiData.pairs: object expected"); - message.pairs[i] = $root.KeyValuePair.fromObject(object.pairs[i]); + if (typeof object.pairs[i] !== 'object') throw TypeError('.OpenApiData.pairs: object expected') + message.pairs[i] = $root.KeyValuePair.fromObject(object.pairs[i]) } + } + return message } - return message; - }; - /** + /** * Creates a plain object from an OpenApiData message. Also converts values to other types if specified. * @function toObject * @memberof OpenApiData @@ -1270,37 +1166,33 @@ $root.OpenApiData = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - OpenApiData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.pairs = []; - if (message.pairs && message.pairs.length) { - object.pairs = []; - for (var j = 0; j < message.pairs.length; ++j) - object.pairs[j] = $root.KeyValuePair.toObject(message.pairs[j], options); - } - return object; - }; - - /** + OpenApiData.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.pairs = [] + if (message.pairs && message.pairs.length) { + object.pairs = [] + for (var j = 0; j < message.pairs.length; ++j) object.pairs[j] = $root.KeyValuePair.toObject(message.pairs[j], options) + } + return object + } + + /** * Converts this OpenApiData to JSON. * @function toJSON * @memberof OpenApiData * @instance * @returns {Object.} JSON object */ - OpenApiData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return OpenApiData; -})(); + OpenApiData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.TokenApiData = (function() { + return OpenApiData + }()) - /** + $root.TokenApiData = (function () { + /** * Properties of a TokenApiData. * @exports ITokenApiData * @interface ITokenApiData @@ -1308,7 +1200,7 @@ $root.TokenApiData = (function() { * @property {string|null} [resourceEnv] TokenApiData resourceEnv */ - /** + /** * Constructs a new TokenApiData. * @exports TokenApiData * @classdesc Represents a TokenApiData. @@ -1316,30 +1208,27 @@ $root.TokenApiData = (function() { * @constructor * @param {ITokenApiData=} [properties] Properties to set */ - function TokenApiData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function TokenApiData(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * TokenApiData resourceAppid. * @member {string} resourceAppid * @memberof TokenApiData * @instance */ - TokenApiData.prototype.resourceAppid = ""; + TokenApiData.prototype.resourceAppid = '' - /** + /** * TokenApiData resourceEnv. * @member {string} resourceEnv * @memberof TokenApiData * @instance */ - TokenApiData.prototype.resourceEnv = ""; + TokenApiData.prototype.resourceEnv = '' - /** + /** * Creates a new TokenApiData instance using the specified properties. * @function create * @memberof TokenApiData @@ -1347,11 +1236,11 @@ $root.TokenApiData = (function() { * @param {ITokenApiData=} [properties] Properties to set * @returns {TokenApiData} TokenApiData instance */ - TokenApiData.create = function create(properties) { - return new TokenApiData(properties); - }; + TokenApiData.create = function create(properties) { + return new TokenApiData(properties) + } - /** + /** * Encodes the specified TokenApiData message. Does not implicitly {@link TokenApiData.verify|verify} messages. * @function encode * @memberof TokenApiData @@ -1360,17 +1249,14 @@ $root.TokenApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TokenApiData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceAppid != null && message.hasOwnProperty("resourceAppid")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.resourceAppid); - if (message.resourceEnv != null && message.hasOwnProperty("resourceEnv")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.resourceEnv); - return writer; - }; - - /** + TokenApiData.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.resourceAppid != null && message.hasOwnProperty('resourceAppid')) writer.uint32(/* id 1, wireType 2 = */10).string(message.resourceAppid) + if (message.resourceEnv != null && message.hasOwnProperty('resourceEnv')) writer.uint32(/* id 2, wireType 2 = */18).string(message.resourceEnv) + return writer + } + + /** * Encodes the specified TokenApiData message, length delimited. Does not implicitly {@link TokenApiData.verify|verify} messages. * @function encodeDelimited * @memberof TokenApiData @@ -1379,11 +1265,11 @@ $root.TokenApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TokenApiData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + TokenApiData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a TokenApiData message from the specified reader or buffer. * @function decode * @memberof TokenApiData @@ -1394,28 +1280,28 @@ $root.TokenApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TokenApiData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.TokenApiData(); - while (reader.pos < end) { - var tag = reader.uint32(); + TokenApiData.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.TokenApiData() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.resourceAppid = reader.string(); - break; - case 2: - message.resourceEnv = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.resourceAppid = reader.string() + break + case 2: + message.resourceEnv = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a TokenApiData message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof TokenApiData @@ -1425,13 +1311,12 @@ $root.TokenApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TokenApiData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + TokenApiData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a TokenApiData message. * @function verify * @memberof TokenApiData @@ -1439,19 +1324,14 @@ $root.TokenApiData = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TokenApiData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceAppid != null && message.hasOwnProperty("resourceAppid")) - if (!$util.isString(message.resourceAppid)) - return "resourceAppid: string expected"; - if (message.resourceEnv != null && message.hasOwnProperty("resourceEnv")) - if (!$util.isString(message.resourceEnv)) - return "resourceEnv: string expected"; - return null; - }; - - /** + TokenApiData.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.resourceAppid != null && message.hasOwnProperty('resourceAppid')) if (!$util.isString(message.resourceAppid)) return 'resourceAppid: string expected' + if (message.resourceEnv != null && message.hasOwnProperty('resourceEnv')) if (!$util.isString(message.resourceEnv)) return 'resourceEnv: string expected' + return null + } + + /** * Creates a TokenApiData message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof TokenApiData @@ -1459,18 +1339,15 @@ $root.TokenApiData = (function() { * @param {Object.} object Plain object * @returns {TokenApiData} TokenApiData */ - TokenApiData.fromObject = function fromObject(object) { - if (object instanceof $root.TokenApiData) - return object; - var message = new $root.TokenApiData(); - if (object.resourceAppid != null) - message.resourceAppid = String(object.resourceAppid); - if (object.resourceEnv != null) - message.resourceEnv = String(object.resourceEnv); - return message; - }; - - /** + TokenApiData.fromObject = function fromObject(object) { + if (object instanceof $root.TokenApiData) return object + var message = new $root.TokenApiData() + if (object.resourceAppid != null) message.resourceAppid = String(object.resourceAppid) + if (object.resourceEnv != null) message.resourceEnv = String(object.resourceEnv) + return message + } + + /** * Creates a plain object from a TokenApiData message. Also converts values to other types if specified. * @function toObject * @memberof TokenApiData @@ -1479,38 +1356,34 @@ $root.TokenApiData = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TokenApiData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.resourceAppid = ""; - object.resourceEnv = ""; - } - if (message.resourceAppid != null && message.hasOwnProperty("resourceAppid")) - object.resourceAppid = message.resourceAppid; - if (message.resourceEnv != null && message.hasOwnProperty("resourceEnv")) - object.resourceEnv = message.resourceEnv; - return object; - }; - - /** + TokenApiData.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.resourceAppid = '' + object.resourceEnv = '' + } + if (message.resourceAppid != null && message.hasOwnProperty('resourceAppid')) object.resourceAppid = message.resourceAppid + if (message.resourceEnv != null && message.hasOwnProperty('resourceEnv')) object.resourceEnv = message.resourceEnv + return object + } + + /** * Converts this TokenApiData to JSON. * @function toJSON * @memberof TokenApiData * @instance * @returns {Object.} JSON object */ - TokenApiData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return TokenApiData; -})(); + TokenApiData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.CommApiData = (function() { + return TokenApiData + }()) - /** + $root.CommApiData = (function () { + /** * Properties of a CommApiData. * @exports ICommApiData * @interface ICommApiData @@ -1522,7 +1395,7 @@ $root.CommApiData = (function() { * @property {string|null} [appid] CommApiData appid */ - /** + /** * Constructs a new CommApiData. * @exports CommApiData * @classdesc Represents a CommApiData. @@ -1530,62 +1403,59 @@ $root.CommApiData = (function() { * @constructor * @param {ICommApiData=} [properties] Properties to set */ - function CommApiData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function CommApiData(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * CommApiData apiType. * @member {CommApiData.ApiType} apiType * @memberof CommApiData * @instance */ - CommApiData.prototype.apiType = 0; + CommApiData.prototype.apiType = 0 - /** + /** * CommApiData openapiData. * @member {IOpenApiData|null|undefined} openapiData * @memberof CommApiData * @instance */ - CommApiData.prototype.openapiData = null; + CommApiData.prototype.openapiData = null - /** + /** * CommApiData innerData. * @member {IInnerApiData|null|undefined} innerData * @memberof CommApiData * @instance */ - CommApiData.prototype.innerData = null; + CommApiData.prototype.innerData = null - /** + /** * CommApiData svrkitData. * @member {ISvrkitApiData|null|undefined} svrkitData * @memberof CommApiData * @instance */ - CommApiData.prototype.svrkitData = null; + CommApiData.prototype.svrkitData = null - /** + /** * CommApiData tokenData. * @member {ITokenApiData|null|undefined} tokenData * @memberof CommApiData * @instance */ - CommApiData.prototype.tokenData = null; + CommApiData.prototype.tokenData = null - /** + /** * CommApiData appid. * @member {string} appid * @memberof CommApiData * @instance */ - CommApiData.prototype.appid = ""; + CommApiData.prototype.appid = '' - /** + /** * Creates a new CommApiData instance using the specified properties. * @function create * @memberof CommApiData @@ -1593,11 +1463,11 @@ $root.CommApiData = (function() { * @param {ICommApiData=} [properties] Properties to set * @returns {CommApiData} CommApiData instance */ - CommApiData.create = function create(properties) { - return new CommApiData(properties); - }; + CommApiData.create = function create(properties) { + return new CommApiData(properties) + } - /** + /** * Encodes the specified CommApiData message. Does not implicitly {@link CommApiData.verify|verify} messages. * @function encode * @memberof CommApiData @@ -1606,25 +1476,18 @@ $root.CommApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - CommApiData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.apiType != null && message.hasOwnProperty("apiType")) - writer.uint32(/* id 1, wireType 0 =*/8).int32(message.apiType); - if (message.openapiData != null && message.hasOwnProperty("openapiData")) - $root.OpenApiData.encode(message.openapiData, writer.uint32(/* id 2, wireType 2 =*/18).fork()).ldelim(); - if (message.innerData != null && message.hasOwnProperty("innerData")) - $root.InnerApiData.encode(message.innerData, writer.uint32(/* id 3, wireType 2 =*/26).fork()).ldelim(); - if (message.svrkitData != null && message.hasOwnProperty("svrkitData")) - $root.SvrkitApiData.encode(message.svrkitData, writer.uint32(/* id 4, wireType 2 =*/34).fork()).ldelim(); - if (message.tokenData != null && message.hasOwnProperty("tokenData")) - $root.TokenApiData.encode(message.tokenData, writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.appid != null && message.hasOwnProperty("appid")) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.appid); - return writer; - }; - - /** + CommApiData.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.apiType != null && message.hasOwnProperty('apiType')) writer.uint32(/* id 1, wireType 0 = */8).int32(message.apiType) + if (message.openapiData != null && message.hasOwnProperty('openapiData')) $root.OpenApiData.encode(message.openapiData, writer.uint32(/* id 2, wireType 2 = */18).fork()).ldelim() + if (message.innerData != null && message.hasOwnProperty('innerData')) $root.InnerApiData.encode(message.innerData, writer.uint32(/* id 3, wireType 2 = */26).fork()).ldelim() + if (message.svrkitData != null && message.hasOwnProperty('svrkitData')) $root.SvrkitApiData.encode(message.svrkitData, writer.uint32(/* id 4, wireType 2 = */34).fork()).ldelim() + if (message.tokenData != null && message.hasOwnProperty('tokenData')) $root.TokenApiData.encode(message.tokenData, writer.uint32(/* id 5, wireType 2 = */42).fork()).ldelim() + if (message.appid != null && message.hasOwnProperty('appid')) writer.uint32(/* id 6, wireType 2 = */50).string(message.appid) + return writer + } + + /** * Encodes the specified CommApiData message, length delimited. Does not implicitly {@link CommApiData.verify|verify} messages. * @function encodeDelimited * @memberof CommApiData @@ -1633,11 +1496,11 @@ $root.CommApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - CommApiData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + CommApiData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a CommApiData message from the specified reader or buffer. * @function decode * @memberof CommApiData @@ -1648,40 +1511,40 @@ $root.CommApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommApiData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.CommApiData(); - while (reader.pos < end) { - var tag = reader.uint32(); + CommApiData.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.CommApiData() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.apiType = reader.int32(); - break; - case 2: - message.openapiData = $root.OpenApiData.decode(reader, reader.uint32()); - break; - case 3: - message.innerData = $root.InnerApiData.decode(reader, reader.uint32()); - break; - case 4: - message.svrkitData = $root.SvrkitApiData.decode(reader, reader.uint32()); - break; - case 5: - message.tokenData = $root.TokenApiData.decode(reader, reader.uint32()); - break; - case 6: - message.appid = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.apiType = reader.int32() + break + case 2: + message.openapiData = $root.OpenApiData.decode(reader, reader.uint32()) + break + case 3: + message.innerData = $root.InnerApiData.decode(reader, reader.uint32()) + break + case 4: + message.svrkitData = $root.SvrkitApiData.decode(reader, reader.uint32()) + break + case 5: + message.tokenData = $root.TokenApiData.decode(reader, reader.uint32()) + break + case 6: + message.appid = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a CommApiData message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof CommApiData @@ -1691,13 +1554,12 @@ $root.CommApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommApiData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + CommApiData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a CommApiData message. * @function verify * @memberof CommApiData @@ -1705,46 +1567,40 @@ $root.CommApiData = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - CommApiData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.apiType != null && message.hasOwnProperty("apiType")) + CommApiData.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.apiType != null && message.hasOwnProperty('apiType')) { switch (message.apiType) { - default: - return "apiType: enum value expected"; - case 0: - case 1: - case 2: - case 3: - break; + default: + return 'apiType: enum value expected' + case 0: + case 1: + case 2: + case 3: + break } - if (message.openapiData != null && message.hasOwnProperty("openapiData")) { - var error = $root.OpenApiData.verify(message.openapiData); - if (error) - return "openapiData." + error; - } - if (message.innerData != null && message.hasOwnProperty("innerData")) { - var error = $root.InnerApiData.verify(message.innerData); - if (error) - return "innerData." + error; - } - if (message.svrkitData != null && message.hasOwnProperty("svrkitData")) { - var error = $root.SvrkitApiData.verify(message.svrkitData); - if (error) - return "svrkitData." + error; - } - if (message.tokenData != null && message.hasOwnProperty("tokenData")) { - var error = $root.TokenApiData.verify(message.tokenData); - if (error) - return "tokenData." + error; - } - if (message.appid != null && message.hasOwnProperty("appid")) - if (!$util.isString(message.appid)) - return "appid: string expected"; - return null; - }; - - /** + } + if (message.openapiData != null && message.hasOwnProperty('openapiData')) { + var error = $root.OpenApiData.verify(message.openapiData) + if (error) return 'openapiData.' + error + } + if (message.innerData != null && message.hasOwnProperty('innerData')) { + var error = $root.InnerApiData.verify(message.innerData) + if (error) return 'innerData.' + error + } + if (message.svrkitData != null && message.hasOwnProperty('svrkitData')) { + var error = $root.SvrkitApiData.verify(message.svrkitData) + if (error) return 'svrkitData.' + error + } + if (message.tokenData != null && message.hasOwnProperty('tokenData')) { + var error = $root.TokenApiData.verify(message.tokenData) + if (error) return 'tokenData.' + error + } + if (message.appid != null && message.hasOwnProperty('appid')) if (!$util.isString(message.appid)) return 'appid: string expected' + return null + } + + /** * Creates a CommApiData message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof CommApiData @@ -1752,54 +1608,48 @@ $root.CommApiData = (function() { * @param {Object.} object Plain object * @returns {CommApiData} CommApiData */ - CommApiData.fromObject = function fromObject(object) { - if (object instanceof $root.CommApiData) - return object; - var message = new $root.CommApiData(); - switch (object.apiType) { - case "OPEN_API": - case 0: - message.apiType = 0; - break; - case "INNER_API": - case 1: - message.apiType = 1; - break; - case "SVRKIT_API": - case 2: - message.apiType = 2; - break; - case "TOKEN_API": - case 3: - message.apiType = 3; - break; - } - if (object.openapiData != null) { - if (typeof object.openapiData !== "object") - throw TypeError(".CommApiData.openapiData: object expected"); - message.openapiData = $root.OpenApiData.fromObject(object.openapiData); - } - if (object.innerData != null) { - if (typeof object.innerData !== "object") - throw TypeError(".CommApiData.innerData: object expected"); - message.innerData = $root.InnerApiData.fromObject(object.innerData); - } - if (object.svrkitData != null) { - if (typeof object.svrkitData !== "object") - throw TypeError(".CommApiData.svrkitData: object expected"); - message.svrkitData = $root.SvrkitApiData.fromObject(object.svrkitData); - } - if (object.tokenData != null) { - if (typeof object.tokenData !== "object") - throw TypeError(".CommApiData.tokenData: object expected"); - message.tokenData = $root.TokenApiData.fromObject(object.tokenData); - } - if (object.appid != null) - message.appid = String(object.appid); - return message; - }; - - /** + CommApiData.fromObject = function fromObject(object) { + if (object instanceof $root.CommApiData) return object + var message = new $root.CommApiData() + switch (object.apiType) { + case 'OPEN_API': + case 0: + message.apiType = 0 + break + case 'INNER_API': + case 1: + message.apiType = 1 + break + case 'SVRKIT_API': + case 2: + message.apiType = 2 + break + case 'TOKEN_API': + case 3: + message.apiType = 3 + break + } + if (object.openapiData != null) { + if (typeof object.openapiData !== 'object') throw TypeError('.CommApiData.openapiData: object expected') + message.openapiData = $root.OpenApiData.fromObject(object.openapiData) + } + if (object.innerData != null) { + if (typeof object.innerData !== 'object') throw TypeError('.CommApiData.innerData: object expected') + message.innerData = $root.InnerApiData.fromObject(object.innerData) + } + if (object.svrkitData != null) { + if (typeof object.svrkitData !== 'object') throw TypeError('.CommApiData.svrkitData: object expected') + message.svrkitData = $root.SvrkitApiData.fromObject(object.svrkitData) + } + if (object.tokenData != null) { + if (typeof object.tokenData !== 'object') throw TypeError('.CommApiData.tokenData: object expected') + message.tokenData = $root.TokenApiData.fromObject(object.tokenData) + } + if (object.appid != null) message.appid = String(object.appid) + return message + } + + /** * Creates a plain object from a CommApiData message. Also converts values to other types if specified. * @function toObject * @memberof CommApiData @@ -1808,45 +1658,38 @@ $root.CommApiData = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CommApiData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.apiType = options.enums === String ? "OPEN_API" : 0; - object.openapiData = null; - object.innerData = null; - object.svrkitData = null; - object.tokenData = null; - object.appid = ""; - } - if (message.apiType != null && message.hasOwnProperty("apiType")) - object.apiType = options.enums === String ? $root.CommApiData.ApiType[message.apiType] : message.apiType; - if (message.openapiData != null && message.hasOwnProperty("openapiData")) - object.openapiData = $root.OpenApiData.toObject(message.openapiData, options); - if (message.innerData != null && message.hasOwnProperty("innerData")) - object.innerData = $root.InnerApiData.toObject(message.innerData, options); - if (message.svrkitData != null && message.hasOwnProperty("svrkitData")) - object.svrkitData = $root.SvrkitApiData.toObject(message.svrkitData, options); - if (message.tokenData != null && message.hasOwnProperty("tokenData")) - object.tokenData = $root.TokenApiData.toObject(message.tokenData, options); - if (message.appid != null && message.hasOwnProperty("appid")) - object.appid = message.appid; - return object; - }; - - /** + CommApiData.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.apiType = options.enums === String ? 'OPEN_API' : 0 + object.openapiData = null + object.innerData = null + object.svrkitData = null + object.tokenData = null + object.appid = '' + } + if (message.apiType != null && message.hasOwnProperty('apiType')) object.apiType = options.enums === String ? $root.CommApiData.ApiType[message.apiType] : message.apiType + if (message.openapiData != null && message.hasOwnProperty('openapiData')) object.openapiData = $root.OpenApiData.toObject(message.openapiData, options) + if (message.innerData != null && message.hasOwnProperty('innerData')) object.innerData = $root.InnerApiData.toObject(message.innerData, options) + if (message.svrkitData != null && message.hasOwnProperty('svrkitData')) object.svrkitData = $root.SvrkitApiData.toObject(message.svrkitData, options) + if (message.tokenData != null && message.hasOwnProperty('tokenData')) object.tokenData = $root.TokenApiData.toObject(message.tokenData, options) + if (message.appid != null && message.hasOwnProperty('appid')) object.appid = message.appid + return object + } + + /** * Converts this CommApiData to JSON. * @function toJSON * @memberof CommApiData * @instance * @returns {Object.} JSON object */ - CommApiData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + CommApiData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - /** + /** * ApiType enum. * @name CommApiData.ApiType * @enum {string} @@ -1855,21 +1698,21 @@ $root.CommApiData = (function() { * @property {number} SVRKIT_API=2 SVRKIT_API value * @property {number} TOKEN_API=3 TOKEN_API value */ - CommApiData.ApiType = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "OPEN_API"] = 0; - values[valuesById[1] = "INNER_API"] = 1; - values[valuesById[2] = "SVRKIT_API"] = 2; - values[valuesById[3] = "TOKEN_API"] = 3; - return values; - })(); - - return CommApiData; -})(); + CommApiData.ApiType = (function () { + var valuesById = {}; var + values = Object.create(valuesById) + values[valuesById[0] = 'OPEN_API'] = 0 + values[valuesById[1] = 'INNER_API'] = 1 + values[valuesById[2] = 'SVRKIT_API'] = 2 + values[valuesById[3] = 'TOKEN_API'] = 3 + return values + }()) -$root.CommOpenApiResp = (function() { + return CommApiData + }()) - /** + $root.CommOpenApiResp = (function () { + /** * Properties of a CommOpenApiResp. * @exports ICommOpenApiResp * @interface ICommOpenApiResp @@ -1881,7 +1724,7 @@ $root.CommOpenApiResp = (function() { * @property {number|null} [svrkitErrorCode] CommOpenApiResp svrkitErrorCode */ - /** + /** * Constructs a new CommOpenApiResp. * @exports CommOpenApiResp * @classdesc Represents a CommOpenApiResp. @@ -1889,63 +1732,60 @@ $root.CommOpenApiResp = (function() { * @constructor * @param {ICommOpenApiResp=} [properties] Properties to set */ - function CommOpenApiResp(properties) { - this.headers = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function CommOpenApiResp(properties) { + this.headers = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * CommOpenApiResp respData. * @member {Uint8Array} respData * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.respData = $util.newBuffer([]); + CommOpenApiResp.prototype.respData = $util.newBuffer([]) - /** + /** * CommOpenApiResp contentType. * @member {string} contentType * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.contentType = ""; + CommOpenApiResp.prototype.contentType = '' - /** + /** * CommOpenApiResp errorCode. * @member {number} errorCode * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.errorCode = 0; + CommOpenApiResp.prototype.errorCode = 0 - /** + /** * CommOpenApiResp httpCode. * @member {number} httpCode * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.httpCode = 0; + CommOpenApiResp.prototype.httpCode = 0 - /** + /** * CommOpenApiResp headers. * @member {Array.} headers * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.headers = $util.emptyArray; + CommOpenApiResp.prototype.headers = $util.emptyArray - /** + /** * CommOpenApiResp svrkitErrorCode. * @member {number} svrkitErrorCode * @memberof CommOpenApiResp * @instance */ - CommOpenApiResp.prototype.svrkitErrorCode = 0; + CommOpenApiResp.prototype.svrkitErrorCode = 0 - /** + /** * Creates a new CommOpenApiResp instance using the specified properties. * @function create * @memberof CommOpenApiResp @@ -1953,11 +1793,11 @@ $root.CommOpenApiResp = (function() { * @param {ICommOpenApiResp=} [properties] Properties to set * @returns {CommOpenApiResp} CommOpenApiResp instance */ - CommOpenApiResp.create = function create(properties) { - return new CommOpenApiResp(properties); - }; + CommOpenApiResp.create = function create(properties) { + return new CommOpenApiResp(properties) + } - /** + /** * Encodes the specified CommOpenApiResp message. Does not implicitly {@link CommOpenApiResp.verify|verify} messages. * @function encode * @memberof CommOpenApiResp @@ -1966,26 +1806,18 @@ $root.CommOpenApiResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - CommOpenApiResp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.respData != null && message.hasOwnProperty("respData")) - writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.respData); - if (message.contentType != null && message.hasOwnProperty("contentType")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.contentType); - if (message.errorCode != null && message.hasOwnProperty("errorCode")) - writer.uint32(/* id 3, wireType 0 =*/24).int32(message.errorCode); - if (message.httpCode != null && message.hasOwnProperty("httpCode")) - writer.uint32(/* id 4, wireType 0 =*/32).uint32(message.httpCode); - if (message.headers != null && message.headers.length) - for (var i = 0; i < message.headers.length; ++i) - $root.HttpHeader.encode(message.headers[i], writer.uint32(/* id 5, wireType 2 =*/42).fork()).ldelim(); - if (message.svrkitErrorCode != null && message.hasOwnProperty("svrkitErrorCode")) - writer.uint32(/* id 6, wireType 0 =*/48).int32(message.svrkitErrorCode); - return writer; - }; - - /** + CommOpenApiResp.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.respData != null && message.hasOwnProperty('respData')) writer.uint32(/* id 1, wireType 2 = */10).bytes(message.respData) + if (message.contentType != null && message.hasOwnProperty('contentType')) writer.uint32(/* id 2, wireType 2 = */18).string(message.contentType) + if (message.errorCode != null && message.hasOwnProperty('errorCode')) writer.uint32(/* id 3, wireType 0 = */24).int32(message.errorCode) + if (message.httpCode != null && message.hasOwnProperty('httpCode')) writer.uint32(/* id 4, wireType 0 = */32).uint32(message.httpCode) + if (message.headers != null && message.headers.length) for (var i = 0; i < message.headers.length; ++i) $root.HttpHeader.encode(message.headers[i], writer.uint32(/* id 5, wireType 2 = */42).fork()).ldelim() + if (message.svrkitErrorCode != null && message.hasOwnProperty('svrkitErrorCode')) writer.uint32(/* id 6, wireType 0 = */48).int32(message.svrkitErrorCode) + return writer + } + + /** * Encodes the specified CommOpenApiResp message, length delimited. Does not implicitly {@link CommOpenApiResp.verify|verify} messages. * @function encodeDelimited * @memberof CommOpenApiResp @@ -1994,11 +1826,11 @@ $root.CommOpenApiResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - CommOpenApiResp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + CommOpenApiResp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a CommOpenApiResp message from the specified reader or buffer. * @function decode * @memberof CommOpenApiResp @@ -2009,42 +1841,41 @@ $root.CommOpenApiResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommOpenApiResp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.CommOpenApiResp(); - while (reader.pos < end) { - var tag = reader.uint32(); + CommOpenApiResp.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.CommOpenApiResp() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.respData = reader.bytes(); - break; - case 2: - message.contentType = reader.string(); - break; - case 3: - message.errorCode = reader.int32(); - break; - case 4: - message.httpCode = reader.uint32(); - break; - case 5: - if (!(message.headers && message.headers.length)) - message.headers = []; - message.headers.push($root.HttpHeader.decode(reader, reader.uint32())); - break; - case 6: - message.svrkitErrorCode = reader.int32(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.respData = reader.bytes() + break + case 2: + message.contentType = reader.string() + break + case 3: + message.errorCode = reader.int32() + break + case 4: + message.httpCode = reader.uint32() + break + case 5: + if (!(message.headers && message.headers.length)) message.headers = [] + message.headers.push($root.HttpHeader.decode(reader, reader.uint32())) + break + case 6: + message.svrkitErrorCode = reader.int32() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a CommOpenApiResp message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof CommOpenApiResp @@ -2054,13 +1885,12 @@ $root.CommOpenApiResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - CommOpenApiResp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + CommOpenApiResp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a CommOpenApiResp message. * @function verify * @memberof CommOpenApiResp @@ -2068,37 +1898,24 @@ $root.CommOpenApiResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - CommOpenApiResp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.respData != null && message.hasOwnProperty("respData")) - if (!(message.respData && typeof message.respData.length === "number" || $util.isString(message.respData))) - return "respData: buffer expected"; - if (message.contentType != null && message.hasOwnProperty("contentType")) - if (!$util.isString(message.contentType)) - return "contentType: string expected"; - if (message.errorCode != null && message.hasOwnProperty("errorCode")) - if (!$util.isInteger(message.errorCode)) - return "errorCode: integer expected"; - if (message.httpCode != null && message.hasOwnProperty("httpCode")) - if (!$util.isInteger(message.httpCode)) - return "httpCode: integer expected"; - if (message.headers != null && message.hasOwnProperty("headers")) { - if (!Array.isArray(message.headers)) - return "headers: array expected"; + CommOpenApiResp.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.respData != null && message.hasOwnProperty('respData')) if (!(message.respData && typeof message.respData.length === 'number' || $util.isString(message.respData))) return 'respData: buffer expected' + if (message.contentType != null && message.hasOwnProperty('contentType')) if (!$util.isString(message.contentType)) return 'contentType: string expected' + if (message.errorCode != null && message.hasOwnProperty('errorCode')) if (!$util.isInteger(message.errorCode)) return 'errorCode: integer expected' + if (message.httpCode != null && message.hasOwnProperty('httpCode')) if (!$util.isInteger(message.httpCode)) return 'httpCode: integer expected' + if (message.headers != null && message.hasOwnProperty('headers')) { + if (!Array.isArray(message.headers)) return 'headers: array expected' for (var i = 0; i < message.headers.length; ++i) { - var error = $root.HttpHeader.verify(message.headers[i]); - if (error) - return "headers." + error; + var error = $root.HttpHeader.verify(message.headers[i]) + if (error) return 'headers.' + error } + } + if (message.svrkitErrorCode != null && message.hasOwnProperty('svrkitErrorCode')) if (!$util.isInteger(message.svrkitErrorCode)) return 'svrkitErrorCode: integer expected' + return null } - if (message.svrkitErrorCode != null && message.hasOwnProperty("svrkitErrorCode")) - if (!$util.isInteger(message.svrkitErrorCode)) - return "svrkitErrorCode: integer expected"; - return null; - }; - /** + /** * Creates a CommOpenApiResp message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof CommOpenApiResp @@ -2106,37 +1923,29 @@ $root.CommOpenApiResp = (function() { * @param {Object.} object Plain object * @returns {CommOpenApiResp} CommOpenApiResp */ - CommOpenApiResp.fromObject = function fromObject(object) { - if (object instanceof $root.CommOpenApiResp) - return object; - var message = new $root.CommOpenApiResp(); - if (object.respData != null) - if (typeof object.respData === "string") - $util.base64.decode(object.respData, message.respData = $util.newBuffer($util.base64.length(object.respData)), 0); - else if (object.respData.length) - message.respData = object.respData; - if (object.contentType != null) - message.contentType = String(object.contentType); - if (object.errorCode != null) - message.errorCode = object.errorCode | 0; - if (object.httpCode != null) - message.httpCode = object.httpCode >>> 0; - if (object.headers) { - if (!Array.isArray(object.headers)) - throw TypeError(".CommOpenApiResp.headers: array expected"); - message.headers = []; + CommOpenApiResp.fromObject = function fromObject(object) { + if (object instanceof $root.CommOpenApiResp) return object + var message = new $root.CommOpenApiResp() + if (object.respData != null) { + if (typeof object.respData === 'string') $util.base64.decode(object.respData, message.respData = $util.newBuffer($util.base64.length(object.respData)), 0) + else if (object.respData.length) message.respData = object.respData + } + if (object.contentType != null) message.contentType = String(object.contentType) + if (object.errorCode != null) message.errorCode = object.errorCode | 0 + if (object.httpCode != null) message.httpCode = object.httpCode >>> 0 + if (object.headers) { + if (!Array.isArray(object.headers)) throw TypeError('.CommOpenApiResp.headers: array expected') + message.headers = [] for (var i = 0; i < object.headers.length; ++i) { - if (typeof object.headers[i] !== "object") - throw TypeError(".CommOpenApiResp.headers: object expected"); - message.headers[i] = $root.HttpHeader.fromObject(object.headers[i]); + if (typeof object.headers[i] !== 'object') throw TypeError('.CommOpenApiResp.headers: object expected') + message.headers[i] = $root.HttpHeader.fromObject(object.headers[i]) } + } + if (object.svrkitErrorCode != null) message.svrkitErrorCode = object.svrkitErrorCode | 0 + return message } - if (object.svrkitErrorCode != null) - message.svrkitErrorCode = object.svrkitErrorCode | 0; - return message; - }; - /** + /** * Creates a plain object from a CommOpenApiResp message. Also converts values to other types if specified. * @function toObject * @memberof CommOpenApiResp @@ -2145,60 +1954,49 @@ $root.CommOpenApiResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - CommOpenApiResp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.headers = []; - if (options.defaults) { - if (options.bytes === String) - object.respData = ""; + CommOpenApiResp.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.headers = [] + if (options.defaults) { + if (options.bytes === String) object.respData = '' else { - object.respData = []; - if (options.bytes !== Array) - object.respData = $util.newBuffer(object.respData); + object.respData = [] + if (options.bytes !== Array) object.respData = $util.newBuffer(object.respData) } - object.contentType = ""; - object.errorCode = 0; - object.httpCode = 0; - object.svrkitErrorCode = 0; - } - if (message.respData != null && message.hasOwnProperty("respData")) - object.respData = options.bytes === String ? $util.base64.encode(message.respData, 0, message.respData.length) : options.bytes === Array ? Array.prototype.slice.call(message.respData) : message.respData; - if (message.contentType != null && message.hasOwnProperty("contentType")) - object.contentType = message.contentType; - if (message.errorCode != null && message.hasOwnProperty("errorCode")) - object.errorCode = message.errorCode; - if (message.httpCode != null && message.hasOwnProperty("httpCode")) - object.httpCode = message.httpCode; - if (message.headers && message.headers.length) { - object.headers = []; - for (var j = 0; j < message.headers.length; ++j) - object.headers[j] = $root.HttpHeader.toObject(message.headers[j], options); - } - if (message.svrkitErrorCode != null && message.hasOwnProperty("svrkitErrorCode")) - object.svrkitErrorCode = message.svrkitErrorCode; - return object; - }; - - /** + object.contentType = '' + object.errorCode = 0 + object.httpCode = 0 + object.svrkitErrorCode = 0 + } + if (message.respData != null && message.hasOwnProperty('respData')) object.respData = options.bytes === String ? $util.base64.encode(message.respData, 0, message.respData.length) : options.bytes === Array ? Array.prototype.slice.call(message.respData) : message.respData + if (message.contentType != null && message.hasOwnProperty('contentType')) object.contentType = message.contentType + if (message.errorCode != null && message.hasOwnProperty('errorCode')) object.errorCode = message.errorCode + if (message.httpCode != null && message.hasOwnProperty('httpCode')) object.httpCode = message.httpCode + if (message.headers && message.headers.length) { + object.headers = [] + for (var j = 0; j < message.headers.length; ++j) object.headers[j] = $root.HttpHeader.toObject(message.headers[j], options) + } + if (message.svrkitErrorCode != null && message.hasOwnProperty('svrkitErrorCode')) object.svrkitErrorCode = message.svrkitErrorCode + return object + } + + /** * Converts this CommOpenApiResp to JSON. * @function toJSON * @memberof CommOpenApiResp * @instance * @returns {Object.} JSON object */ - CommOpenApiResp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return CommOpenApiResp; -})(); + CommOpenApiResp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.InnerApiData = (function() { + return CommOpenApiResp + }()) - /** + $root.InnerApiData = (function () { + /** * Properties of an InnerApiData. * @exports IInnerApiData * @interface IInnerApiData @@ -2211,7 +2009,7 @@ $root.InnerApiData = (function() { * @property {Uint8Array|null} [body] InnerApiData body */ - /** + /** * Constructs a new InnerApiData. * @exports InnerApiData * @classdesc Represents an InnerApiData. @@ -2219,71 +2017,68 @@ $root.InnerApiData = (function() { * @constructor * @param {IInnerApiData=} [properties] Properties to set */ - function InnerApiData(properties) { - this.headers = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function InnerApiData(properties) { + this.headers = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * InnerApiData modid. * @member {number} modid * @memberof InnerApiData * @instance */ - InnerApiData.prototype.modid = 0; + InnerApiData.prototype.modid = 0 - /** + /** * InnerApiData cmdid. * @member {number} cmdid * @memberof InnerApiData * @instance */ - InnerApiData.prototype.cmdid = 0; + InnerApiData.prototype.cmdid = 0 - /** + /** * InnerApiData url. * @member {string} url * @memberof InnerApiData * @instance */ - InnerApiData.prototype.url = ""; + InnerApiData.prototype.url = '' - /** + /** * InnerApiData useHttps. * @member {boolean} useHttps * @memberof InnerApiData * @instance */ - InnerApiData.prototype.useHttps = false; + InnerApiData.prototype.useHttps = false - /** + /** * InnerApiData method. * @member {HTTP_METHODS} method * @memberof InnerApiData * @instance */ - InnerApiData.prototype.method = 1; + InnerApiData.prototype.method = 1 - /** + /** * InnerApiData headers. * @member {Array.} headers * @memberof InnerApiData * @instance */ - InnerApiData.prototype.headers = $util.emptyArray; + InnerApiData.prototype.headers = $util.emptyArray - /** + /** * InnerApiData body. * @member {Uint8Array} body * @memberof InnerApiData * @instance */ - InnerApiData.prototype.body = $util.newBuffer([]); + InnerApiData.prototype.body = $util.newBuffer([]) - /** + /** * Creates a new InnerApiData instance using the specified properties. * @function create * @memberof InnerApiData @@ -2291,11 +2086,11 @@ $root.InnerApiData = (function() { * @param {IInnerApiData=} [properties] Properties to set * @returns {InnerApiData} InnerApiData instance */ - InnerApiData.create = function create(properties) { - return new InnerApiData(properties); - }; + InnerApiData.create = function create(properties) { + return new InnerApiData(properties) + } - /** + /** * Encodes the specified InnerApiData message. Does not implicitly {@link InnerApiData.verify|verify} messages. * @function encode * @memberof InnerApiData @@ -2304,28 +2099,19 @@ $root.InnerApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InnerApiData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.modid != null && message.hasOwnProperty("modid")) - writer.uint32(/* id 1, wireType 0 =*/8).uint32(message.modid); - if (message.cmdid != null && message.hasOwnProperty("cmdid")) - writer.uint32(/* id 2, wireType 0 =*/16).uint32(message.cmdid); - if (message.url != null && message.hasOwnProperty("url")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.url); - if (message.useHttps != null && message.hasOwnProperty("useHttps")) - writer.uint32(/* id 4, wireType 0 =*/32).bool(message.useHttps); - if (message.method != null && message.hasOwnProperty("method")) - writer.uint32(/* id 5, wireType 0 =*/40).int32(message.method); - if (message.headers != null && message.headers.length) - for (var i = 0; i < message.headers.length; ++i) - writer.uint32(/* id 6, wireType 2 =*/50).string(message.headers[i]); - if (message.body != null && message.hasOwnProperty("body")) - writer.uint32(/* id 7, wireType 2 =*/58).bytes(message.body); - return writer; - }; - - /** + InnerApiData.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.modid != null && message.hasOwnProperty('modid')) writer.uint32(/* id 1, wireType 0 = */8).uint32(message.modid) + if (message.cmdid != null && message.hasOwnProperty('cmdid')) writer.uint32(/* id 2, wireType 0 = */16).uint32(message.cmdid) + if (message.url != null && message.hasOwnProperty('url')) writer.uint32(/* id 3, wireType 2 = */26).string(message.url) + if (message.useHttps != null && message.hasOwnProperty('useHttps')) writer.uint32(/* id 4, wireType 0 = */32).bool(message.useHttps) + if (message.method != null && message.hasOwnProperty('method')) writer.uint32(/* id 5, wireType 0 = */40).int32(message.method) + if (message.headers != null && message.headers.length) for (var i = 0; i < message.headers.length; ++i) writer.uint32(/* id 6, wireType 2 = */50).string(message.headers[i]) + if (message.body != null && message.hasOwnProperty('body')) writer.uint32(/* id 7, wireType 2 = */58).bytes(message.body) + return writer + } + + /** * Encodes the specified InnerApiData message, length delimited. Does not implicitly {@link InnerApiData.verify|verify} messages. * @function encodeDelimited * @memberof InnerApiData @@ -2334,11 +2120,11 @@ $root.InnerApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - InnerApiData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + InnerApiData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an InnerApiData message from the specified reader or buffer. * @function decode * @memberof InnerApiData @@ -2349,45 +2135,44 @@ $root.InnerApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - InnerApiData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.InnerApiData(); - while (reader.pos < end) { - var tag = reader.uint32(); + InnerApiData.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.InnerApiData() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.modid = reader.uint32(); - break; - case 2: - message.cmdid = reader.uint32(); - break; - case 3: - message.url = reader.string(); - break; - case 4: - message.useHttps = reader.bool(); - break; - case 5: - message.method = reader.int32(); - break; - case 6: - if (!(message.headers && message.headers.length)) - message.headers = []; - message.headers.push(reader.string()); - break; - case 7: - message.body = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.modid = reader.uint32() + break + case 2: + message.cmdid = reader.uint32() + break + case 3: + message.url = reader.string() + break + case 4: + message.useHttps = reader.bool() + break + case 5: + message.method = reader.int32() + break + case 6: + if (!(message.headers && message.headers.length)) message.headers = [] + message.headers.push(reader.string()) + break + case 7: + message.body = reader.bytes() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an InnerApiData message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof InnerApiData @@ -2397,13 +2182,12 @@ $root.InnerApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - InnerApiData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + InnerApiData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an InnerApiData message. * @function verify * @memberof InnerApiData @@ -2411,47 +2195,34 @@ $root.InnerApiData = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - InnerApiData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.modid != null && message.hasOwnProperty("modid")) - if (!$util.isInteger(message.modid)) - return "modid: integer expected"; - if (message.cmdid != null && message.hasOwnProperty("cmdid")) - if (!$util.isInteger(message.cmdid)) - return "cmdid: integer expected"; - if (message.url != null && message.hasOwnProperty("url")) - if (!$util.isString(message.url)) - return "url: string expected"; - if (message.useHttps != null && message.hasOwnProperty("useHttps")) - if (typeof message.useHttps !== "boolean") - return "useHttps: boolean expected"; - if (message.method != null && message.hasOwnProperty("method")) + InnerApiData.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.modid != null && message.hasOwnProperty('modid')) if (!$util.isInteger(message.modid)) return 'modid: integer expected' + if (message.cmdid != null && message.hasOwnProperty('cmdid')) if (!$util.isInteger(message.cmdid)) return 'cmdid: integer expected' + if (message.url != null && message.hasOwnProperty('url')) if (!$util.isString(message.url)) return 'url: string expected' + if (message.useHttps != null && message.hasOwnProperty('useHttps')) if (typeof message.useHttps !== 'boolean') return 'useHttps: boolean expected' + if (message.method != null && message.hasOwnProperty('method')) { switch (message.method) { - default: - return "method: enum value expected"; - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - break; + default: + return 'method: enum value expected' + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + break } - if (message.headers != null && message.hasOwnProperty("headers")) { - if (!Array.isArray(message.headers)) - return "headers: array expected"; - for (var i = 0; i < message.headers.length; ++i) - if (!$util.isString(message.headers[i])) - return "headers: string[] expected"; - } - if (message.body != null && message.hasOwnProperty("body")) - if (!(message.body && typeof message.body.length === "number" || $util.isString(message.body))) - return "body: buffer expected"; - return null; - }; - - /** + } + if (message.headers != null && message.hasOwnProperty('headers')) { + if (!Array.isArray(message.headers)) return 'headers: array expected' + for (var i = 0; i < message.headers.length; ++i) if (!$util.isString(message.headers[i])) return 'headers: string[] expected' + } + if (message.body != null && message.hasOwnProperty('body')) if (!(message.body && typeof message.body.length === 'number' || $util.isString(message.body))) return 'body: buffer expected' + return null + } + + /** * Creates an InnerApiData message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof InnerApiData @@ -2459,60 +2230,52 @@ $root.InnerApiData = (function() { * @param {Object.} object Plain object * @returns {InnerApiData} InnerApiData */ - InnerApiData.fromObject = function fromObject(object) { - if (object instanceof $root.InnerApiData) - return object; - var message = new $root.InnerApiData(); - if (object.modid != null) - message.modid = object.modid >>> 0; - if (object.cmdid != null) - message.cmdid = object.cmdid >>> 0; - if (object.url != null) - message.url = String(object.url); - if (object.useHttps != null) - message.useHttps = Boolean(object.useHttps); - switch (object.method) { - case "HTTP_GET": - case 1: - message.method = 1; - break; - case "HTTP_POST": - case 2: - message.method = 2; - break; - case "HTTP_PUT": - case 3: - message.method = 3; - break; - case "HTTP_DELETE": - case 4: - message.method = 4; - break; - case "HTTP_HEAD": - case 5: - message.method = 5; - break; - case "HTTP_PATCH": - case 6: - message.method = 6; - break; - } - if (object.headers) { - if (!Array.isArray(object.headers)) - throw TypeError(".InnerApiData.headers: array expected"); - message.headers = []; - for (var i = 0; i < object.headers.length; ++i) - message.headers[i] = String(object.headers[i]); - } - if (object.body != null) - if (typeof object.body === "string") - $util.base64.decode(object.body, message.body = $util.newBuffer($util.base64.length(object.body)), 0); - else if (object.body.length) - message.body = object.body; - return message; - }; - - /** + InnerApiData.fromObject = function fromObject(object) { + if (object instanceof $root.InnerApiData) return object + var message = new $root.InnerApiData() + if (object.modid != null) message.modid = object.modid >>> 0 + if (object.cmdid != null) message.cmdid = object.cmdid >>> 0 + if (object.url != null) message.url = String(object.url) + if (object.useHttps != null) message.useHttps = Boolean(object.useHttps) + switch (object.method) { + case 'HTTP_GET': + case 1: + message.method = 1 + break + case 'HTTP_POST': + case 2: + message.method = 2 + break + case 'HTTP_PUT': + case 3: + message.method = 3 + break + case 'HTTP_DELETE': + case 4: + message.method = 4 + break + case 'HTTP_HEAD': + case 5: + message.method = 5 + break + case 'HTTP_PATCH': + case 6: + message.method = 6 + break + } + if (object.headers) { + if (!Array.isArray(object.headers)) throw TypeError('.InnerApiData.headers: array expected') + message.headers = [] + for (var i = 0; i < object.headers.length; ++i) message.headers[i] = String(object.headers[i]) + } + if (object.body != null) { + if (typeof object.body === 'string') $util.base64.decode(object.body, message.body = $util.newBuffer($util.base64.length(object.body)), 0) + else if (object.body.length) message.body = object.body + } + return message + } + + /** * Creates a plain object from an InnerApiData message. Also converts values to other types if specified. * @function toObject * @memberof InnerApiData @@ -2521,63 +2284,51 @@ $root.InnerApiData = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - InnerApiData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.headers = []; - if (options.defaults) { - object.modid = 0; - object.cmdid = 0; - object.url = ""; - object.useHttps = false; - object.method = options.enums === String ? "HTTP_GET" : 1; - if (options.bytes === String) - object.body = ""; + InnerApiData.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.headers = [] + if (options.defaults) { + object.modid = 0 + object.cmdid = 0 + object.url = '' + object.useHttps = false + object.method = options.enums === String ? 'HTTP_GET' : 1 + if (options.bytes === String) object.body = '' else { - object.body = []; - if (options.bytes !== Array) - object.body = $util.newBuffer(object.body); + object.body = [] + if (options.bytes !== Array) object.body = $util.newBuffer(object.body) } + } + if (message.modid != null && message.hasOwnProperty('modid')) object.modid = message.modid + if (message.cmdid != null && message.hasOwnProperty('cmdid')) object.cmdid = message.cmdid + if (message.url != null && message.hasOwnProperty('url')) object.url = message.url + if (message.useHttps != null && message.hasOwnProperty('useHttps')) object.useHttps = message.useHttps + if (message.method != null && message.hasOwnProperty('method')) object.method = options.enums === String ? $root.HTTP_METHODS[message.method] : message.method + if (message.headers && message.headers.length) { + object.headers = [] + for (var j = 0; j < message.headers.length; ++j) object.headers[j] = message.headers[j] + } + if (message.body != null && message.hasOwnProperty('body')) object.body = options.bytes === String ? $util.base64.encode(message.body, 0, message.body.length) : options.bytes === Array ? Array.prototype.slice.call(message.body) : message.body + return object } - if (message.modid != null && message.hasOwnProperty("modid")) - object.modid = message.modid; - if (message.cmdid != null && message.hasOwnProperty("cmdid")) - object.cmdid = message.cmdid; - if (message.url != null && message.hasOwnProperty("url")) - object.url = message.url; - if (message.useHttps != null && message.hasOwnProperty("useHttps")) - object.useHttps = message.useHttps; - if (message.method != null && message.hasOwnProperty("method")) - object.method = options.enums === String ? $root.HTTP_METHODS[message.method] : message.method; - if (message.headers && message.headers.length) { - object.headers = []; - for (var j = 0; j < message.headers.length; ++j) - object.headers[j] = message.headers[j]; - } - if (message.body != null && message.hasOwnProperty("body")) - object.body = options.bytes === String ? $util.base64.encode(message.body, 0, message.body.length) : options.bytes === Array ? Array.prototype.slice.call(message.body) : message.body; - return object; - }; - - /** + + /** * Converts this InnerApiData to JSON. * @function toJSON * @memberof InnerApiData * @instance * @returns {Object.} JSON object */ - InnerApiData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return InnerApiData; -})(); + InnerApiData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.SvrkitApiData = (function() { + return InnerApiData + }()) - /** + $root.SvrkitApiData = (function () { + /** * Properties of a SvrkitApiData. * @exports ISvrkitApiData * @interface ISvrkitApiData @@ -2585,7 +2336,7 @@ $root.SvrkitApiData = (function() { * @property {Uint8Array|null} [reqData] SvrkitApiData reqData */ - /** + /** * Constructs a new SvrkitApiData. * @exports SvrkitApiData * @classdesc Represents a SvrkitApiData. @@ -2593,30 +2344,27 @@ $root.SvrkitApiData = (function() { * @constructor * @param {ISvrkitApiData=} [properties] Properties to set */ - function SvrkitApiData(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function SvrkitApiData(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * SvrkitApiData apiName. * @member {string} apiName * @memberof SvrkitApiData * @instance */ - SvrkitApiData.prototype.apiName = ""; + SvrkitApiData.prototype.apiName = '' - /** + /** * SvrkitApiData reqData. * @member {Uint8Array} reqData * @memberof SvrkitApiData * @instance */ - SvrkitApiData.prototype.reqData = $util.newBuffer([]); + SvrkitApiData.prototype.reqData = $util.newBuffer([]) - /** + /** * Creates a new SvrkitApiData instance using the specified properties. * @function create * @memberof SvrkitApiData @@ -2624,11 +2372,11 @@ $root.SvrkitApiData = (function() { * @param {ISvrkitApiData=} [properties] Properties to set * @returns {SvrkitApiData} SvrkitApiData instance */ - SvrkitApiData.create = function create(properties) { - return new SvrkitApiData(properties); - }; + SvrkitApiData.create = function create(properties) { + return new SvrkitApiData(properties) + } - /** + /** * Encodes the specified SvrkitApiData message. Does not implicitly {@link SvrkitApiData.verify|verify} messages. * @function encode * @memberof SvrkitApiData @@ -2637,17 +2385,14 @@ $root.SvrkitApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SvrkitApiData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.apiName != null && message.hasOwnProperty("apiName")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.apiName); - if (message.reqData != null && message.hasOwnProperty("reqData")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.reqData); - return writer; - }; - - /** + SvrkitApiData.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.apiName != null && message.hasOwnProperty('apiName')) writer.uint32(/* id 1, wireType 2 = */10).string(message.apiName) + if (message.reqData != null && message.hasOwnProperty('reqData')) writer.uint32(/* id 2, wireType 2 = */18).bytes(message.reqData) + return writer + } + + /** * Encodes the specified SvrkitApiData message, length delimited. Does not implicitly {@link SvrkitApiData.verify|verify} messages. * @function encodeDelimited * @memberof SvrkitApiData @@ -2656,11 +2401,11 @@ $root.SvrkitApiData = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - SvrkitApiData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + SvrkitApiData.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a SvrkitApiData message from the specified reader or buffer. * @function decode * @memberof SvrkitApiData @@ -2671,28 +2416,28 @@ $root.SvrkitApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SvrkitApiData.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.SvrkitApiData(); - while (reader.pos < end) { - var tag = reader.uint32(); + SvrkitApiData.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.SvrkitApiData() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.apiName = reader.string(); - break; - case 2: - message.reqData = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.apiName = reader.string() + break + case 2: + message.reqData = reader.bytes() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a SvrkitApiData message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof SvrkitApiData @@ -2702,13 +2447,12 @@ $root.SvrkitApiData = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - SvrkitApiData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + SvrkitApiData.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a SvrkitApiData message. * @function verify * @memberof SvrkitApiData @@ -2716,19 +2460,14 @@ $root.SvrkitApiData = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - SvrkitApiData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.apiName != null && message.hasOwnProperty("apiName")) - if (!$util.isString(message.apiName)) - return "apiName: string expected"; - if (message.reqData != null && message.hasOwnProperty("reqData")) - if (!(message.reqData && typeof message.reqData.length === "number" || $util.isString(message.reqData))) - return "reqData: buffer expected"; - return null; - }; - - /** + SvrkitApiData.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.apiName != null && message.hasOwnProperty('apiName')) if (!$util.isString(message.apiName)) return 'apiName: string expected' + if (message.reqData != null && message.hasOwnProperty('reqData')) if (!(message.reqData && typeof message.reqData.length === 'number' || $util.isString(message.reqData))) return 'reqData: buffer expected' + return null + } + + /** * Creates a SvrkitApiData message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof SvrkitApiData @@ -2736,21 +2475,18 @@ $root.SvrkitApiData = (function() { * @param {Object.} object Plain object * @returns {SvrkitApiData} SvrkitApiData */ - SvrkitApiData.fromObject = function fromObject(object) { - if (object instanceof $root.SvrkitApiData) - return object; - var message = new $root.SvrkitApiData(); - if (object.apiName != null) - message.apiName = String(object.apiName); - if (object.reqData != null) - if (typeof object.reqData === "string") - $util.base64.decode(object.reqData, message.reqData = $util.newBuffer($util.base64.length(object.reqData)), 0); - else if (object.reqData.length) - message.reqData = object.reqData; - return message; - }; - - /** + SvrkitApiData.fromObject = function fromObject(object) { + if (object instanceof $root.SvrkitApiData) return object + var message = new $root.SvrkitApiData() + if (object.apiName != null) message.apiName = String(object.apiName) + if (object.reqData != null) { + if (typeof object.reqData === 'string') $util.base64.decode(object.reqData, message.reqData = $util.newBuffer($util.base64.length(object.reqData)), 0) + else if (object.reqData.length) message.reqData = object.reqData + } + return message + } + + /** * Creates a plain object from a SvrkitApiData message. Also converts values to other types if specified. * @function toObject * @memberof SvrkitApiData @@ -2759,42 +2495,37 @@ $root.SvrkitApiData = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - SvrkitApiData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.apiName = ""; - if (options.bytes === String) - object.reqData = ""; + SvrkitApiData.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.apiName = '' + if (options.bytes === String) object.reqData = '' else { - object.reqData = []; - if (options.bytes !== Array) - object.reqData = $util.newBuffer(object.reqData); + object.reqData = [] + if (options.bytes !== Array) object.reqData = $util.newBuffer(object.reqData) } + } + if (message.apiName != null && message.hasOwnProperty('apiName')) object.apiName = message.apiName + if (message.reqData != null && message.hasOwnProperty('reqData')) object.reqData = options.bytes === String ? $util.base64.encode(message.reqData, 0, message.reqData.length) : options.bytes === Array ? Array.prototype.slice.call(message.reqData) : message.reqData + return object } - if (message.apiName != null && message.hasOwnProperty("apiName")) - object.apiName = message.apiName; - if (message.reqData != null && message.hasOwnProperty("reqData")) - object.reqData = options.bytes === String ? $util.base64.encode(message.reqData, 0, message.reqData.length) : options.bytes === Array ? Array.prototype.slice.call(message.reqData) : message.reqData; - return object; - }; - /** + /** * Converts this SvrkitApiData to JSON. * @function toJSON * @memberof SvrkitApiData * @instance * @returns {Object.} JSON object */ - SvrkitApiData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + SvrkitApiData.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - return SvrkitApiData; -})(); + return SvrkitApiData + }()) -/** + /** * HTTP_METHODS enum. * @exports HTTP_METHODS * @enum {string} @@ -2805,20 +2536,20 @@ $root.SvrkitApiData = (function() { * @property {number} HTTP_HEAD=5 HTTP_HEAD value * @property {number} HTTP_PATCH=6 HTTP_PATCH value */ -$root.HTTP_METHODS = (function() { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[1] = "HTTP_GET"] = 1; - values[valuesById[2] = "HTTP_POST"] = 2; - values[valuesById[3] = "HTTP_PUT"] = 3; - values[valuesById[4] = "HTTP_DELETE"] = 4; - values[valuesById[5] = "HTTP_HEAD"] = 5; - values[valuesById[6] = "HTTP_PATCH"] = 6; - return values; -})(); - -$root.HttpHeader = (function() { - - /** + $root.HTTP_METHODS = (function () { + var valuesById = {}; var + values = Object.create(valuesById) + values[valuesById[1] = 'HTTP_GET'] = 1 + values[valuesById[2] = 'HTTP_POST'] = 2 + values[valuesById[3] = 'HTTP_PUT'] = 3 + values[valuesById[4] = 'HTTP_DELETE'] = 4 + values[valuesById[5] = 'HTTP_HEAD'] = 5 + values[valuesById[6] = 'HTTP_PATCH'] = 6 + return values + }()) + + $root.HttpHeader = (function () { + /** * Properties of a HttpHeader. * @exports IHttpHeader * @interface IHttpHeader @@ -2826,7 +2557,7 @@ $root.HttpHeader = (function() { * @property {string|null} [value] HttpHeader value */ - /** + /** * Constructs a new HttpHeader. * @exports HttpHeader * @classdesc Represents a HttpHeader. @@ -2834,30 +2565,27 @@ $root.HttpHeader = (function() { * @constructor * @param {IHttpHeader=} [properties] Properties to set */ - function HttpHeader(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function HttpHeader(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * HttpHeader key. * @member {string} key * @memberof HttpHeader * @instance */ - HttpHeader.prototype.key = ""; + HttpHeader.prototype.key = '' - /** + /** * HttpHeader value. * @member {string} value * @memberof HttpHeader * @instance */ - HttpHeader.prototype.value = ""; + HttpHeader.prototype.value = '' - /** + /** * Creates a new HttpHeader instance using the specified properties. * @function create * @memberof HttpHeader @@ -2865,11 +2593,11 @@ $root.HttpHeader = (function() { * @param {IHttpHeader=} [properties] Properties to set * @returns {HttpHeader} HttpHeader instance */ - HttpHeader.create = function create(properties) { - return new HttpHeader(properties); - }; + HttpHeader.create = function create(properties) { + return new HttpHeader(properties) + } - /** + /** * Encodes the specified HttpHeader message. Does not implicitly {@link HttpHeader.verify|verify} messages. * @function encode * @memberof HttpHeader @@ -2878,17 +2606,14 @@ $root.HttpHeader = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - HttpHeader.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.key != null && message.hasOwnProperty("key")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.key); - if (message.value != null && message.hasOwnProperty("value")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.value); - return writer; - }; - - /** + HttpHeader.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.key != null && message.hasOwnProperty('key')) writer.uint32(/* id 1, wireType 2 = */10).string(message.key) + if (message.value != null && message.hasOwnProperty('value')) writer.uint32(/* id 2, wireType 2 = */18).string(message.value) + return writer + } + + /** * Encodes the specified HttpHeader message, length delimited. Does not implicitly {@link HttpHeader.verify|verify} messages. * @function encodeDelimited * @memberof HttpHeader @@ -2897,11 +2622,11 @@ $root.HttpHeader = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - HttpHeader.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + HttpHeader.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a HttpHeader message from the specified reader or buffer. * @function decode * @memberof HttpHeader @@ -2912,28 +2637,28 @@ $root.HttpHeader = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - HttpHeader.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.HttpHeader(); - while (reader.pos < end) { - var tag = reader.uint32(); + HttpHeader.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.HttpHeader() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.key = reader.string(); - break; - case 2: - message.value = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.key = reader.string() + break + case 2: + message.value = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a HttpHeader message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof HttpHeader @@ -2943,13 +2668,12 @@ $root.HttpHeader = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - HttpHeader.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + HttpHeader.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a HttpHeader message. * @function verify * @memberof HttpHeader @@ -2957,19 +2681,14 @@ $root.HttpHeader = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - HttpHeader.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.key != null && message.hasOwnProperty("key")) - if (!$util.isString(message.key)) - return "key: string expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (!$util.isString(message.value)) - return "value: string expected"; - return null; - }; - - /** + HttpHeader.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.key != null && message.hasOwnProperty('key')) if (!$util.isString(message.key)) return 'key: string expected' + if (message.value != null && message.hasOwnProperty('value')) if (!$util.isString(message.value)) return 'value: string expected' + return null + } + + /** * Creates a HttpHeader message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof HttpHeader @@ -2977,18 +2696,15 @@ $root.HttpHeader = (function() { * @param {Object.} object Plain object * @returns {HttpHeader} HttpHeader */ - HttpHeader.fromObject = function fromObject(object) { - if (object instanceof $root.HttpHeader) - return object; - var message = new $root.HttpHeader(); - if (object.key != null) - message.key = String(object.key); - if (object.value != null) - message.value = String(object.value); - return message; - }; - - /** + HttpHeader.fromObject = function fromObject(object) { + if (object instanceof $root.HttpHeader) return object + var message = new $root.HttpHeader() + if (object.key != null) message.key = String(object.key) + if (object.value != null) message.value = String(object.value) + return message + } + + /** * Creates a plain object from a HttpHeader message. Also converts values to other types if specified. * @function toObject * @memberof HttpHeader @@ -2997,45 +2713,41 @@ $root.HttpHeader = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - HttpHeader.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.key = ""; - object.value = ""; - } - if (message.key != null && message.hasOwnProperty("key")) - object.key = message.key; - if (message.value != null && message.hasOwnProperty("value")) - object.value = message.value; - return object; - }; - - /** + HttpHeader.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.key = '' + object.value = '' + } + if (message.key != null && message.hasOwnProperty('key')) object.key = message.key + if (message.value != null && message.hasOwnProperty('value')) object.value = message.value + return object + } + + /** * Converts this HttpHeader to JSON. * @function toJSON * @memberof HttpHeader * @instance * @returns {Object.} JSON object */ - HttpHeader.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return HttpHeader; -})(); + HttpHeader.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.ApiGetOpenDataByCloudIdReq = (function() { + return HttpHeader + }()) - /** + $root.ApiGetOpenDataByCloudIdReq = (function () { + /** * Properties of an ApiGetOpenDataByCloudIdReq. * @exports IApiGetOpenDataByCloudIdReq * @interface IApiGetOpenDataByCloudIdReq * @property {Array.|null} [cloudidList] ApiGetOpenDataByCloudIdReq cloudidList */ - /** + /** * Constructs a new ApiGetOpenDataByCloudIdReq. * @exports ApiGetOpenDataByCloudIdReq * @classdesc Represents an ApiGetOpenDataByCloudIdReq. @@ -3043,23 +2755,20 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @constructor * @param {IApiGetOpenDataByCloudIdReq=} [properties] Properties to set */ - function ApiGetOpenDataByCloudIdReq(properties) { - this.cloudidList = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function ApiGetOpenDataByCloudIdReq(properties) { + this.cloudidList = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * ApiGetOpenDataByCloudIdReq cloudidList. * @member {Array.} cloudidList * @memberof ApiGetOpenDataByCloudIdReq * @instance */ - ApiGetOpenDataByCloudIdReq.prototype.cloudidList = $util.emptyArray; + ApiGetOpenDataByCloudIdReq.prototype.cloudidList = $util.emptyArray - /** + /** * Creates a new ApiGetOpenDataByCloudIdReq instance using the specified properties. * @function create * @memberof ApiGetOpenDataByCloudIdReq @@ -3067,11 +2776,11 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {IApiGetOpenDataByCloudIdReq=} [properties] Properties to set * @returns {ApiGetOpenDataByCloudIdReq} ApiGetOpenDataByCloudIdReq instance */ - ApiGetOpenDataByCloudIdReq.create = function create(properties) { - return new ApiGetOpenDataByCloudIdReq(properties); - }; + ApiGetOpenDataByCloudIdReq.create = function create(properties) { + return new ApiGetOpenDataByCloudIdReq(properties) + } - /** + /** * Encodes the specified ApiGetOpenDataByCloudIdReq message. Does not implicitly {@link ApiGetOpenDataByCloudIdReq.verify|verify} messages. * @function encode * @memberof ApiGetOpenDataByCloudIdReq @@ -3080,16 +2789,13 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiGetOpenDataByCloudIdReq.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cloudidList != null && message.cloudidList.length) - for (var i = 0; i < message.cloudidList.length; ++i) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.cloudidList[i]); - return writer; - }; + ApiGetOpenDataByCloudIdReq.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.cloudidList != null && message.cloudidList.length) for (var i = 0; i < message.cloudidList.length; ++i) writer.uint32(/* id 2, wireType 2 = */18).string(message.cloudidList[i]) + return writer + } - /** + /** * Encodes the specified ApiGetOpenDataByCloudIdReq message, length delimited. Does not implicitly {@link ApiGetOpenDataByCloudIdReq.verify|verify} messages. * @function encodeDelimited * @memberof ApiGetOpenDataByCloudIdReq @@ -3098,11 +2804,11 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiGetOpenDataByCloudIdReq.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + ApiGetOpenDataByCloudIdReq.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an ApiGetOpenDataByCloudIdReq message from the specified reader or buffer. * @function decode * @memberof ApiGetOpenDataByCloudIdReq @@ -3113,27 +2819,26 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiGetOpenDataByCloudIdReq.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiGetOpenDataByCloudIdReq(); - while (reader.pos < end) { - var tag = reader.uint32(); + ApiGetOpenDataByCloudIdReq.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiGetOpenDataByCloudIdReq() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 2: - if (!(message.cloudidList && message.cloudidList.length)) - message.cloudidList = []; - message.cloudidList.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; + case 2: + if (!(message.cloudidList && message.cloudidList.length)) message.cloudidList = [] + message.cloudidList.push(reader.string()) + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an ApiGetOpenDataByCloudIdReq message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiGetOpenDataByCloudIdReq @@ -3143,13 +2848,12 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiGetOpenDataByCloudIdReq.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + ApiGetOpenDataByCloudIdReq.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an ApiGetOpenDataByCloudIdReq message. * @function verify * @memberof ApiGetOpenDataByCloudIdReq @@ -3157,20 +2861,16 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ApiGetOpenDataByCloudIdReq.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.cloudidList != null && message.hasOwnProperty("cloudidList")) { - if (!Array.isArray(message.cloudidList)) - return "cloudidList: array expected"; - for (var i = 0; i < message.cloudidList.length; ++i) - if (!$util.isString(message.cloudidList[i])) - return "cloudidList: string[] expected"; + ApiGetOpenDataByCloudIdReq.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.cloudidList != null && message.hasOwnProperty('cloudidList')) { + if (!Array.isArray(message.cloudidList)) return 'cloudidList: array expected' + for (var i = 0; i < message.cloudidList.length; ++i) if (!$util.isString(message.cloudidList[i])) return 'cloudidList: string[] expected' + } + return null } - return null; - }; - /** + /** * Creates an ApiGetOpenDataByCloudIdReq message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiGetOpenDataByCloudIdReq @@ -3178,21 +2878,18 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {Object.} object Plain object * @returns {ApiGetOpenDataByCloudIdReq} ApiGetOpenDataByCloudIdReq */ - ApiGetOpenDataByCloudIdReq.fromObject = function fromObject(object) { - if (object instanceof $root.ApiGetOpenDataByCloudIdReq) - return object; - var message = new $root.ApiGetOpenDataByCloudIdReq(); - if (object.cloudidList) { - if (!Array.isArray(object.cloudidList)) - throw TypeError(".ApiGetOpenDataByCloudIdReq.cloudidList: array expected"); - message.cloudidList = []; - for (var i = 0; i < object.cloudidList.length; ++i) - message.cloudidList[i] = String(object.cloudidList[i]); - } - return message; - }; - - /** + ApiGetOpenDataByCloudIdReq.fromObject = function fromObject(object) { + if (object instanceof $root.ApiGetOpenDataByCloudIdReq) return object + var message = new $root.ApiGetOpenDataByCloudIdReq() + if (object.cloudidList) { + if (!Array.isArray(object.cloudidList)) throw TypeError('.ApiGetOpenDataByCloudIdReq.cloudidList: array expected') + message.cloudidList = [] + for (var i = 0; i < object.cloudidList.length; ++i) message.cloudidList[i] = String(object.cloudidList[i]) + } + return message + } + + /** * Creates a plain object from an ApiGetOpenDataByCloudIdReq message. Also converts values to other types if specified. * @function toObject * @memberof ApiGetOpenDataByCloudIdReq @@ -3201,44 +2898,40 @@ $root.ApiGetOpenDataByCloudIdReq = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ApiGetOpenDataByCloudIdReq.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.cloudidList = []; - if (message.cloudidList && message.cloudidList.length) { - object.cloudidList = []; - for (var j = 0; j < message.cloudidList.length; ++j) - object.cloudidList[j] = message.cloudidList[j]; - } - return object; - }; - - /** + ApiGetOpenDataByCloudIdReq.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.cloudidList = [] + if (message.cloudidList && message.cloudidList.length) { + object.cloudidList = [] + for (var j = 0; j < message.cloudidList.length; ++j) object.cloudidList[j] = message.cloudidList[j] + } + return object + } + + /** * Converts this ApiGetOpenDataByCloudIdReq to JSON. * @function toJSON * @memberof ApiGetOpenDataByCloudIdReq * @instance * @returns {Object.} JSON object */ - ApiGetOpenDataByCloudIdReq.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ApiGetOpenDataByCloudIdReq; -})(); + ApiGetOpenDataByCloudIdReq.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.ApiGetOpenDataByCloudIdResp = (function() { + return ApiGetOpenDataByCloudIdReq + }()) - /** + $root.ApiGetOpenDataByCloudIdResp = (function () { + /** * Properties of an ApiGetOpenDataByCloudIdResp. * @exports IApiGetOpenDataByCloudIdResp * @interface IApiGetOpenDataByCloudIdResp * @property {Array.|null} [dataList] ApiGetOpenDataByCloudIdResp dataList */ - /** + /** * Constructs a new ApiGetOpenDataByCloudIdResp. * @exports ApiGetOpenDataByCloudIdResp * @classdesc Represents an ApiGetOpenDataByCloudIdResp. @@ -3246,23 +2939,20 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @constructor * @param {IApiGetOpenDataByCloudIdResp=} [properties] Properties to set */ - function ApiGetOpenDataByCloudIdResp(properties) { - this.dataList = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function ApiGetOpenDataByCloudIdResp(properties) { + this.dataList = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * ApiGetOpenDataByCloudIdResp dataList. * @member {Array.} dataList * @memberof ApiGetOpenDataByCloudIdResp * @instance */ - ApiGetOpenDataByCloudIdResp.prototype.dataList = $util.emptyArray; + ApiGetOpenDataByCloudIdResp.prototype.dataList = $util.emptyArray - /** + /** * Creates a new ApiGetOpenDataByCloudIdResp instance using the specified properties. * @function create * @memberof ApiGetOpenDataByCloudIdResp @@ -3270,11 +2960,11 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {IApiGetOpenDataByCloudIdResp=} [properties] Properties to set * @returns {ApiGetOpenDataByCloudIdResp} ApiGetOpenDataByCloudIdResp instance */ - ApiGetOpenDataByCloudIdResp.create = function create(properties) { - return new ApiGetOpenDataByCloudIdResp(properties); - }; + ApiGetOpenDataByCloudIdResp.create = function create(properties) { + return new ApiGetOpenDataByCloudIdResp(properties) + } - /** + /** * Encodes the specified ApiGetOpenDataByCloudIdResp message. Does not implicitly {@link ApiGetOpenDataByCloudIdResp.verify|verify} messages. * @function encode * @memberof ApiGetOpenDataByCloudIdResp @@ -3283,16 +2973,13 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiGetOpenDataByCloudIdResp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataList != null && message.dataList.length) - for (var i = 0; i < message.dataList.length; ++i) - $root.ApiGetOpenDataByCloudIdResp.OpDataItem.encode(message.dataList[i], writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - return writer; - }; + ApiGetOpenDataByCloudIdResp.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.dataList != null && message.dataList.length) for (var i = 0; i < message.dataList.length; ++i) $root.ApiGetOpenDataByCloudIdResp.OpDataItem.encode(message.dataList[i], writer.uint32(/* id 1, wireType 2 = */10).fork()).ldelim() + return writer + } - /** + /** * Encodes the specified ApiGetOpenDataByCloudIdResp message, length delimited. Does not implicitly {@link ApiGetOpenDataByCloudIdResp.verify|verify} messages. * @function encodeDelimited * @memberof ApiGetOpenDataByCloudIdResp @@ -3301,11 +2988,11 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiGetOpenDataByCloudIdResp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + ApiGetOpenDataByCloudIdResp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an ApiGetOpenDataByCloudIdResp message from the specified reader or buffer. * @function decode * @memberof ApiGetOpenDataByCloudIdResp @@ -3316,27 +3003,26 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiGetOpenDataByCloudIdResp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiGetOpenDataByCloudIdResp(); - while (reader.pos < end) { - var tag = reader.uint32(); + ApiGetOpenDataByCloudIdResp.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiGetOpenDataByCloudIdResp() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - if (!(message.dataList && message.dataList.length)) - message.dataList = []; - message.dataList.push($root.ApiGetOpenDataByCloudIdResp.OpDataItem.decode(reader, reader.uint32())); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + if (!(message.dataList && message.dataList.length)) message.dataList = [] + message.dataList.push($root.ApiGetOpenDataByCloudIdResp.OpDataItem.decode(reader, reader.uint32())) + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an ApiGetOpenDataByCloudIdResp message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiGetOpenDataByCloudIdResp @@ -3346,13 +3032,12 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiGetOpenDataByCloudIdResp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + ApiGetOpenDataByCloudIdResp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an ApiGetOpenDataByCloudIdResp message. * @function verify * @memberof ApiGetOpenDataByCloudIdResp @@ -3360,22 +3045,19 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ApiGetOpenDataByCloudIdResp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataList != null && message.hasOwnProperty("dataList")) { - if (!Array.isArray(message.dataList)) - return "dataList: array expected"; + ApiGetOpenDataByCloudIdResp.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.dataList != null && message.hasOwnProperty('dataList')) { + if (!Array.isArray(message.dataList)) return 'dataList: array expected' for (var i = 0; i < message.dataList.length; ++i) { - var error = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.verify(message.dataList[i]); - if (error) - return "dataList." + error; + var error = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.verify(message.dataList[i]) + if (error) return 'dataList.' + error } + } + return null } - return null; - }; - /** + /** * Creates an ApiGetOpenDataByCloudIdResp message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiGetOpenDataByCloudIdResp @@ -3383,24 +3065,21 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {Object.} object Plain object * @returns {ApiGetOpenDataByCloudIdResp} ApiGetOpenDataByCloudIdResp */ - ApiGetOpenDataByCloudIdResp.fromObject = function fromObject(object) { - if (object instanceof $root.ApiGetOpenDataByCloudIdResp) - return object; - var message = new $root.ApiGetOpenDataByCloudIdResp(); - if (object.dataList) { - if (!Array.isArray(object.dataList)) - throw TypeError(".ApiGetOpenDataByCloudIdResp.dataList: array expected"); - message.dataList = []; + ApiGetOpenDataByCloudIdResp.fromObject = function fromObject(object) { + if (object instanceof $root.ApiGetOpenDataByCloudIdResp) return object + var message = new $root.ApiGetOpenDataByCloudIdResp() + if (object.dataList) { + if (!Array.isArray(object.dataList)) throw TypeError('.ApiGetOpenDataByCloudIdResp.dataList: array expected') + message.dataList = [] for (var i = 0; i < object.dataList.length; ++i) { - if (typeof object.dataList[i] !== "object") - throw TypeError(".ApiGetOpenDataByCloudIdResp.dataList: object expected"); - message.dataList[i] = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.fromObject(object.dataList[i]); + if (typeof object.dataList[i] !== 'object') throw TypeError('.ApiGetOpenDataByCloudIdResp.dataList: object expected') + message.dataList[i] = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.fromObject(object.dataList[i]) } + } + return message } - return message; - }; - /** + /** * Creates a plain object from an ApiGetOpenDataByCloudIdResp message. Also converts values to other types if specified. * @function toObject * @memberof ApiGetOpenDataByCloudIdResp @@ -3409,33 +3088,29 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ApiGetOpenDataByCloudIdResp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataList = []; - if (message.dataList && message.dataList.length) { - object.dataList = []; - for (var j = 0; j < message.dataList.length; ++j) - object.dataList[j] = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.toObject(message.dataList[j], options); - } - return object; - }; - - /** + ApiGetOpenDataByCloudIdResp.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.dataList = [] + if (message.dataList && message.dataList.length) { + object.dataList = [] + for (var j = 0; j < message.dataList.length; ++j) object.dataList[j] = $root.ApiGetOpenDataByCloudIdResp.OpDataItem.toObject(message.dataList[j], options) + } + return object + } + + /** * Converts this ApiGetOpenDataByCloudIdResp to JSON. * @function toJSON * @memberof ApiGetOpenDataByCloudIdResp * @instance * @returns {Object.} JSON object */ - ApiGetOpenDataByCloudIdResp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - ApiGetOpenDataByCloudIdResp.OpDataItem = (function() { + ApiGetOpenDataByCloudIdResp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } + ApiGetOpenDataByCloudIdResp.OpDataItem = (function () { /** * Properties of an OpDataItem. * @memberof ApiGetOpenDataByCloudIdResp @@ -3444,7 +3119,7 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @property {string|null} [json] OpDataItem json */ - /** + /** * Constructs a new OpDataItem. * @memberof ApiGetOpenDataByCloudIdResp * @classdesc Represents an OpDataItem. @@ -3452,30 +3127,27 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @constructor * @param {ApiGetOpenDataByCloudIdResp.IOpDataItem=} [properties] Properties to set */ - function OpDataItem(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function OpDataItem(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * OpDataItem cloudId. * @member {string} cloudId * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem * @instance */ - OpDataItem.prototype.cloudId = ""; + OpDataItem.prototype.cloudId = '' - /** + /** * OpDataItem json. * @member {string} json * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem * @instance */ - OpDataItem.prototype.json = ""; + OpDataItem.prototype.json = '' - /** + /** * Creates a new OpDataItem instance using the specified properties. * @function create * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3483,11 +3155,11 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {ApiGetOpenDataByCloudIdResp.IOpDataItem=} [properties] Properties to set * @returns {ApiGetOpenDataByCloudIdResp.OpDataItem} OpDataItem instance */ - OpDataItem.create = function create(properties) { - return new OpDataItem(properties); - }; + OpDataItem.create = function create(properties) { + return new OpDataItem(properties) + } - /** + /** * Encodes the specified OpDataItem message. Does not implicitly {@link ApiGetOpenDataByCloudIdResp.OpDataItem.verify|verify} messages. * @function encode * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3496,17 +3168,14 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - OpDataItem.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.cloudId != null && message.hasOwnProperty("cloudId")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.cloudId); - if (message.json != null && message.hasOwnProperty("json")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.json); - return writer; - }; - - /** + OpDataItem.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.cloudId != null && message.hasOwnProperty('cloudId')) writer.uint32(/* id 1, wireType 2 = */10).string(message.cloudId) + if (message.json != null && message.hasOwnProperty('json')) writer.uint32(/* id 2, wireType 2 = */18).string(message.json) + return writer + } + + /** * Encodes the specified OpDataItem message, length delimited. Does not implicitly {@link ApiGetOpenDataByCloudIdResp.OpDataItem.verify|verify} messages. * @function encodeDelimited * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3515,11 +3184,11 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - OpDataItem.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + OpDataItem.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an OpDataItem message from the specified reader or buffer. * @function decode * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3530,28 +3199,28 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OpDataItem.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiGetOpenDataByCloudIdResp.OpDataItem(); + OpDataItem.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiGetOpenDataByCloudIdResp.OpDataItem() while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { + var tag = reader.uint32() + switch (tag >>> 3) { case 1: - message.cloudId = reader.string(); - break; + message.cloudId = reader.string() + break case 2: - message.json = reader.string(); - break; + message.json = reader.string() + break default: - reader.skipType(tag & 7); - break; - } + reader.skipType(tag & 7) + break + } } - return message; - }; + return message + } - /** + /** * Decodes an OpDataItem message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3561,13 +3230,12 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - OpDataItem.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + OpDataItem.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an OpDataItem message. * @function verify * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3575,19 +3243,14 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - OpDataItem.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.cloudId != null && message.hasOwnProperty("cloudId")) - if (!$util.isString(message.cloudId)) - return "cloudId: string expected"; - if (message.json != null && message.hasOwnProperty("json")) - if (!$util.isString(message.json)) - return "json: string expected"; - return null; - }; - - /** + OpDataItem.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.cloudId != null && message.hasOwnProperty('cloudId')) if (!$util.isString(message.cloudId)) return 'cloudId: string expected' + if (message.json != null && message.hasOwnProperty('json')) if (!$util.isString(message.json)) return 'json: string expected' + return null + } + + /** * Creates an OpDataItem message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3595,18 +3258,15 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {Object.} object Plain object * @returns {ApiGetOpenDataByCloudIdResp.OpDataItem} OpDataItem */ - OpDataItem.fromObject = function fromObject(object) { - if (object instanceof $root.ApiGetOpenDataByCloudIdResp.OpDataItem) - return object; - var message = new $root.ApiGetOpenDataByCloudIdResp.OpDataItem(); - if (object.cloudId != null) - message.cloudId = String(object.cloudId); - if (object.json != null) - message.json = String(object.json); - return message; - }; - - /** + OpDataItem.fromObject = function fromObject(object) { + if (object instanceof $root.ApiGetOpenDataByCloudIdResp.OpDataItem) return object + var message = new $root.ApiGetOpenDataByCloudIdResp.OpDataItem() + if (object.cloudId != null) message.cloudId = String(object.cloudId) + if (object.json != null) message.json = String(object.json) + return message + } + + /** * Creates a plain object from an OpDataItem message. Also converts values to other types if specified. * @function toObject * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem @@ -3615,41 +3275,37 @@ $root.ApiGetOpenDataByCloudIdResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - OpDataItem.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; + OpDataItem.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} if (options.defaults) { - object.cloudId = ""; - object.json = ""; + object.cloudId = '' + object.json = '' } - if (message.cloudId != null && message.hasOwnProperty("cloudId")) - object.cloudId = message.cloudId; - if (message.json != null && message.hasOwnProperty("json")) - object.json = message.json; - return object; - }; + if (message.cloudId != null && message.hasOwnProperty('cloudId')) object.cloudId = message.cloudId + if (message.json != null && message.hasOwnProperty('json')) object.json = message.json + return object + } - /** + /** * Converts this OpDataItem to JSON. * @function toJSON * @memberof ApiGetOpenDataByCloudIdResp.OpDataItem * @instance * @returns {Object.} JSON object */ - OpDataItem.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; + OpDataItem.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - return OpDataItem; - })(); + return OpDataItem + }()) - return ApiGetOpenDataByCloudIdResp; -})(); + return ApiGetOpenDataByCloudIdResp + }()) -$root.ApiVoipSignReq = (function() { - - /** + $root.ApiVoipSignReq = (function () { + /** * Properties of an ApiVoipSignReq. * @exports IApiVoipSignReq * @interface IApiVoipSignReq @@ -3658,7 +3314,7 @@ $root.ApiVoipSignReq = (function() { * @property {string|null} [nonce] ApiVoipSignReq nonce */ - /** + /** * Constructs a new ApiVoipSignReq. * @exports ApiVoipSignReq * @classdesc Represents an ApiVoipSignReq. @@ -3666,38 +3322,35 @@ $root.ApiVoipSignReq = (function() { * @constructor * @param {IApiVoipSignReq=} [properties] Properties to set */ - function ApiVoipSignReq(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function ApiVoipSignReq(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * ApiVoipSignReq groupId. * @member {string} groupId * @memberof ApiVoipSignReq * @instance */ - ApiVoipSignReq.prototype.groupId = ""; + ApiVoipSignReq.prototype.groupId = '' - /** + /** * ApiVoipSignReq timestamp. * @member {number} timestamp * @memberof ApiVoipSignReq * @instance */ - ApiVoipSignReq.prototype.timestamp = 0; + ApiVoipSignReq.prototype.timestamp = 0 - /** + /** * ApiVoipSignReq nonce. * @member {string} nonce * @memberof ApiVoipSignReq * @instance */ - ApiVoipSignReq.prototype.nonce = ""; + ApiVoipSignReq.prototype.nonce = '' - /** + /** * Creates a new ApiVoipSignReq instance using the specified properties. * @function create * @memberof ApiVoipSignReq @@ -3705,11 +3358,11 @@ $root.ApiVoipSignReq = (function() { * @param {IApiVoipSignReq=} [properties] Properties to set * @returns {ApiVoipSignReq} ApiVoipSignReq instance */ - ApiVoipSignReq.create = function create(properties) { - return new ApiVoipSignReq(properties); - }; + ApiVoipSignReq.create = function create(properties) { + return new ApiVoipSignReq(properties) + } - /** + /** * Encodes the specified ApiVoipSignReq message. Does not implicitly {@link ApiVoipSignReq.verify|verify} messages. * @function encode * @memberof ApiVoipSignReq @@ -3718,19 +3371,15 @@ $root.ApiVoipSignReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiVoipSignReq.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.groupId != null && message.hasOwnProperty("groupId")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.groupId); - if (message.timestamp != null && message.hasOwnProperty("timestamp")) - writer.uint32(/* id 3, wireType 0 =*/24).uint32(message.timestamp); - if (message.nonce != null && message.hasOwnProperty("nonce")) - writer.uint32(/* id 4, wireType 2 =*/34).string(message.nonce); - return writer; - }; - - /** + ApiVoipSignReq.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.groupId != null && message.hasOwnProperty('groupId')) writer.uint32(/* id 2, wireType 2 = */18).string(message.groupId) + if (message.timestamp != null && message.hasOwnProperty('timestamp')) writer.uint32(/* id 3, wireType 0 = */24).uint32(message.timestamp) + if (message.nonce != null && message.hasOwnProperty('nonce')) writer.uint32(/* id 4, wireType 2 = */34).string(message.nonce) + return writer + } + + /** * Encodes the specified ApiVoipSignReq message, length delimited. Does not implicitly {@link ApiVoipSignReq.verify|verify} messages. * @function encodeDelimited * @memberof ApiVoipSignReq @@ -3739,11 +3388,11 @@ $root.ApiVoipSignReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiVoipSignReq.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + ApiVoipSignReq.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an ApiVoipSignReq message from the specified reader or buffer. * @function decode * @memberof ApiVoipSignReq @@ -3754,31 +3403,31 @@ $root.ApiVoipSignReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiVoipSignReq.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiVoipSignReq(); - while (reader.pos < end) { - var tag = reader.uint32(); + ApiVoipSignReq.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiVoipSignReq() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 2: - message.groupId = reader.string(); - break; - case 3: - message.timestamp = reader.uint32(); - break; - case 4: - message.nonce = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 2: + message.groupId = reader.string() + break + case 3: + message.timestamp = reader.uint32() + break + case 4: + message.nonce = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an ApiVoipSignReq message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiVoipSignReq @@ -3788,13 +3437,12 @@ $root.ApiVoipSignReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiVoipSignReq.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + ApiVoipSignReq.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an ApiVoipSignReq message. * @function verify * @memberof ApiVoipSignReq @@ -3802,22 +3450,15 @@ $root.ApiVoipSignReq = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ApiVoipSignReq.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.groupId != null && message.hasOwnProperty("groupId")) - if (!$util.isString(message.groupId)) - return "groupId: string expected"; - if (message.timestamp != null && message.hasOwnProperty("timestamp")) - if (!$util.isInteger(message.timestamp)) - return "timestamp: integer expected"; - if (message.nonce != null && message.hasOwnProperty("nonce")) - if (!$util.isString(message.nonce)) - return "nonce: string expected"; - return null; - }; - - /** + ApiVoipSignReq.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.groupId != null && message.hasOwnProperty('groupId')) if (!$util.isString(message.groupId)) return 'groupId: string expected' + if (message.timestamp != null && message.hasOwnProperty('timestamp')) if (!$util.isInteger(message.timestamp)) return 'timestamp: integer expected' + if (message.nonce != null && message.hasOwnProperty('nonce')) if (!$util.isString(message.nonce)) return 'nonce: string expected' + return null + } + + /** * Creates an ApiVoipSignReq message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiVoipSignReq @@ -3825,20 +3466,16 @@ $root.ApiVoipSignReq = (function() { * @param {Object.} object Plain object * @returns {ApiVoipSignReq} ApiVoipSignReq */ - ApiVoipSignReq.fromObject = function fromObject(object) { - if (object instanceof $root.ApiVoipSignReq) - return object; - var message = new $root.ApiVoipSignReq(); - if (object.groupId != null) - message.groupId = String(object.groupId); - if (object.timestamp != null) - message.timestamp = object.timestamp >>> 0; - if (object.nonce != null) - message.nonce = String(object.nonce); - return message; - }; - - /** + ApiVoipSignReq.fromObject = function fromObject(object) { + if (object instanceof $root.ApiVoipSignReq) return object + var message = new $root.ApiVoipSignReq() + if (object.groupId != null) message.groupId = String(object.groupId) + if (object.timestamp != null) message.timestamp = object.timestamp >>> 0 + if (object.nonce != null) message.nonce = String(object.nonce) + return message + } + + /** * Creates a plain object from an ApiVoipSignReq message. Also converts values to other types if specified. * @function toObject * @memberof ApiVoipSignReq @@ -3847,48 +3484,43 @@ $root.ApiVoipSignReq = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ApiVoipSignReq.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.groupId = ""; - object.timestamp = 0; - object.nonce = ""; - } - if (message.groupId != null && message.hasOwnProperty("groupId")) - object.groupId = message.groupId; - if (message.timestamp != null && message.hasOwnProperty("timestamp")) - object.timestamp = message.timestamp; - if (message.nonce != null && message.hasOwnProperty("nonce")) - object.nonce = message.nonce; - return object; - }; - - /** + ApiVoipSignReq.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.groupId = '' + object.timestamp = 0 + object.nonce = '' + } + if (message.groupId != null && message.hasOwnProperty('groupId')) object.groupId = message.groupId + if (message.timestamp != null && message.hasOwnProperty('timestamp')) object.timestamp = message.timestamp + if (message.nonce != null && message.hasOwnProperty('nonce')) object.nonce = message.nonce + return object + } + + /** * Converts this ApiVoipSignReq to JSON. * @function toJSON * @memberof ApiVoipSignReq * @instance * @returns {Object.} JSON object */ - ApiVoipSignReq.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ApiVoipSignReq; -})(); + ApiVoipSignReq.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.ApiVoipSignResp = (function() { + return ApiVoipSignReq + }()) - /** + $root.ApiVoipSignResp = (function () { + /** * Properties of an ApiVoipSignResp. * @exports IApiVoipSignResp * @interface IApiVoipSignResp * @property {string|null} [signature] ApiVoipSignResp signature */ - /** + /** * Constructs a new ApiVoipSignResp. * @exports ApiVoipSignResp * @classdesc Represents an ApiVoipSignResp. @@ -3896,22 +3528,19 @@ $root.ApiVoipSignResp = (function() { * @constructor * @param {IApiVoipSignResp=} [properties] Properties to set */ - function ApiVoipSignResp(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function ApiVoipSignResp(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * ApiVoipSignResp signature. * @member {string} signature * @memberof ApiVoipSignResp * @instance */ - ApiVoipSignResp.prototype.signature = ""; + ApiVoipSignResp.prototype.signature = '' - /** + /** * Creates a new ApiVoipSignResp instance using the specified properties. * @function create * @memberof ApiVoipSignResp @@ -3919,11 +3548,11 @@ $root.ApiVoipSignResp = (function() { * @param {IApiVoipSignResp=} [properties] Properties to set * @returns {ApiVoipSignResp} ApiVoipSignResp instance */ - ApiVoipSignResp.create = function create(properties) { - return new ApiVoipSignResp(properties); - }; + ApiVoipSignResp.create = function create(properties) { + return new ApiVoipSignResp(properties) + } - /** + /** * Encodes the specified ApiVoipSignResp message. Does not implicitly {@link ApiVoipSignResp.verify|verify} messages. * @function encode * @memberof ApiVoipSignResp @@ -3932,15 +3561,13 @@ $root.ApiVoipSignResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiVoipSignResp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.signature != null && message.hasOwnProperty("signature")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.signature); - return writer; - }; + ApiVoipSignResp.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.signature != null && message.hasOwnProperty('signature')) writer.uint32(/* id 1, wireType 2 = */10).string(message.signature) + return writer + } - /** + /** * Encodes the specified ApiVoipSignResp message, length delimited. Does not implicitly {@link ApiVoipSignResp.verify|verify} messages. * @function encodeDelimited * @memberof ApiVoipSignResp @@ -3949,11 +3576,11 @@ $root.ApiVoipSignResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiVoipSignResp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + ApiVoipSignResp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an ApiVoipSignResp message from the specified reader or buffer. * @function decode * @memberof ApiVoipSignResp @@ -3964,25 +3591,25 @@ $root.ApiVoipSignResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiVoipSignResp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiVoipSignResp(); - while (reader.pos < end) { - var tag = reader.uint32(); + ApiVoipSignResp.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiVoipSignResp() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.signature = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.signature = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an ApiVoipSignResp message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiVoipSignResp @@ -3992,13 +3619,12 @@ $root.ApiVoipSignResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiVoipSignResp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + ApiVoipSignResp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an ApiVoipSignResp message. * @function verify * @memberof ApiVoipSignResp @@ -4006,16 +3632,13 @@ $root.ApiVoipSignResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ApiVoipSignResp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.signature != null && message.hasOwnProperty("signature")) - if (!$util.isString(message.signature)) - return "signature: string expected"; - return null; - }; + ApiVoipSignResp.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.signature != null && message.hasOwnProperty('signature')) if (!$util.isString(message.signature)) return 'signature: string expected' + return null + } - /** + /** * Creates an ApiVoipSignResp message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiVoipSignResp @@ -4023,16 +3646,14 @@ $root.ApiVoipSignResp = (function() { * @param {Object.} object Plain object * @returns {ApiVoipSignResp} ApiVoipSignResp */ - ApiVoipSignResp.fromObject = function fromObject(object) { - if (object instanceof $root.ApiVoipSignResp) - return object; - var message = new $root.ApiVoipSignResp(); - if (object.signature != null) - message.signature = String(object.signature); - return message; - }; + ApiVoipSignResp.fromObject = function fromObject(object) { + if (object instanceof $root.ApiVoipSignResp) return object + var message = new $root.ApiVoipSignResp() + if (object.signature != null) message.signature = String(object.signature) + return message + } - /** + /** * Creates a plain object from an ApiVoipSignResp message. Also converts values to other types if specified. * @function toObject * @memberof ApiVoipSignResp @@ -4041,41 +3662,37 @@ $root.ApiVoipSignResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ApiVoipSignResp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.signature = ""; - if (message.signature != null && message.hasOwnProperty("signature")) - object.signature = message.signature; - return object; - }; - - /** + ApiVoipSignResp.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) object.signature = '' + if (message.signature != null && message.hasOwnProperty('signature')) object.signature = message.signature + return object + } + + /** * Converts this ApiVoipSignResp to JSON. * @function toJSON * @memberof ApiVoipSignResp * @instance * @returns {Object.} JSON object */ - ApiVoipSignResp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ApiVoipSignResp; -})(); + ApiVoipSignResp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.GetCloudCallSignReq = (function() { + return ApiVoipSignResp + }()) - /** + $root.GetCloudCallSignReq = (function () { + /** * Properties of a GetCloudCallSignReq. * @exports IGetCloudCallSignReq * @interface IGetCloudCallSignReq * @property {Array.|null} [parameterList] GetCloudCallSignReq parameterList */ - /** + /** * Constructs a new GetCloudCallSignReq. * @exports GetCloudCallSignReq * @classdesc Represents a GetCloudCallSignReq. @@ -4083,23 +3700,20 @@ $root.GetCloudCallSignReq = (function() { * @constructor * @param {IGetCloudCallSignReq=} [properties] Properties to set */ - function GetCloudCallSignReq(properties) { - this.parameterList = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function GetCloudCallSignReq(properties) { + this.parameterList = [] + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * GetCloudCallSignReq parameterList. * @member {Array.} parameterList * @memberof GetCloudCallSignReq * @instance */ - GetCloudCallSignReq.prototype.parameterList = $util.emptyArray; + GetCloudCallSignReq.prototype.parameterList = $util.emptyArray - /** + /** * Creates a new GetCloudCallSignReq instance using the specified properties. * @function create * @memberof GetCloudCallSignReq @@ -4107,11 +3721,11 @@ $root.GetCloudCallSignReq = (function() { * @param {IGetCloudCallSignReq=} [properties] Properties to set * @returns {GetCloudCallSignReq} GetCloudCallSignReq instance */ - GetCloudCallSignReq.create = function create(properties) { - return new GetCloudCallSignReq(properties); - }; + GetCloudCallSignReq.create = function create(properties) { + return new GetCloudCallSignReq(properties) + } - /** + /** * Encodes the specified GetCloudCallSignReq message. Does not implicitly {@link GetCloudCallSignReq.verify|verify} messages. * @function encode * @memberof GetCloudCallSignReq @@ -4120,16 +3734,13 @@ $root.GetCloudCallSignReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetCloudCallSignReq.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.parameterList != null && message.parameterList.length) - for (var i = 0; i < message.parameterList.length; ++i) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.parameterList[i]); - return writer; - }; + GetCloudCallSignReq.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.parameterList != null && message.parameterList.length) for (var i = 0; i < message.parameterList.length; ++i) writer.uint32(/* id 2, wireType 2 = */18).string(message.parameterList[i]) + return writer + } - /** + /** * Encodes the specified GetCloudCallSignReq message, length delimited. Does not implicitly {@link GetCloudCallSignReq.verify|verify} messages. * @function encodeDelimited * @memberof GetCloudCallSignReq @@ -4138,11 +3749,11 @@ $root.GetCloudCallSignReq = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetCloudCallSignReq.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + GetCloudCallSignReq.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a GetCloudCallSignReq message from the specified reader or buffer. * @function decode * @memberof GetCloudCallSignReq @@ -4153,27 +3764,26 @@ $root.GetCloudCallSignReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetCloudCallSignReq.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.GetCloudCallSignReq(); - while (reader.pos < end) { - var tag = reader.uint32(); + GetCloudCallSignReq.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.GetCloudCallSignReq() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 2: - if (!(message.parameterList && message.parameterList.length)) - message.parameterList = []; - message.parameterList.push(reader.string()); - break; - default: - reader.skipType(tag & 7); - break; + case 2: + if (!(message.parameterList && message.parameterList.length)) message.parameterList = [] + message.parameterList.push(reader.string()) + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a GetCloudCallSignReq message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof GetCloudCallSignReq @@ -4183,13 +3793,12 @@ $root.GetCloudCallSignReq = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetCloudCallSignReq.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + GetCloudCallSignReq.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a GetCloudCallSignReq message. * @function verify * @memberof GetCloudCallSignReq @@ -4197,20 +3806,16 @@ $root.GetCloudCallSignReq = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetCloudCallSignReq.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.parameterList != null && message.hasOwnProperty("parameterList")) { - if (!Array.isArray(message.parameterList)) - return "parameterList: array expected"; - for (var i = 0; i < message.parameterList.length; ++i) - if (!$util.isString(message.parameterList[i])) - return "parameterList: string[] expected"; + GetCloudCallSignReq.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.parameterList != null && message.hasOwnProperty('parameterList')) { + if (!Array.isArray(message.parameterList)) return 'parameterList: array expected' + for (var i = 0; i < message.parameterList.length; ++i) if (!$util.isString(message.parameterList[i])) return 'parameterList: string[] expected' + } + return null } - return null; - }; - /** + /** * Creates a GetCloudCallSignReq message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof GetCloudCallSignReq @@ -4218,21 +3823,18 @@ $root.GetCloudCallSignReq = (function() { * @param {Object.} object Plain object * @returns {GetCloudCallSignReq} GetCloudCallSignReq */ - GetCloudCallSignReq.fromObject = function fromObject(object) { - if (object instanceof $root.GetCloudCallSignReq) - return object; - var message = new $root.GetCloudCallSignReq(); - if (object.parameterList) { - if (!Array.isArray(object.parameterList)) - throw TypeError(".GetCloudCallSignReq.parameterList: array expected"); - message.parameterList = []; - for (var i = 0; i < object.parameterList.length; ++i) - message.parameterList[i] = String(object.parameterList[i]); - } - return message; - }; - - /** + GetCloudCallSignReq.fromObject = function fromObject(object) { + if (object instanceof $root.GetCloudCallSignReq) return object + var message = new $root.GetCloudCallSignReq() + if (object.parameterList) { + if (!Array.isArray(object.parameterList)) throw TypeError('.GetCloudCallSignReq.parameterList: array expected') + message.parameterList = [] + for (var i = 0; i < object.parameterList.length; ++i) message.parameterList[i] = String(object.parameterList[i]) + } + return message + } + + /** * Creates a plain object from a GetCloudCallSignReq message. Also converts values to other types if specified. * @function toObject * @memberof GetCloudCallSignReq @@ -4241,44 +3843,40 @@ $root.GetCloudCallSignReq = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetCloudCallSignReq.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.parameterList = []; - if (message.parameterList && message.parameterList.length) { - object.parameterList = []; - for (var j = 0; j < message.parameterList.length; ++j) - object.parameterList[j] = message.parameterList[j]; - } - return object; - }; - - /** + GetCloudCallSignReq.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.arrays || options.defaults) object.parameterList = [] + if (message.parameterList && message.parameterList.length) { + object.parameterList = [] + for (var j = 0; j < message.parameterList.length; ++j) object.parameterList[j] = message.parameterList[j] + } + return object + } + + /** * Converts this GetCloudCallSignReq to JSON. * @function toJSON * @memberof GetCloudCallSignReq * @instance * @returns {Object.} JSON object */ - GetCloudCallSignReq.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GetCloudCallSignReq; -})(); + GetCloudCallSignReq.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.GetCloudCallSignResp = (function() { + return GetCloudCallSignReq + }()) - /** + $root.GetCloudCallSignResp = (function () { + /** * Properties of a GetCloudCallSignResp. * @exports IGetCloudCallSignResp * @interface IGetCloudCallSignResp * @property {string|null} [signature] GetCloudCallSignResp signature */ - /** + /** * Constructs a new GetCloudCallSignResp. * @exports GetCloudCallSignResp * @classdesc Represents a GetCloudCallSignResp. @@ -4286,22 +3884,19 @@ $root.GetCloudCallSignResp = (function() { * @constructor * @param {IGetCloudCallSignResp=} [properties] Properties to set */ - function GetCloudCallSignResp(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function GetCloudCallSignResp(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * GetCloudCallSignResp signature. * @member {string} signature * @memberof GetCloudCallSignResp * @instance */ - GetCloudCallSignResp.prototype.signature = ""; + GetCloudCallSignResp.prototype.signature = '' - /** + /** * Creates a new GetCloudCallSignResp instance using the specified properties. * @function create * @memberof GetCloudCallSignResp @@ -4309,11 +3904,11 @@ $root.GetCloudCallSignResp = (function() { * @param {IGetCloudCallSignResp=} [properties] Properties to set * @returns {GetCloudCallSignResp} GetCloudCallSignResp instance */ - GetCloudCallSignResp.create = function create(properties) { - return new GetCloudCallSignResp(properties); - }; + GetCloudCallSignResp.create = function create(properties) { + return new GetCloudCallSignResp(properties) + } - /** + /** * Encodes the specified GetCloudCallSignResp message. Does not implicitly {@link GetCloudCallSignResp.verify|verify} messages. * @function encode * @memberof GetCloudCallSignResp @@ -4322,15 +3917,13 @@ $root.GetCloudCallSignResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetCloudCallSignResp.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.signature != null && message.hasOwnProperty("signature")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.signature); - return writer; - }; + GetCloudCallSignResp.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.signature != null && message.hasOwnProperty('signature')) writer.uint32(/* id 1, wireType 2 = */10).string(message.signature) + return writer + } - /** + /** * Encodes the specified GetCloudCallSignResp message, length delimited. Does not implicitly {@link GetCloudCallSignResp.verify|verify} messages. * @function encodeDelimited * @memberof GetCloudCallSignResp @@ -4339,11 +3932,11 @@ $root.GetCloudCallSignResp = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - GetCloudCallSignResp.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + GetCloudCallSignResp.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a GetCloudCallSignResp message from the specified reader or buffer. * @function decode * @memberof GetCloudCallSignResp @@ -4354,25 +3947,25 @@ $root.GetCloudCallSignResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetCloudCallSignResp.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.GetCloudCallSignResp(); - while (reader.pos < end) { - var tag = reader.uint32(); + GetCloudCallSignResp.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.GetCloudCallSignResp() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.signature = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.signature = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes a GetCloudCallSignResp message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof GetCloudCallSignResp @@ -4382,13 +3975,12 @@ $root.GetCloudCallSignResp = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - GetCloudCallSignResp.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + GetCloudCallSignResp.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a GetCloudCallSignResp message. * @function verify * @memberof GetCloudCallSignResp @@ -4396,16 +3988,13 @@ $root.GetCloudCallSignResp = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - GetCloudCallSignResp.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.signature != null && message.hasOwnProperty("signature")) - if (!$util.isString(message.signature)) - return "signature: string expected"; - return null; - }; + GetCloudCallSignResp.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.signature != null && message.hasOwnProperty('signature')) if (!$util.isString(message.signature)) return 'signature: string expected' + return null + } - /** + /** * Creates a GetCloudCallSignResp message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof GetCloudCallSignResp @@ -4413,16 +4002,14 @@ $root.GetCloudCallSignResp = (function() { * @param {Object.} object Plain object * @returns {GetCloudCallSignResp} GetCloudCallSignResp */ - GetCloudCallSignResp.fromObject = function fromObject(object) { - if (object instanceof $root.GetCloudCallSignResp) - return object; - var message = new $root.GetCloudCallSignResp(); - if (object.signature != null) - message.signature = String(object.signature); - return message; - }; + GetCloudCallSignResp.fromObject = function fromObject(object) { + if (object instanceof $root.GetCloudCallSignResp) return object + var message = new $root.GetCloudCallSignResp() + if (object.signature != null) message.signature = String(object.signature) + return message + } - /** + /** * Creates a plain object from a GetCloudCallSignResp message. Also converts values to other types if specified. * @function toObject * @memberof GetCloudCallSignResp @@ -4431,34 +4018,30 @@ $root.GetCloudCallSignResp = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - GetCloudCallSignResp.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.signature = ""; - if (message.signature != null && message.hasOwnProperty("signature")) - object.signature = message.signature; - return object; - }; - - /** + GetCloudCallSignResp.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) object.signature = '' + if (message.signature != null && message.hasOwnProperty('signature')) object.signature = message.signature + return object + } + + /** * Converts this GetCloudCallSignResp to JSON. * @function toJSON * @memberof GetCloudCallSignResp * @instance * @returns {Object.} JSON object */ - GetCloudCallSignResp.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return GetCloudCallSignResp; -})(); + GetCloudCallSignResp.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } -$root.AuthorizationInfo = (function() { + return GetCloudCallSignResp + }()) - /** + $root.AuthorizationInfo = (function () { + /** * Properties of an AuthorizationInfo. * @exports IAuthorizationInfo * @interface IAuthorizationInfo @@ -4466,7 +4049,7 @@ $root.AuthorizationInfo = (function() { * @property {Uint8Array|null} [wxParam] AuthorizationInfo wxParam */ - /** + /** * Constructs a new AuthorizationInfo. * @exports AuthorizationInfo * @classdesc Represents an AuthorizationInfo. @@ -4474,30 +4057,27 @@ $root.AuthorizationInfo = (function() { * @constructor * @param {IAuthorizationInfo=} [properties] Properties to set */ - function AuthorizationInfo(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function AuthorizationInfo(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * AuthorizationInfo tcbCredentials. * @member {AuthorizationInfo.ITcbCredentials|null|undefined} tcbCredentials * @memberof AuthorizationInfo * @instance */ - AuthorizationInfo.prototype.tcbCredentials = null; + AuthorizationInfo.prototype.tcbCredentials = null - /** + /** * AuthorizationInfo wxParam. * @member {Uint8Array} wxParam * @memberof AuthorizationInfo * @instance */ - AuthorizationInfo.prototype.wxParam = $util.newBuffer([]); + AuthorizationInfo.prototype.wxParam = $util.newBuffer([]) - /** + /** * Creates a new AuthorizationInfo instance using the specified properties. * @function create * @memberof AuthorizationInfo @@ -4505,11 +4085,11 @@ $root.AuthorizationInfo = (function() { * @param {IAuthorizationInfo=} [properties] Properties to set * @returns {AuthorizationInfo} AuthorizationInfo instance */ - AuthorizationInfo.create = function create(properties) { - return new AuthorizationInfo(properties); - }; + AuthorizationInfo.create = function create(properties) { + return new AuthorizationInfo(properties) + } - /** + /** * Encodes the specified AuthorizationInfo message. Does not implicitly {@link AuthorizationInfo.verify|verify} messages. * @function encode * @memberof AuthorizationInfo @@ -4518,17 +4098,14 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - AuthorizationInfo.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.tcbCredentials != null && message.hasOwnProperty("tcbCredentials")) - $root.AuthorizationInfo.TcbCredentials.encode(message.tcbCredentials, writer.uint32(/* id 1, wireType 2 =*/10).fork()).ldelim(); - if (message.wxParam != null && message.hasOwnProperty("wxParam")) - writer.uint32(/* id 2, wireType 2 =*/18).bytes(message.wxParam); - return writer; - }; - - /** + AuthorizationInfo.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.tcbCredentials != null && message.hasOwnProperty('tcbCredentials')) $root.AuthorizationInfo.TcbCredentials.encode(message.tcbCredentials, writer.uint32(/* id 1, wireType 2 = */10).fork()).ldelim() + if (message.wxParam != null && message.hasOwnProperty('wxParam')) writer.uint32(/* id 2, wireType 2 = */18).bytes(message.wxParam) + return writer + } + + /** * Encodes the specified AuthorizationInfo message, length delimited. Does not implicitly {@link AuthorizationInfo.verify|verify} messages. * @function encodeDelimited * @memberof AuthorizationInfo @@ -4537,11 +4114,11 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - AuthorizationInfo.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + AuthorizationInfo.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an AuthorizationInfo message from the specified reader or buffer. * @function decode * @memberof AuthorizationInfo @@ -4552,28 +4129,28 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AuthorizationInfo.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.AuthorizationInfo(); - while (reader.pos < end) { - var tag = reader.uint32(); + AuthorizationInfo.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.AuthorizationInfo() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.decode(reader, reader.uint32()); - break; - case 2: - message.wxParam = reader.bytes(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.decode(reader, reader.uint32()) + break + case 2: + message.wxParam = reader.bytes() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an AuthorizationInfo message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof AuthorizationInfo @@ -4583,13 +4160,12 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - AuthorizationInfo.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + AuthorizationInfo.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an AuthorizationInfo message. * @function verify * @memberof AuthorizationInfo @@ -4597,21 +4173,17 @@ $root.AuthorizationInfo = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - AuthorizationInfo.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.tcbCredentials != null && message.hasOwnProperty("tcbCredentials")) { - var error = $root.AuthorizationInfo.TcbCredentials.verify(message.tcbCredentials); - if (error) - return "tcbCredentials." + error; - } - if (message.wxParam != null && message.hasOwnProperty("wxParam")) - if (!(message.wxParam && typeof message.wxParam.length === "number" || $util.isString(message.wxParam))) - return "wxParam: buffer expected"; - return null; - }; - - /** + AuthorizationInfo.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.tcbCredentials != null && message.hasOwnProperty('tcbCredentials')) { + var error = $root.AuthorizationInfo.TcbCredentials.verify(message.tcbCredentials) + if (error) return 'tcbCredentials.' + error + } + if (message.wxParam != null && message.hasOwnProperty('wxParam')) if (!(message.wxParam && typeof message.wxParam.length === 'number' || $util.isString(message.wxParam))) return 'wxParam: buffer expected' + return null + } + + /** * Creates an AuthorizationInfo message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof AuthorizationInfo @@ -4619,24 +4191,21 @@ $root.AuthorizationInfo = (function() { * @param {Object.} object Plain object * @returns {AuthorizationInfo} AuthorizationInfo */ - AuthorizationInfo.fromObject = function fromObject(object) { - if (object instanceof $root.AuthorizationInfo) - return object; - var message = new $root.AuthorizationInfo(); - if (object.tcbCredentials != null) { - if (typeof object.tcbCredentials !== "object") - throw TypeError(".AuthorizationInfo.tcbCredentials: object expected"); - message.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.fromObject(object.tcbCredentials); - } - if (object.wxParam != null) - if (typeof object.wxParam === "string") - $util.base64.decode(object.wxParam, message.wxParam = $util.newBuffer($util.base64.length(object.wxParam)), 0); - else if (object.wxParam.length) - message.wxParam = object.wxParam; - return message; - }; - - /** + AuthorizationInfo.fromObject = function fromObject(object) { + if (object instanceof $root.AuthorizationInfo) return object + var message = new $root.AuthorizationInfo() + if (object.tcbCredentials != null) { + if (typeof object.tcbCredentials !== 'object') throw TypeError('.AuthorizationInfo.tcbCredentials: object expected') + message.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.fromObject(object.tcbCredentials) + } + if (object.wxParam != null) { + if (typeof object.wxParam === 'string') $util.base64.decode(object.wxParam, message.wxParam = $util.newBuffer($util.base64.length(object.wxParam)), 0) + else if (object.wxParam.length) message.wxParam = object.wxParam + } + return message + } + + /** * Creates a plain object from an AuthorizationInfo message. Also converts values to other types if specified. * @function toObject * @memberof AuthorizationInfo @@ -4645,40 +4214,34 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - AuthorizationInfo.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.tcbCredentials = null; - if (options.bytes === String) - object.wxParam = ""; + AuthorizationInfo.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) { + object.tcbCredentials = null + if (options.bytes === String) object.wxParam = '' else { - object.wxParam = []; - if (options.bytes !== Array) - object.wxParam = $util.newBuffer(object.wxParam); + object.wxParam = [] + if (options.bytes !== Array) object.wxParam = $util.newBuffer(object.wxParam) } + } + if (message.tcbCredentials != null && message.hasOwnProperty('tcbCredentials')) object.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.toObject(message.tcbCredentials, options) + if (message.wxParam != null && message.hasOwnProperty('wxParam')) object.wxParam = options.bytes === String ? $util.base64.encode(message.wxParam, 0, message.wxParam.length) : options.bytes === Array ? Array.prototype.slice.call(message.wxParam) : message.wxParam + return object } - if (message.tcbCredentials != null && message.hasOwnProperty("tcbCredentials")) - object.tcbCredentials = $root.AuthorizationInfo.TcbCredentials.toObject(message.tcbCredentials, options); - if (message.wxParam != null && message.hasOwnProperty("wxParam")) - object.wxParam = options.bytes === String ? $util.base64.encode(message.wxParam, 0, message.wxParam.length) : options.bytes === Array ? Array.prototype.slice.call(message.wxParam) : message.wxParam; - return object; - }; - /** + /** * Converts this AuthorizationInfo to JSON. * @function toJSON * @memberof AuthorizationInfo * @instance * @returns {Object.} JSON object */ - AuthorizationInfo.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - AuthorizationInfo.TcbCredentials = (function() { + AuthorizationInfo.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } + AuthorizationInfo.TcbCredentials = (function () { /** * Properties of a TcbCredentials. * @memberof AuthorizationInfo @@ -4688,7 +4251,7 @@ $root.AuthorizationInfo = (function() { * @property {string|null} [token] TcbCredentials token */ - /** + /** * Constructs a new TcbCredentials. * @memberof AuthorizationInfo * @classdesc Represents a TcbCredentials. @@ -4696,38 +4259,35 @@ $root.AuthorizationInfo = (function() { * @constructor * @param {AuthorizationInfo.ITcbCredentials=} [properties] Properties to set */ - function TcbCredentials(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function TcbCredentials(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * TcbCredentials secretId. * @member {string} secretId * @memberof AuthorizationInfo.TcbCredentials * @instance */ - TcbCredentials.prototype.secretId = ""; + TcbCredentials.prototype.secretId = '' - /** + /** * TcbCredentials secretKey. * @member {string} secretKey * @memberof AuthorizationInfo.TcbCredentials * @instance */ - TcbCredentials.prototype.secretKey = ""; + TcbCredentials.prototype.secretKey = '' - /** + /** * TcbCredentials token. * @member {string} token * @memberof AuthorizationInfo.TcbCredentials * @instance */ - TcbCredentials.prototype.token = ""; + TcbCredentials.prototype.token = '' - /** + /** * Creates a new TcbCredentials instance using the specified properties. * @function create * @memberof AuthorizationInfo.TcbCredentials @@ -4735,11 +4295,11 @@ $root.AuthorizationInfo = (function() { * @param {AuthorizationInfo.ITcbCredentials=} [properties] Properties to set * @returns {AuthorizationInfo.TcbCredentials} TcbCredentials instance */ - TcbCredentials.create = function create(properties) { - return new TcbCredentials(properties); - }; + TcbCredentials.create = function create(properties) { + return new TcbCredentials(properties) + } - /** + /** * Encodes the specified TcbCredentials message. Does not implicitly {@link AuthorizationInfo.TcbCredentials.verify|verify} messages. * @function encode * @memberof AuthorizationInfo.TcbCredentials @@ -4748,19 +4308,15 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TcbCredentials.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.secretId != null && message.hasOwnProperty("secretId")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.secretId); - if (message.secretKey != null && message.hasOwnProperty("secretKey")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.secretKey); - if (message.token != null && message.hasOwnProperty("token")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.token); - return writer; - }; - - /** + TcbCredentials.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.secretId != null && message.hasOwnProperty('secretId')) writer.uint32(/* id 1, wireType 2 = */10).string(message.secretId) + if (message.secretKey != null && message.hasOwnProperty('secretKey')) writer.uint32(/* id 2, wireType 2 = */18).string(message.secretKey) + if (message.token != null && message.hasOwnProperty('token')) writer.uint32(/* id 3, wireType 2 = */26).string(message.token) + return writer + } + + /** * Encodes the specified TcbCredentials message, length delimited. Does not implicitly {@link AuthorizationInfo.TcbCredentials.verify|verify} messages. * @function encodeDelimited * @memberof AuthorizationInfo.TcbCredentials @@ -4769,11 +4325,11 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - TcbCredentials.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + TcbCredentials.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a TcbCredentials message from the specified reader or buffer. * @function decode * @memberof AuthorizationInfo.TcbCredentials @@ -4784,31 +4340,31 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TcbCredentials.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.AuthorizationInfo.TcbCredentials(); + TcbCredentials.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.AuthorizationInfo.TcbCredentials() while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { + var tag = reader.uint32() + switch (tag >>> 3) { case 1: - message.secretId = reader.string(); - break; + message.secretId = reader.string() + break case 2: - message.secretKey = reader.string(); - break; + message.secretKey = reader.string() + break case 3: - message.token = reader.string(); - break; + message.token = reader.string() + break default: - reader.skipType(tag & 7); - break; - } + reader.skipType(tag & 7) + break + } } - return message; - }; + return message + } - /** + /** * Decodes a TcbCredentials message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof AuthorizationInfo.TcbCredentials @@ -4818,13 +4374,12 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - TcbCredentials.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + TcbCredentials.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a TcbCredentials message. * @function verify * @memberof AuthorizationInfo.TcbCredentials @@ -4832,22 +4387,15 @@ $root.AuthorizationInfo = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - TcbCredentials.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.secretId != null && message.hasOwnProperty("secretId")) - if (!$util.isString(message.secretId)) - return "secretId: string expected"; - if (message.secretKey != null && message.hasOwnProperty("secretKey")) - if (!$util.isString(message.secretKey)) - return "secretKey: string expected"; - if (message.token != null && message.hasOwnProperty("token")) - if (!$util.isString(message.token)) - return "token: string expected"; - return null; - }; - - /** + TcbCredentials.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.secretId != null && message.hasOwnProperty('secretId')) if (!$util.isString(message.secretId)) return 'secretId: string expected' + if (message.secretKey != null && message.hasOwnProperty('secretKey')) if (!$util.isString(message.secretKey)) return 'secretKey: string expected' + if (message.token != null && message.hasOwnProperty('token')) if (!$util.isString(message.token)) return 'token: string expected' + return null + } + + /** * Creates a TcbCredentials message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof AuthorizationInfo.TcbCredentials @@ -4855,20 +4403,16 @@ $root.AuthorizationInfo = (function() { * @param {Object.} object Plain object * @returns {AuthorizationInfo.TcbCredentials} TcbCredentials */ - TcbCredentials.fromObject = function fromObject(object) { - if (object instanceof $root.AuthorizationInfo.TcbCredentials) - return object; - var message = new $root.AuthorizationInfo.TcbCredentials(); - if (object.secretId != null) - message.secretId = String(object.secretId); - if (object.secretKey != null) - message.secretKey = String(object.secretKey); - if (object.token != null) - message.token = String(object.token); - return message; - }; - - /** + TcbCredentials.fromObject = function fromObject(object) { + if (object instanceof $root.AuthorizationInfo.TcbCredentials) return object + var message = new $root.AuthorizationInfo.TcbCredentials() + if (object.secretId != null) message.secretId = String(object.secretId) + if (object.secretKey != null) message.secretKey = String(object.secretKey) + if (object.token != null) message.token = String(object.token) + return message + } + + /** * Creates a plain object from a TcbCredentials message. Also converts values to other types if specified. * @function toObject * @memberof AuthorizationInfo.TcbCredentials @@ -4877,40 +4421,35 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - TcbCredentials.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; + TcbCredentials.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} if (options.defaults) { - object.secretId = ""; - object.secretKey = ""; - object.token = ""; + object.secretId = '' + object.secretKey = '' + object.token = '' } - if (message.secretId != null && message.hasOwnProperty("secretId")) - object.secretId = message.secretId; - if (message.secretKey != null && message.hasOwnProperty("secretKey")) - object.secretKey = message.secretKey; - if (message.token != null && message.hasOwnProperty("token")) - object.token = message.token; - return object; - }; + if (message.secretId != null && message.hasOwnProperty('secretId')) object.secretId = message.secretId + if (message.secretKey != null && message.hasOwnProperty('secretKey')) object.secretKey = message.secretKey + if (message.token != null && message.hasOwnProperty('token')) object.token = message.token + return object + } - /** + /** * Converts this TcbCredentials to JSON. * @function toJSON * @memberof AuthorizationInfo.TcbCredentials * @instance * @returns {Object.} JSON object */ - TcbCredentials.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return TcbCredentials; - })(); + TcbCredentials.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - AuthorizationInfo.WxParam = (function() { + return TcbCredentials + }()) + AuthorizationInfo.WxParam = (function () { /** * Properties of a WxParam. * @memberof AuthorizationInfo @@ -4920,7 +4459,7 @@ $root.AuthorizationInfo = (function() { * @property {string|null} [extJson] WxParam extJson */ - /** + /** * Constructs a new WxParam. * @memberof AuthorizationInfo * @classdesc Represents a WxParam. @@ -4928,38 +4467,35 @@ $root.AuthorizationInfo = (function() { * @constructor * @param {AuthorizationInfo.IWxParam=} [properties] Properties to set */ - function WxParam(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function WxParam(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * WxParam qbaseTicket. * @member {Uint8Array} qbaseTicket * @memberof AuthorizationInfo.WxParam * @instance */ - WxParam.prototype.qbaseTicket = $util.newBuffer([]); + WxParam.prototype.qbaseTicket = $util.newBuffer([]) - /** + /** * WxParam authUin. * @member {string} authUin * @memberof AuthorizationInfo.WxParam * @instance */ - WxParam.prototype.authUin = ""; + WxParam.prototype.authUin = '' - /** + /** * WxParam extJson. * @member {string} extJson * @memberof AuthorizationInfo.WxParam * @instance */ - WxParam.prototype.extJson = ""; + WxParam.prototype.extJson = '' - /** + /** * Creates a new WxParam instance using the specified properties. * @function create * @memberof AuthorizationInfo.WxParam @@ -4967,11 +4503,11 @@ $root.AuthorizationInfo = (function() { * @param {AuthorizationInfo.IWxParam=} [properties] Properties to set * @returns {AuthorizationInfo.WxParam} WxParam instance */ - WxParam.create = function create(properties) { - return new WxParam(properties); - }; + WxParam.create = function create(properties) { + return new WxParam(properties) + } - /** + /** * Encodes the specified WxParam message. Does not implicitly {@link AuthorizationInfo.WxParam.verify|verify} messages. * @function encode * @memberof AuthorizationInfo.WxParam @@ -4980,19 +4516,15 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WxParam.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.qbaseTicket != null && message.hasOwnProperty("qbaseTicket")) - writer.uint32(/* id 1, wireType 2 =*/10).bytes(message.qbaseTicket); - if (message.authUin != null && message.hasOwnProperty("authUin")) - writer.uint32(/* id 2, wireType 2 =*/18).string(message.authUin); - if (message.extJson != null && message.hasOwnProperty("extJson")) - writer.uint32(/* id 3, wireType 2 =*/26).string(message.extJson); - return writer; - }; - - /** + WxParam.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.qbaseTicket != null && message.hasOwnProperty('qbaseTicket')) writer.uint32(/* id 1, wireType 2 = */10).bytes(message.qbaseTicket) + if (message.authUin != null && message.hasOwnProperty('authUin')) writer.uint32(/* id 2, wireType 2 = */18).string(message.authUin) + if (message.extJson != null && message.hasOwnProperty('extJson')) writer.uint32(/* id 3, wireType 2 = */26).string(message.extJson) + return writer + } + + /** * Encodes the specified WxParam message, length delimited. Does not implicitly {@link AuthorizationInfo.WxParam.verify|verify} messages. * @function encodeDelimited * @memberof AuthorizationInfo.WxParam @@ -5001,11 +4533,11 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - WxParam.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + WxParam.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes a WxParam message from the specified reader or buffer. * @function decode * @memberof AuthorizationInfo.WxParam @@ -5016,31 +4548,31 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WxParam.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.AuthorizationInfo.WxParam(); + WxParam.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.AuthorizationInfo.WxParam() while (reader.pos < end) { - var tag = reader.uint32(); - switch (tag >>> 3) { + var tag = reader.uint32() + switch (tag >>> 3) { case 1: - message.qbaseTicket = reader.bytes(); - break; + message.qbaseTicket = reader.bytes() + break case 2: - message.authUin = reader.string(); - break; + message.authUin = reader.string() + break case 3: - message.extJson = reader.string(); - break; + message.extJson = reader.string() + break default: - reader.skipType(tag & 7); - break; - } + reader.skipType(tag & 7) + break + } } - return message; - }; + return message + } - /** + /** * Decodes a WxParam message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof AuthorizationInfo.WxParam @@ -5050,13 +4582,12 @@ $root.AuthorizationInfo = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - WxParam.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + WxParam.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies a WxParam message. * @function verify * @memberof AuthorizationInfo.WxParam @@ -5064,22 +4595,15 @@ $root.AuthorizationInfo = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - WxParam.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.qbaseTicket != null && message.hasOwnProperty("qbaseTicket")) - if (!(message.qbaseTicket && typeof message.qbaseTicket.length === "number" || $util.isString(message.qbaseTicket))) - return "qbaseTicket: buffer expected"; - if (message.authUin != null && message.hasOwnProperty("authUin")) - if (!$util.isString(message.authUin)) - return "authUin: string expected"; - if (message.extJson != null && message.hasOwnProperty("extJson")) - if (!$util.isString(message.extJson)) - return "extJson: string expected"; - return null; - }; - - /** + WxParam.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.qbaseTicket != null && message.hasOwnProperty('qbaseTicket')) if (!(message.qbaseTicket && typeof message.qbaseTicket.length === 'number' || $util.isString(message.qbaseTicket))) return 'qbaseTicket: buffer expected' + if (message.authUin != null && message.hasOwnProperty('authUin')) if (!$util.isString(message.authUin)) return 'authUin: string expected' + if (message.extJson != null && message.hasOwnProperty('extJson')) if (!$util.isString(message.extJson)) return 'extJson: string expected' + return null + } + + /** * Creates a WxParam message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof AuthorizationInfo.WxParam @@ -5087,23 +4611,19 @@ $root.AuthorizationInfo = (function() { * @param {Object.} object Plain object * @returns {AuthorizationInfo.WxParam} WxParam */ - WxParam.fromObject = function fromObject(object) { - if (object instanceof $root.AuthorizationInfo.WxParam) - return object; - var message = new $root.AuthorizationInfo.WxParam(); - if (object.qbaseTicket != null) - if (typeof object.qbaseTicket === "string") - $util.base64.decode(object.qbaseTicket, message.qbaseTicket = $util.newBuffer($util.base64.length(object.qbaseTicket)), 0); - else if (object.qbaseTicket.length) - message.qbaseTicket = object.qbaseTicket; - if (object.authUin != null) - message.authUin = String(object.authUin); - if (object.extJson != null) - message.extJson = String(object.extJson); - return message; - }; + WxParam.fromObject = function fromObject(object) { + if (object instanceof $root.AuthorizationInfo.WxParam) return object + var message = new $root.AuthorizationInfo.WxParam() + if (object.qbaseTicket != null) { + if (typeof object.qbaseTicket === 'string') $util.base64.decode(object.qbaseTicket, message.qbaseTicket = $util.newBuffer($util.base64.length(object.qbaseTicket)), 0) + else if (object.qbaseTicket.length) message.qbaseTicket = object.qbaseTicket + } + if (object.authUin != null) message.authUin = String(object.authUin) + if (object.extJson != null) message.extJson = String(object.extJson) + return message + } - /** + /** * Creates a plain object from a WxParam message. Also converts values to other types if specified. * @function toObject * @memberof AuthorizationInfo.WxParam @@ -5112,57 +4632,50 @@ $root.AuthorizationInfo = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - WxParam.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; + WxParam.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} if (options.defaults) { - if (options.bytes === String) - object.qbaseTicket = ""; - else { - object.qbaseTicket = []; - if (options.bytes !== Array) - object.qbaseTicket = $util.newBuffer(object.qbaseTicket); - } - object.authUin = ""; - object.extJson = ""; + if (options.bytes === String) object.qbaseTicket = '' + else { + object.qbaseTicket = [] + if (options.bytes !== Array) object.qbaseTicket = $util.newBuffer(object.qbaseTicket) + } + object.authUin = '' + object.extJson = '' } - if (message.qbaseTicket != null && message.hasOwnProperty("qbaseTicket")) - object.qbaseTicket = options.bytes === String ? $util.base64.encode(message.qbaseTicket, 0, message.qbaseTicket.length) : options.bytes === Array ? Array.prototype.slice.call(message.qbaseTicket) : message.qbaseTicket; - if (message.authUin != null && message.hasOwnProperty("authUin")) - object.authUin = message.authUin; - if (message.extJson != null && message.hasOwnProperty("extJson")) - object.extJson = message.extJson; - return object; - }; + if (message.qbaseTicket != null && message.hasOwnProperty('qbaseTicket')) object.qbaseTicket = options.bytes === String ? $util.base64.encode(message.qbaseTicket, 0, message.qbaseTicket.length) : options.bytes === Array ? Array.prototype.slice.call(message.qbaseTicket) : message.qbaseTicket + if (message.authUin != null && message.hasOwnProperty('authUin')) object.authUin = message.authUin + if (message.extJson != null && message.hasOwnProperty('extJson')) object.extJson = message.extJson + return object + } - /** + /** * Converts this WxParam to JSON. * @function toJSON * @memberof AuthorizationInfo.WxParam * @instance * @returns {Object.} JSON object */ - WxParam.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return WxParam; - })(); + WxParam.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } - return AuthorizationInfo; -})(); + return WxParam + }()) -$root.ApiOptions = (function() { + return AuthorizationInfo + }()) - /** + $root.ApiOptions = (function () { + /** * Properties of an ApiOptions. * @exports IApiOptions * @interface IApiOptions * @property {string|null} [appid] ApiOptions appid */ - /** + /** * Constructs a new ApiOptions. * @exports ApiOptions * @classdesc Represents an ApiOptions. @@ -5170,22 +4683,19 @@ $root.ApiOptions = (function() { * @constructor * @param {IApiOptions=} [properties] Properties to set */ - function ApiOptions(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } + function ApiOptions(properties) { + if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]] + } - /** + /** * ApiOptions appid. * @member {string} appid * @memberof ApiOptions * @instance */ - ApiOptions.prototype.appid = ""; + ApiOptions.prototype.appid = '' - /** + /** * Creates a new ApiOptions instance using the specified properties. * @function create * @memberof ApiOptions @@ -5193,11 +4703,11 @@ $root.ApiOptions = (function() { * @param {IApiOptions=} [properties] Properties to set * @returns {ApiOptions} ApiOptions instance */ - ApiOptions.create = function create(properties) { - return new ApiOptions(properties); - }; + ApiOptions.create = function create(properties) { + return new ApiOptions(properties) + } - /** + /** * Encodes the specified ApiOptions message. Does not implicitly {@link ApiOptions.verify|verify} messages. * @function encode * @memberof ApiOptions @@ -5206,15 +4716,13 @@ $root.ApiOptions = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiOptions.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.appid != null && message.hasOwnProperty("appid")) - writer.uint32(/* id 1, wireType 2 =*/10).string(message.appid); - return writer; - }; + ApiOptions.encode = function encode(message, writer) { + if (!writer) writer = $Writer.create() + if (message.appid != null && message.hasOwnProperty('appid')) writer.uint32(/* id 1, wireType 2 = */10).string(message.appid) + return writer + } - /** + /** * Encodes the specified ApiOptions message, length delimited. Does not implicitly {@link ApiOptions.verify|verify} messages. * @function encodeDelimited * @memberof ApiOptions @@ -5223,11 +4731,11 @@ $root.ApiOptions = (function() { * @param {$protobuf.Writer} [writer] Writer to encode to * @returns {$protobuf.Writer} Writer */ - ApiOptions.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; + ApiOptions.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer).ldelim() + } - /** + /** * Decodes an ApiOptions message from the specified reader or buffer. * @function decode * @memberof ApiOptions @@ -5238,25 +4746,25 @@ $root.ApiOptions = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiOptions.decode = function decode(reader, length) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.ApiOptions(); - while (reader.pos < end) { - var tag = reader.uint32(); + ApiOptions.decode = function decode(reader, length) { + if (!(reader instanceof $Reader)) reader = $Reader.create(reader) + var end = length === undefined ? reader.len : reader.pos + length; var + message = new $root.ApiOptions() + while (reader.pos < end) { + var tag = reader.uint32() switch (tag >>> 3) { - case 1: - message.appid = reader.string(); - break; - default: - reader.skipType(tag & 7); - break; + case 1: + message.appid = reader.string() + break + default: + reader.skipType(tag & 7) + break } + } + return message } - return message; - }; - /** + /** * Decodes an ApiOptions message from the specified reader or buffer, length delimited. * @function decodeDelimited * @memberof ApiOptions @@ -5266,13 +4774,12 @@ $root.ApiOptions = (function() { * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ - ApiOptions.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; + ApiOptions.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof $Reader)) reader = new $Reader(reader) + return this.decode(reader, reader.uint32()) + } - /** + /** * Verifies an ApiOptions message. * @function verify * @memberof ApiOptions @@ -5280,16 +4787,13 @@ $root.ApiOptions = (function() { * @param {Object.} message Plain object to verify * @returns {string|null} `null` if valid, otherwise the reason why it is not */ - ApiOptions.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.appid != null && message.hasOwnProperty("appid")) - if (!$util.isString(message.appid)) - return "appid: string expected"; - return null; - }; + ApiOptions.verify = function verify(message) { + if (typeof message !== 'object' || message === null) return 'object expected' + if (message.appid != null && message.hasOwnProperty('appid')) if (!$util.isString(message.appid)) return 'appid: string expected' + return null + } - /** + /** * Creates an ApiOptions message from a plain object. Also converts values to their respective internal types. * @function fromObject * @memberof ApiOptions @@ -5297,16 +4801,14 @@ $root.ApiOptions = (function() { * @param {Object.} object Plain object * @returns {ApiOptions} ApiOptions */ - ApiOptions.fromObject = function fromObject(object) { - if (object instanceof $root.ApiOptions) - return object; - var message = new $root.ApiOptions(); - if (object.appid != null) - message.appid = String(object.appid); - return message; - }; + ApiOptions.fromObject = function fromObject(object) { + if (object instanceof $root.ApiOptions) return object + var message = new $root.ApiOptions() + if (object.appid != null) message.appid = String(object.appid) + return message + } - /** + /** * Creates a plain object from an ApiOptions message. Also converts values to other types if specified. * @function toObject * @memberof ApiOptions @@ -5315,192 +4817,181 @@ $root.ApiOptions = (function() { * @param {$protobuf.IConversionOptions} [options] Conversion options * @returns {Object.} Plain object */ - ApiOptions.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.appid = ""; - if (message.appid != null && message.hasOwnProperty("appid")) - object.appid = message.appid; - return object; - }; - - /** + ApiOptions.toObject = function toObject(message, options) { + if (!options) options = {} + var object = {} + if (options.defaults) object.appid = '' + if (message.appid != null && message.hasOwnProperty('appid')) object.appid = message.appid + return object + } + + /** * Converts this ApiOptions to JSON. * @function toJSON * @memberof ApiOptions * @instance * @returns {Object.} JSON object */ - ApiOptions.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - - return ApiOptions; -})(); - -module.exports = $root; + ApiOptions.prototype.toJSON = function toJSON() { + return this.constructor.toObject(this, $protobuf.util.toJSONOptions) + } + return ApiOptions + }()) -/***/ }), + module.exports = $root + /***/ }), -/***/ "./src/utils/assert.ts": -/*!*****************************!*\ + /***/ './src/utils/assert.ts': + /*! *****************************!*\ !*** ./src/utils/assert.ts ***! - \*****************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.assertObjectNotEmpty = exports.assertRequiredParam = exports.assertObjectOptionalType = exports.assertType = exports.validObjectOptionalType = exports.validType = exports.sameType = void 0; -const type_1 = __webpack_require__(/*! ./type */ "./src/utils/type.ts"); -const error_1 = __webpack_require__(/*! ./error */ "./src/utils/error.ts"); -const error_config_1 = __webpack_require__(/*! config/error.config */ "./src/config/error.config.ts"); -function sameType(input, ref, name) { - function sameTypeImpl(input, ref, name) { - const inputType = type_1.getType(input); - const refType = type_1.getType(ref); - if (inputType !== refType) { - return `${name} should be ${refType} instead of ${inputType}; `; - } - let errors = ''; - switch (inputType) { + \**************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.assertObjectNotEmpty = exports.assertRequiredParam = exports.assertObjectOptionalType = exports.assertType = exports.validObjectOptionalType = exports.validType = exports.sameType = void 0 + const type_1 = __webpack_require__(/*! ./type */ './src/utils/type.ts') + const error_1 = __webpack_require__(/*! ./error */ './src/utils/error.ts') + const error_config_1 = __webpack_require__(/*! config/error.config */ './src/config/error.config.ts') + function sameType(input, ref, name) { + function sameTypeImpl(input, ref, name) { + const inputType = type_1.getType(input) + const refType = type_1.getType(ref) + if (inputType !== refType) { + return `${name} should be ${refType} instead of ${inputType}; ` + } + let errors = '' + switch (inputType) { case 'object': { - for (const key in ref) { - errors += sameTypeImpl(input[key], ref[key], `${name}.${key}`); - } - break; + for (const key in ref) { + errors += sameTypeImpl(input[key], ref[key], `${name}.${key}`) + } + break } case 'array': { - for (let i = 0; i < ref.length; i++) { - errors += sameTypeImpl(input[i], ref[i], `${name}[${i}]`); - } - break; + for (let i = 0; i < ref.length; i++) { + errors += sameTypeImpl(input[i], ref[i], `${name}[${i}]`) + } + break } default: { - break; + break } + } + return errors } - return errors; - } - const error = sameTypeImpl(input, ref, name); - return { - passed: !error, - reason: error, - }; -} -exports.sameType = sameType; -function validType(input, ref, name = 'parameter') { - function validTypeImpl(input, ref, name) { - const inputType = type_1.getType(input); - const refType = type_1.getType(ref); - if (refType === 'string') { + const error = sameTypeImpl(input, ref, name) + return { + passed: !error, + reason: error, + } + } + exports.sameType = sameType + function validType(input, ref, name = 'parameter') { + function validTypeImpl(input, ref, name) { + const inputType = type_1.getType(input) + const refType = type_1.getType(ref) + if (refType === 'string') { if (inputType !== ref) { - return `${name} should be ${ref} instead of ${inputType};`; + return `${name} should be ${ref} instead of ${inputType};` } - return ''; - } - else { + return '' + } else { if (inputType !== refType) { - return `${name} should be ${refType} instead of ${inputType}; `; + return `${name} should be ${refType} instead of ${inputType}; ` } - let errors = ''; + let errors = '' switch (inputType) { - case 'object': { - for (const key in ref) { - errors += validTypeImpl(input[key], ref[key], `${name}.${key}`); - } - break; - } - case 'array': { - for (let i = 0; i < ref.length; i++) { - errors += validTypeImpl(input[i], ref[i], `${name}[${i}]`); - } - break; + case 'object': { + for (const key in ref) { + errors += validTypeImpl(input[key], ref[key], `${name}.${key}`) } - default: { - break; + break + } + case 'array': { + for (let i = 0; i < ref.length; i++) { + errors += validTypeImpl(input[i], ref[i], `${name}[${i}]`) } + break + } + default: { + break + } } - return errors; + return errors + } } - } - const error = validTypeImpl(input, ref, name); - return { - passed: !error, - reason: error, - }; -} -exports.validType = validType; -function validObjectOptionalType(input, ref, name = 'parameter') { - function validImpl(input, ref, name) { - const inputType = type_1.getType(input); - const refType = type_1.getType(ref); - if (refType !== 'object') - return ''; - if (inputType === 'object') { + const error = validTypeImpl(input, ref, name) + return { + passed: !error, + reason: error, + } + } + exports.validType = validType + function validObjectOptionalType(input, ref, name = 'parameter') { + function validImpl(input, ref, name) { + const inputType = type_1.getType(input) + const refType = type_1.getType(ref) + if (refType !== 'object') return '' + if (inputType === 'object') { for (const key in input) { - const val = input[key]; - if (val === undefined || key === null) { - continue; - } - const assertResult = validType(val, ref[key], `${name}.${key}`); - return assertResult.passed ? '' : assertResult.reason; + const val = input[key] + if (val === undefined || key === null) { + continue + } + const assertResult = validType(val, ref[key], `${name}.${key}`) + return assertResult.passed ? '' : assertResult.reason } + } else { + return `${name} should be object instead of ${inputType}` + } + return '' } - else { - return `${name} should be object instead of ${inputType}`; + const error = validImpl(input, ref, name) + return { + passed: !error, + reason: error, } - return ''; - } - const error = validImpl(input, ref, name); - return { - passed: !error, - reason: error, - }; -} -exports.validObjectOptionalType = validObjectOptionalType; -function assertType(param, ref, name = 'parameter', ErrorClass = error_1.CloudSDKError) { - // check param validity - let paramCheckResult = validType(param, ref, name); - if (!paramCheckResult.passed) { - throw new ErrorClass({ + } + exports.validObjectOptionalType = validObjectOptionalType + function assertType(param, ref, name = 'parameter', ErrorClass = error_1.CloudSDKError) { + // check param validity + const paramCheckResult = validType(param, ref, name) + if (!paramCheckResult.passed) { + throw new ErrorClass({ errMsg: paramCheckResult.reason, - }); - } -} -exports.assertType = assertType; -function assertObjectOptionalType(param, ref, name = 'parameter', ErrorClass = error_1.CloudSDKError) { - // check param validity - let paramCheckResult = validObjectOptionalType(param, ref, name); - if (!paramCheckResult.passed) { - throw new ErrorClass({ + }) + } + } + exports.assertType = assertType + function assertObjectOptionalType(param, ref, name = 'parameter', ErrorClass = error_1.CloudSDKError) { + // check param validity + const paramCheckResult = validObjectOptionalType(param, ref, name) + if (!paramCheckResult.passed) { + throw new ErrorClass({ errMsg: paramCheckResult.reason, - }); - } -} -exports.assertObjectOptionalType = assertObjectOptionalType; -function assertRequiredParam(param, name, funcName, ErrorClass = error_1.CloudSDKError) { - if (param === undefined || param === null) { - throw new ErrorClass({ + }) + } + } + exports.assertObjectOptionalType = assertObjectOptionalType + function assertRequiredParam(param, name, funcName, ErrorClass = error_1.CloudSDKError) { + if (param === undefined || param === null) { + throw new ErrorClass({ errMsg: `parameter ${name} of function ${funcName} must be provided`, - }); - } -} -exports.assertRequiredParam = assertRequiredParam; -function assertObjectNotEmpty({ target, name, ErrorClass = error_1.CloudSDKError }) { - if (Object.keys(target).length === 0) { - throw new ErrorClass({ + }) + } + } + exports.assertRequiredParam = assertRequiredParam + function assertObjectNotEmpty({target, name, ErrorClass = error_1.CloudSDKError}) { + if (Object.keys(target).length === 0) { + throw new ErrorClass({ errCode: error_config_1.ERR_CODE.SDK_API_PARAMETER_ERROR, errMsg: `${name} must not be empty` - }); - } -} -exports.assertObjectNotEmpty = assertObjectNotEmpty; -/* + }) + } + } + exports.assertObjectNotEmpty = assertObjectNotEmpty + /* export function constructTypeRef(typeDef: any): any { const type = getType(typeDef) @@ -5515,362 +5006,320 @@ export function constructTypeRef(typeDef: any): any { } } -*/ - +*/ + /***/ }), -/***/ }), - -/***/ "./src/utils/error.ts": -/*!****************************!*\ + /***/ './src/utils/error.ts': + /*! ****************************!*\ !*** ./src/utils/error.ts ***! - \****************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toSDKError = exports.returnAsFinalCloudSDKError = exports.returnAsCloudSDKError = exports.isSDKError = exports.createError = exports.CloudSDKError = void 0; -const type_1 = __webpack_require__(/*! ./type */ "./src/utils/type.ts"); -const error_config_1 = __webpack_require__(/*! config/error.config */ "./src/config/error.config.ts"); -/** + \*************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.toSDKError = exports.returnAsFinalCloudSDKError = exports.returnAsCloudSDKError = exports.isSDKError = exports.createError = exports.CloudSDKError = void 0 + const type_1 = __webpack_require__(/*! ./type */ './src/utils/type.ts') + const error_config_1 = __webpack_require__(/*! config/error.config */ './src/config/error.config.ts') + /** * @deprecated */ -class CloudSDKError extends Error { - constructor(options) { - super(options.errMsg); - this.errCode = -1; - Object.defineProperties(this, { + class CloudSDKError extends Error { + constructor(options) { + super(options.errMsg) + this.errCode = -1 + Object.defineProperties(this, { message: { - get() { - return `errCode: ${this.errCode} ${error_config_1.ERR_CODE[this.errCode] || ''} | errMsg: ` + this.errMsg; - }, - set(msg) { - this.errMsg = msg; - } + get() { + return `errCode: ${this.errCode} ${error_config_1.ERR_CODE[this.errCode] || ''} | errMsg: ` + this.errMsg + }, + set(msg) { + this.errMsg = msg + } } - }); - this.errCode = options.errCode || -1; - this.errMsg = options.errMsg; - } - get message() { - return `errCode: ${this.errCode} | errMsg: ` + this.errMsg; - } - set message(msg) { - this.errMsg = msg; - } -} -exports.CloudSDKError = CloudSDKError; -/** + }) + this.errCode = options.errCode || -1 + this.errMsg = options.errMsg + } + + get message() { + return `errCode: ${this.errCode} | errMsg: ` + this.errMsg + } + + set message(msg) { + this.errMsg = msg + } + } + exports.CloudSDKError = CloudSDKError + /** * @deprecated */ -function createError({ errCode = 1, errMsg = '', errClass = CloudSDKError, } = {}) { - return new errClass({ - errCode, - errMsg, - }); -} -exports.createError = createError; -function isSDKError(error) { - return error && (error instanceof Error) && type_1.isString(error.errMsg); -} -exports.isSDKError = isSDKError; -/** + function createError({errCode = 1, errMsg = '', errClass = CloudSDKError} = {}) { + return new errClass({ + errCode, + errMsg, + }) + } + exports.createError = createError + function isSDKError(error) { + return error && (error instanceof Error) && type_1.isString(error.errMsg) + } + exports.isSDKError = isSDKError + /** * @deprecated */ -function returnAsCloudSDKError(err, appendMsg = '') { - if (err) { - if (isSDKError(err)) { + function returnAsCloudSDKError(err, appendMsg = '') { + if (err) { + if (isSDKError(err)) { if (appendMsg) { - err.errMsg += '; ' + appendMsg; + err.errMsg += '; ' + appendMsg } - return err; - } - const errCode = err ? err.errCode : undefined; - const errMsg = (err && err.errMsg || err.toString() || 'unknown error') + '; ' + appendMsg; - return new CloudSDKError({ + return err + } + const errCode = err ? err.errCode : undefined + const errMsg = (err && err.errMsg || err.toString() || 'unknown error') + '; ' + appendMsg + return new CloudSDKError({ errCode, errMsg, - }); - } - return new CloudSDKError({ - errMsg: appendMsg - }); -} -exports.returnAsCloudSDKError = returnAsCloudSDKError; -/** + }) + } + return new CloudSDKError({ + errMsg: appendMsg + }) + } + exports.returnAsCloudSDKError = returnAsCloudSDKError + /** * @deprecated */ -function returnAsFinalCloudSDKError(err, apiName) { - return toSDKError(err, apiName); - // if (err && isSDKError(err)) { - // return err - // } - // const e = returnAsCloudSDKError(err, `at ${apiName} api; `) - // e.errMsg = apiFailMsg(apiName, e.errMsg) - // return e -} -exports.returnAsFinalCloudSDKError = returnAsFinalCloudSDKError; -function toSDKError(e, apiName) { - if (e) { - if (isSDKError(e)) { - return e; - } - const prefix = `${apiName}:fail `; - let err; - if (e instanceof Error) { - e.message = `${prefix}${e.message}`; - e.stack = e.stack.slice(0, 7) + prefix + e.stack.slice(7); - err = e; - err.errCode = -1; - } - else if (typeof e === 'string') { - err = new Error(`${prefix}${e}`); - err.errCode = -1; - } - else { + function returnAsFinalCloudSDKError(err, apiName) { + return toSDKError(err, apiName) + // if (err && isSDKError(err)) { + // return err + // } + // const e = returnAsCloudSDKError(err, `at ${apiName} api; `) + // e.errMsg = apiFailMsg(apiName, e.errMsg) + // return e + } + exports.returnAsFinalCloudSDKError = returnAsFinalCloudSDKError + function toSDKError(e, apiName) { + if (e) { + if (isSDKError(e)) { + return e + } + const prefix = `${apiName}:fail ` + let err + if (e instanceof Error) { + e.message = `${prefix}${e.message}` + e.stack = e.stack.slice(0, 7) + prefix + e.stack.slice(7) + err = e + err.errCode = -1 + } else if (typeof e === 'string') { + err = new Error(`${prefix}${e}`) + err.errCode = -1 + } else { // errCode + errMsg - const errMsg = e.errMsg || ''; - err = new Error(`${apiName}:fail ${e.errCode} ${error_config_1.ERR_CODE[e.errCode] || ''}. ${errMsg}`); - err.errCode = e.errCode || -1; + const errMsg = e.errMsg || '' + err = new Error(`${apiName}:fail ${e.errCode} ${error_config_1.ERR_CODE[e.errCode] || ''}. ${errMsg}`) + err.errCode = e.errCode || -1 + } + err.errMsg = err.message + '' + return err } - err.errMsg = err.message + ''; - return err; - } - const err = new Error(`${apiName}:fail`); - err.errCode = -1; - err.errMsg = err.message + ''; - return err; -} -exports.toSDKError = toSDKError; - - -/***/ }), - -/***/ "./src/utils/msg.ts": -/*!**************************!*\ + const err = new Error(`${apiName}:fail`) + err.errCode = -1 + err.errMsg = err.message + '' + return err + } + exports.toSDKError = toSDKError + /***/ }), + + /***/ './src/utils/msg.ts': + /*! **************************!*\ !*** ./src/utils/msg.ts ***! - \**************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.apiFailMsg = exports.apiCancelMsg = exports.apiSuccessMsg = void 0; -function apiSuccessMsg(apiName) { - return `${apiName}:ok`; -} -exports.apiSuccessMsg = apiSuccessMsg; -function apiCancelMsg(apiName, msg) { - return `${apiName}:cancel ${msg}`; -} -exports.apiCancelMsg = apiCancelMsg; -function apiFailMsg(apiName, msg) { - return `${apiName}:fail ${msg}`; -} -exports.apiFailMsg = apiFailMsg; - - -/***/ }), - -/***/ "./src/utils/symbol.ts": -/*!*****************************!*\ + \************************* */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.apiFailMsg = exports.apiCancelMsg = exports.apiSuccessMsg = void 0 + function apiSuccessMsg(apiName) { + return `${apiName}:ok` + } + exports.apiSuccessMsg = apiSuccessMsg + function apiCancelMsg(apiName, msg) { + return `${apiName}:cancel ${msg}` + } + exports.apiCancelMsg = apiCancelMsg + function apiFailMsg(apiName, msg) { + return `${apiName}:fail ${msg}` + } + exports.apiFailMsg = apiFailMsg + /***/ }), + + /***/ './src/utils/symbol.ts': + /*! *****************************!*\ !*** ./src/utils/symbol.ts ***! - \*****************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InternalSymbol = void 0; -const _symbols = []; -const __internalMark__ = {}; -class HiddenSymbol { - constructor(target) { - Object.defineProperties(this, { + \**************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.InternalSymbol = void 0 + const _symbols = [] + const __internalMark__ = {} + class HiddenSymbol { + constructor(target) { + Object.defineProperties(this, { target: { - enumerable: false, - writable: false, - configurable: false, - value: target, + enumerable: false, + writable: false, + configurable: false, + value: target, }, - }); - } -} -class InternalSymbol extends HiddenSymbol { - constructor(target, __mark__) { - if (__mark__ !== __internalMark__) { - throw new TypeError('InternalSymbol cannot be constructed with new operator'); + }) } - super(target); - } - static for(target) { - for (let i = 0, len = _symbols.length; i < len; i++) { + } + class InternalSymbol extends HiddenSymbol { + constructor(target, __mark__) { + if (__mark__ !== __internalMark__) { + throw new TypeError('InternalSymbol cannot be constructed with new operator') + } + super(target) + } + + static for(target) { + for (let i = 0, len = _symbols.length; i < len; i++) { if (_symbols[i].target === target) { - return _symbols[i].instance; + return _symbols[i].instance } - } - const symbol = new InternalSymbol(target, __internalMark__); - _symbols.push({ + } + const symbol = new InternalSymbol(target, __internalMark__) + _symbols.push({ target, instance: symbol, - }); - return symbol; - } -} -exports.InternalSymbol = InternalSymbol; -exports.default = InternalSymbol; - - -/***/ }), + }) + return symbol + } + } + exports.InternalSymbol = InternalSymbol + exports.default = InternalSymbol + /***/ }), -/***/ "./src/utils/type.ts": -/*!***************************!*\ + /***/ './src/utils/type.ts': + /*! ***************************!*\ !*** ./src/utils/type.ts ***! - \***************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isPlainObject = exports.isInternalObject = exports.isBuffer = exports.isDate = exports.isArray = exports.isFunction = exports.isPromise = exports.isNumber = exports.isString = exports.isObject = exports.getType = void 0; -const symbol_1 = __webpack_require__(/*! ./symbol */ "./src/utils/symbol.ts"); -exports.getType = (x) => Object.prototype.toString.call(x).slice(8, -1).toLowerCase(); -exports.isObject = (x) => exports.getType(x) === 'object'; -exports.isString = (x) => exports.getType(x) === 'string'; -exports.isNumber = (x) => exports.getType(x) === 'number'; -exports.isPromise = (x) => exports.getType(x) === 'promise'; -exports.isFunction = (x) => typeof x === 'function'; -exports.isArray = (x) => Array.isArray(x); -exports.isDate = (x) => exports.getType(x) === 'date'; -exports.isBuffer = (x) => Buffer.isBuffer(x); -exports.isInternalObject = (x) => x && (x._internalType instanceof symbol_1.InternalSymbol); -exports.isPlainObject = (obj) => { - if (typeof obj !== 'object' || obj === null) - return false; - let proto = obj; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(obj) === proto; -}; - - -/***/ }), + \************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.isPlainObject = exports.isInternalObject = exports.isBuffer = exports.isDate = exports.isArray = exports.isFunction = exports.isPromise = exports.isNumber = exports.isString = exports.isObject = exports.getType = void 0 + const symbol_1 = __webpack_require__(/*! ./symbol */ './src/utils/symbol.ts') + exports.getType = (x) => Object.prototype.toString.call(x).slice(8, -1).toLowerCase() + exports.isObject = (x) => exports.getType(x) === 'object' + exports.isString = (x) => exports.getType(x) === 'string' + exports.isNumber = (x) => exports.getType(x) === 'number' + exports.isPromise = (x) => exports.getType(x) === 'promise' + exports.isFunction = (x) => typeof x === 'function' + exports.isArray = (x) => Array.isArray(x) + exports.isDate = (x) => exports.getType(x) === 'date' + exports.isBuffer = (x) => Buffer.isBuffer(x) + exports.isInternalObject = (x) => x && (x._internalType instanceof symbol_1.InternalSymbol) + exports.isPlainObject = (obj) => { + if (typeof obj !== 'object' || obj === null) return false + let proto = obj + while (Object.getPrototypeOf(proto) !== null) { + proto = Object.getPrototypeOf(proto) + } + return Object.getPrototypeOf(obj) === proto + } + /***/ }), -/***/ "./src/utils/utils.ts": -/*!****************************!*\ + /***/ './src/utils/utils.ts': + /*! ****************************!*\ !*** ./src/utils/utils.ts ***! - \****************************/ -/*! no static exports found */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMergedAPIConfig = exports.getServiceConfigFromDefaultConfig = exports.getEnvFromAPIConfig = exports.getEnvFromCloudConfig = exports.isSCFEnvReady = exports.convertCase = void 0; -const type_1 = __webpack_require__(/*! ./type */ "./src/utils/type.ts"); -const signature_1 = __webpack_require__(/*! api/utils/api/signature */ "./src/api/utils/api/signature.ts"); -const ignoreInConvert = (input) => input instanceof signature_1.MidasSignature; -exports.convertCase = (input, options) => { - const { from, to, recursive } = options; - if (type_1.isString(input)) { - if (from === 'camelcase' && to === 'snakecase') { - return input.replace(/[A-Z]/g, (match, ind) => `${ind ? '_' : ''}${match.toLowerCase()}`); - } - else if (from === 'snakecase' && to === 'camelcase') { - return input.replace(/_[a-z]/g, (match, ind) => `${match[1].toUpperCase()}`); - } - } - else if (type_1.isObject(input)) { - return ignoreInConvert(input) ? input : convertObject(input); - } - else if (type_1.isArray(input)) { - const array = []; - for (const item of input) { + \*************************** */ + /*! no static exports found */ + /***/ (function (module, exports, __webpack_require__) { + Object.defineProperty(exports, '__esModule', {value: true}) + exports.getMergedAPIConfig = exports.getServiceConfigFromDefaultConfig = exports.getEnvFromAPIConfig = exports.getEnvFromCloudConfig = exports.isSCFEnvReady = exports.convertCase = void 0 + const type_1 = __webpack_require__(/*! ./type */ './src/utils/type.ts') + const signature_1 = __webpack_require__(/*! api/utils/api/signature */ './src/api/utils/api/signature.ts') + const ignoreInConvert = (input) => input instanceof signature_1.MidasSignature + exports.convertCase = (input, options) => { + const {from, to, recursive} = options + if (type_1.isString(input)) { + if (from === 'camelcase' && to === 'snakecase') { + return input.replace(/[A-Z]/g, (match, ind) => `${ind ? '_' : ''}${match.toLowerCase()}`) + } else if (from === 'snakecase' && to === 'camelcase') { + return input.replace(/_[a-z]/g, (match, ind) => `${match[1].toUpperCase()}`) + } + } else if (type_1.isObject(input)) { + return ignoreInConvert(input) ? input : convertObject(input) + } else if (type_1.isArray(input)) { + const array = [] + for (const item of input) { if (type_1.isObject(item)) { - array.push(convertObject(item)); - } - else if (type_1.isArray(item)) { - if (options.recursive) { - array.push(exports.convertCase(item, options)); - } - else { - array.push(item); - } - } - else { - array.push(item); + array.push(convertObject(item)) + } else if (type_1.isArray(item)) { + if (options.recursive) { + array.push(exports.convertCase(item, options)) + } else { + array.push(item) + } + } else { + array.push(item) } - } - return array; - } - else - return input; - function convertObject(input) { - const data = Object.assign({}, input); - for (const key in data) { - const val = recursive && (type_1.isObject(data[key]) || type_1.isArray(data[key])) ? exports.convertCase(data[key], options) : data[key]; - const convertedKey = exports.convertCase(key, options); - data[convertedKey] = val; + } + return array + } else return input + function convertObject(input) { + const data = {...input} + for (const key in data) { + const val = recursive && (type_1.isObject(data[key]) || type_1.isArray(data[key])) ? exports.convertCase(data[key], options) : data[key] + const convertedKey = exports.convertCase(key, options) + data[convertedKey] = val if (convertedKey !== key) { - delete data[key]; + delete data[key] } + } + return data } - return data; - } -}; -exports.isSCFEnvReady = () => Boolean(process.env.TCB_ENV); -exports.getEnvFromCloudConfig = (config, serviceName = 'default') => { - const env = config.env[serviceName] || config.env.default; - return env; -}; -exports.getEnvFromAPIConfig = (apiConfig, cloudConfig, serviceName = 'default') => { - if (apiConfig && apiConfig.env) { - return apiConfig.env; - } - return exports.getEnvFromCloudConfig(cloudConfig, serviceName); -}; -exports.getServiceConfigFromDefaultConfig = (defaultConfig, serviceName = 'default') => { - return Object.assign(Object.assign({}, defaultConfig), { env: exports.getEnvFromCloudConfig(defaultConfig, serviceName) }); -}; -exports.getMergedAPIConfig = (defaultConfig, newConfig, serviceName = 'default') => { - const merged = Object.assign(Object.assign({}, defaultConfig), newConfig); - if (newConfig && newConfig.env) { - merged.env = newConfig.env; - } - else { - merged.env = exports.getEnvFromCloudConfig(defaultConfig, serviceName); - } - return merged; -}; - - -/***/ }), + } + exports.isSCFEnvReady = () => Boolean(process.env.TCB_ENV) + exports.getEnvFromCloudConfig = (config, serviceName = 'default') => { + const env = config.env[serviceName] || config.env.default + return env + } + exports.getEnvFromAPIConfig = (apiConfig, cloudConfig, serviceName = 'default') => { + if (apiConfig && apiConfig.env) { + return apiConfig.env + } + return exports.getEnvFromCloudConfig(cloudConfig, serviceName) + } + exports.getServiceConfigFromDefaultConfig = (defaultConfig, serviceName = 'default') => ({...defaultConfig, env: exports.getEnvFromCloudConfig(defaultConfig, serviceName)}) + exports.getMergedAPIConfig = (defaultConfig, newConfig, serviceName = 'default') => { + const merged = {...defaultConfig, ...newConfig} + if (newConfig && newConfig.env) { + merged.env = newConfig.env + } else { + merged.env = exports.getEnvFromCloudConfig(defaultConfig, serviceName) + } + return merged + } + /***/ }), -/***/ "crypto": -/*!*************************!*\ + /***/ crypto: + /*! *************************!*\ !*** external "crypto" ***! - \*************************/ -/*! no static exports found */ -/***/ (function(module, exports) { - -module.exports = require("crypto"); - -/***/ }), - -/***/ "protobufjs/minimal": -/*!*************************************!*\ + \************************ */ + /*! no static exports found */ + /***/ (function (module, exports) { + module.exports = require('crypto') + /***/ }), + + /***/ 'protobufjs/minimal': + /*! *************************************!*\ !*** external "protobufjs/minimal" ***! - \*************************************/ -/*! no static exports found */ -/***/ (function(module, exports) { - -module.exports = require("protobufjs/minimal"); - -/***/ }) + \************************************ */ + /*! no static exports found */ + /***/ (function (module, exports) { + module.exports = require('protobufjs/minimal') + /***/ }) -/******/ }); \ No newline at end of file + /** *** */})) diff --git a/gulpfile.js b/gulpfile.js index ccd846f6..60ab8e3d 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/_commons/0.js b/miniprogram/_commons/0.js index 9d62f7b5..87527356 100644 --- a/miniprogram/_commons/0.js +++ b/miniprogram/_commons/0.js @@ -1,144 +1,147 @@ -var globalThis = this, self = this; -module.exports = -/******/ (function(modules) { // webpackBootstrap -/******/ function webpackLoadCallback(loadModules) { -/******/ var i = 0, j, k = 0; -/******/ var deferredModules = [], result; -/******/ var module, chunkIds, chunkId, moreModules, executeModules, moduleId; -/******/ var deferredModule, fulfilled, depId; -/******/ -/******/ for (; i < loadModules.length; ++i) { -/******/ module = loadModules[i]; -/******/ chunkIds = module.ids; -/******/ moreModules = module.modules; -/******/ executeModules = module.entries || []; -/******/ -/******/ for(j = 0; j < chunkIds.length; j++) { -/******/ chunkId = chunkIds[j]; -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ -/******/ deferredModules.push.apply(deferredModules, executeModules || []); -/******/ } -/******/ -/******/ for(; k < deferredModules.length; k++) { -/******/ deferredModule = deferredModules[k]; -/******/ fulfilled = true; -/******/ for(j = 1; j < deferredModule.length; j++) { -/******/ depId = deferredModule[j]; -/******/ if(installedChunks[depId] !== 0) fulfilled = false; -/******/ } -/******/ if(fulfilled) { -/******/ deferredModules.splice(k--, 1); -/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); -/******/ } -/******/ } -/******/ -/******/ return result; -/******/ }; -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded chunks -/******/ // "0" means "already loaded" -/******/ var installedChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // 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 }); -/******/ } -/******/ }; -/******/ -/******/ // 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, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // uncaught error handler for webpack runtime -/******/ __webpack_require__.oe = function(err) { -/******/ process.nextTick(function() { -/******/ throw err; // catch this error by using import().catch() -/******/ }); -/******/ }; -/******/ -/******/ -/******/ // return load module function -/******/ return webpackLoadCallback; -/******/ }) -/************************************************************************/ -/******/ ([]); -// # sourceMappingURL=0.js.map \ No newline at end of file +const globalThis = this; const + self = this +module.exports = +/** *** */ (function (modules) { // webpackBootstrap + /** *** */ function webpackLoadCallback(loadModules) { + /** *** */ let i = 0; let j; let + k = 0 + /** *** */ const deferredModules = []; let + result + /** *** */ let module; let chunkIds; let chunkId; let moreModules; let executeModules; let + moduleId + /** *** */ let deferredModule; let fulfilled; let + depId + /** *** */ + /** *** */ for (; i < loadModules.length; ++i) { + /** *** */ module = loadModules[i] + /** *** */ chunkIds = module.ids + /** *** */ moreModules = module.modules + /** *** */ executeModules = module.entries || [] + /** *** */ + /** *** */ for (j = 0; j < chunkIds.length; j++) { + /** *** */ chunkId = chunkIds[j] + /** *** */ installedChunks[chunkId] = 0 + /** *** */ } + /** *** */ for (moduleId in moreModules) { + /** *** */ if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { + /** *** */ modules[moduleId] = moreModules[moduleId] + /** *** */ } + /** *** */ } + /** *** */ + /** *** */ deferredModules.push.apply(deferredModules, executeModules || []) + /** *** */ } + /** *** */ + /** *** */ for (; k < deferredModules.length; k++) { + /** *** */ deferredModule = deferredModules[k] + /** *** */ fulfilled = true + /** *** */ for (j = 1; j < deferredModule.length; j++) { + /** *** */ depId = deferredModule[j] + /** *** */ if (installedChunks[depId] !== 0) fulfilled = false + /** *** */ } + /** *** */ if (fulfilled) { + /** *** */ deferredModules.splice(k--, 1) + /** *** */ result = __webpack_require__(__webpack_require__.s = deferredModule[0]) + /** *** */ } + /** *** */ } + /** *** */ + /** *** */ return result + /** *** */ } + /** *** */ + /** *** */ // The module cache + /** *** */ const installedModules = {} + /** *** */ + /** *** */ // object to store loaded chunks + /** *** */ // "0" means "already loaded" + /** *** */ var installedChunks = { + /** *** */ 0: 0 + /** *** */} + /** *** */ + /** *** */ // The require function + /** *** */ function __webpack_require__(moduleId) { + /** *** */ + /** *** */ // Check if module is in cache + /** *** */ if (installedModules[moduleId]) { + /** *** */ return installedModules[moduleId].exports + /** *** */ } + /** *** */ // Create a new module (and put it into the cache) + /** *** */ const module = installedModules[moduleId] = { + /** *** */ i: moduleId, + /** *** */ l: false, + /** *** */ exports: {} + /** *** */} + /** *** */ + /** *** */ // Execute the module function + /** *** */ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__) + /** *** */ + /** *** */ // Flag the module as loaded + /** *** */ module.l = true + /** *** */ + /** *** */ // Return the exports of the module + /** *** */ return module.exports + /** *** */ } + /** *** */ + /** *** */ + /** *** */ // expose the modules object (__webpack_modules__) + /** *** */ __webpack_require__.m = modules + /** *** */ + /** *** */ // expose the module cache + /** *** */ __webpack_require__.c = installedModules + /** *** */ + /** *** */ // 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}) + /** *** */ } + /** *** */ } + /** *** */ + /** *** */ // 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, '__esModule', {value: true}) + /** *** */ } + /** *** */ + /** *** */ // create a fake namespace object + /** *** */ // mode & 1: value is a module id, require it + /** *** */ // mode & 2: merge all properties of value into the ns + /** *** */ // mode & 4: return value when already ns object + /** *** */ // mode & 8|1: behave like require + /** *** */ __webpack_require__.t = function (value, mode) { + /** *** */ if (mode & 1) value = __webpack_require__(value) + /** *** */ if (mode & 8) return value + /** *** */ 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}) + /** *** */ 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 + /** *** */ } + /** *** */ + /** *** */ // getDefaultExport function for compatibility with non-harmony modules + /** *** */ __webpack_require__.n = function (module) { + /** *** */ const getter = module && module.__esModule + /** *** */ ? function getDefault() { return module.default } + /** *** */ : function getModuleExports() { return module } + /** *** */ __webpack_require__.d(getter, 'a', getter) + /** *** */ return getter + /** *** */ } + /** *** */ + /** *** */ // Object.prototype.hasOwnProperty.call + /** *** */ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property) } + /** *** */ + /** *** */ // __webpack_public_path__ + /** *** */ __webpack_require__.p = '' + /** *** */ + /** *** */ // uncaught error handler for webpack runtime + /** *** */ __webpack_require__.oe = function (err) { + /** *** */ process.nextTick(function () { + /** *** */ throw err // catch this error by using import().catch() + /** *** */ }) + /** *** */ } + /** *** */ + /** *** */ + /** *** */ // return load module function + /** *** */ return webpackLoadCallback + /** *** */ }([])) +// # sourceMappingURL=0.js.map 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..47f95b36 100644 --- a/miniprogram/app.js +++ b/miniprogram/app.js @@ -45,10 +45,19 @@ 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') @@ -58,7 +67,6 @@ App({ }) }, - onShow(opts) { console.log('App Show', opts) console.log('USER_DATA_PATH', wx.env.USER_DATA_PATH) @@ -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/app.json b/miniprogram/app.json index 49c73295..8fe0b29f 100644 --- a/miniprogram/app.json +++ b/miniprogram/app.json @@ -44,11 +44,14 @@ "pages/view/sticky/sticky-section/sticky-section", "pages/view/movable-view/movable-view", "pages/view/cover-view/cover-view", + "pages/view/match-media/match-media", + "pages/view/page-container/page-container", "pages/view/sticky/sticky", "pages/content/text/text", "pages/content/icon/icon", "pages/content/progress/progress", "pages/content/rich-text/rich-text", + "pages/content/selection/selection", "pages/form/button/button", "pages/form/checkbox/checkbox", "pages/form/form/form", diff --git a/miniprogram/component/navigation-bar/navigation-bar.js b/miniprogram/component/navigation-bar/navigation-bar.js index 4335baa6..36d75f9f 100644 --- a/miniprogram/component/navigation-bar/navigation-bar.js +++ b/miniprogram/component/navigation-bar/navigation-bar.js @@ -1,82 +1,93 @@ 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' + console.log('rect', rect) + if (wx.getDeviceInfo) { + const deviceInfo = wx.getDeviceInfo() + const ios = !!(deviceInfo.system.toLowerCase().search('ios') + 1) + this.setData({ + ios + }) + } + if (wx.getAppBaseInfo) { + const appBaseInfo = wx.getAppBaseInfo() + this.setData({ + theme: appBaseInfo.theme || 'light', + }) + } + if (wx.getWindowInfo) { + const windowInfo = wx.getWindowInfo() + console.log('windowInfo', windowInfo) + this.setData({ + statusBarHeight: windowInfo.statusBarHeight, + navBarHeight: rect.bottom - rect.top + 10 + (isSkyline ? 0 : windowInfo.statusBarHeight), + innerWidth: isSupport ? `width:${rect.left}px` : '', + innerPaddingRight: isSupport + ? `padding-right:${windowInfo.windowWidth - rect.left}px` + : '', + leftWidth: isSupport ? `width:${windowInfo.windowWidth - rect.left}px` : '', + }) + } if (wx.onThemeChange) { wx.onThemeChange(({theme}) => { this.setData({theme}) @@ -89,42 +100,41 @@ 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 + 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) } - 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..4afd5fe8 100644 --- a/miniprogram/components/navigation-bar/index.js +++ b/miniprogram/components/navigation-bar/index.js @@ -38,33 +38,33 @@ Component({ }, attached() { - const isSupport = !!wx.getMenuButtonBoundingClientRect; - const rect = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null; + 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 ios = !!(res.system.toLowerCase().search('ios') + 1) + const sideWidth = isSupport ? res.windowWidth - rect.left : 0 this.setData({ ios, sideWidth: this.data.sideWidth || sideWidth, statusBarHeight: res.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..c9842aeb 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/components/popup/index.wxss b/miniprogram/components/popup/index.wxss index 2f6824bc..e12d7a62 100644 --- a/miniprogram/components/popup/index.wxss +++ b/miniprogram/components/popup/index.wxss @@ -7,13 +7,14 @@ root-portal { .popup { position: absolute; bottom: 0; + top: 0; z-index: 5000; display: flex; flex-direction: row; justify-content: center; align-items: center; width: 100vw; - height: 200px; + /* height: 200px; */ background: rgba(51, 51, 51, 0.65); opacity: 1; transform: scale3d(1, 1, 1); diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/cell-group.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/cell-group.js index 966ceece..344c9a04 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/cell-group.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/cell-group.js @@ -1,43 +1,46 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-cell-group`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-cell-group` let CellGroup = class CellGroup extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-title`]; - this.relations = { - '../cell/cell': { - type: 'child', - linked() { - this.updateLastChid(); - }, - unlinked() { - this.updateLastChid(); - }, - }, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.methods = { - updateLastChid() { - const items = this.$children; - items.forEach((child, index) => child.setData({ isLastChild: index === items.length - 1 })); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-title`] + this.relations = { + '../cell/cell': { + type: 'child', + linked() { + this.updateLastChid() + }, + unlinked() { + this.updateLastChid() + }, + }, } -}; + this.properties = props + this.data = { + prefix, + classPrefix: name, + } + this.methods = { + updateLastChid() { + const items = this.$children + items.forEach((child, index) => child.setData({isLastChild: index === items.length - 1})) + }, + } + } +} CellGroup = __decorate([ - wxComponent() -], CellGroup); -export default CellGroup; + wxComponent() +], CellGroup) +export default CellGroup diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/props.js index c8d887e8..b43d430d 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/props.js @@ -1,17 +1,17 @@ const props = { - bordered: { - type: Boolean, - }, - externalClasses: { - type: Array, - }, - theme: { - type: String, - value: 'default', - }, - title: { - type: String, - value: '', - }, -}; -export default props; + bordered: { + type: Boolean, + }, + externalClasses: { + type: Array, + }, + theme: { + type: String, + value: 'default', + }, + title: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell-group/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/cell.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/cell.js index c7c5ec5e..a58aee5b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/cell.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/cell.js @@ -1,75 +1,81 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { calcIcon } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-cell`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {calcIcon} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-cell` let Cell = class Cell extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-title`, - `${prefix}-class-description`, - `${prefix}-class-note`, - `${prefix}-class-hover`, - `${prefix}-class-image`, - `${prefix}-class-left`, - `${prefix}-class-left-icon`, - `${prefix}-class-center`, - `${prefix}-class-right`, - `${prefix}-class-right-icon`, - ]; - this.relations = { - '../cell-group/cell-group': { - type: 'parent', - }, - }; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - isLastChild: false, - }; - this.observers = { - leftIcon(v) { - this.setIcon('_leftIcon', v, ''); - }, - rightIcon(v) { - this.setIcon('_rightIcon', v, ''); - }, - arrow(v) { - this.setIcon('_arrow', v, 'chevron-right'); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-title`, + `${prefix}-class-description`, + `${prefix}-class-note`, + `${prefix}-class-hover`, + `${prefix}-class-image`, + `${prefix}-class-left`, + `${prefix}-class-left-icon`, + `${prefix}-class-center`, + `${prefix}-class-right`, + `${prefix}-class-right-icon`, + ] + this.relations = { + '../cell-group/cell-group': { + type: 'parent', + }, } - setIcon(name, value, defaultValue) { - this.setData({ - [name]: calcIcon(value, defaultValue), - }); + this.options = { + multipleSlots: true, } - onClick(e) { - this.triggerEvent('click', e.detail); - this.jumpLink(); + this.properties = props + this.data = { + prefix, + classPrefix: name, + isLastChild: false, } - jumpLink(urlKey = 'url', link = 'jumpType') { - const url = this.data[urlKey]; - const jumpType = this.data[link]; - if (url) { - wx[jumpType]({ url }); - } + this.observers = { + leftIcon(v) { + this.setIcon('_leftIcon', v, '') + }, + rightIcon(v) { + this.setIcon('_rightIcon', v, '') + }, + arrow(v) { + this.setIcon('_arrow', v, 'chevron-right') + }, } -}; + } + + setIcon(name, value, defaultValue) { + this.setData({ + [name]: calcIcon(value, defaultValue), + }) + } + + onClick(e) { + this.triggerEvent('click', e.detail) + this.jumpLink() + } + + jumpLink(urlKey = 'url', link = 'jumpType') { + const url = this.data[urlKey] + const jumpType = this.data[link] + if (url) { + wx[jumpType]({url}) + } + } +} Cell = __decorate([ - wxComponent() -], Cell); -export default Cell; + wxComponent() +], Cell) +export default Cell diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/props.js index c5382532..c7347992 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/props.js @@ -1,48 +1,48 @@ const props = { - align: { - type: String, - value: 'middle', - }, - arrow: { - type: null, - value: false, - }, - bordered: { - type: Boolean, - value: true, - }, - description: { - type: String, - }, - hover: { - type: Boolean, - }, - image: { - type: String, - }, - jumpType: { - type: String, - value: 'navigateTo', - }, - leftIcon: { - type: null, - }, - note: { - type: String, - }, - required: { - type: Boolean, - value: false, - }, - rightIcon: { - type: null, - }, - title: { - type: String, - }, - url: { - type: String, - value: '', - }, -}; -export default props; + align: { + type: String, + value: 'middle', + }, + arrow: { + type: null, + value: false, + }, + bordered: { + type: Boolean, + value: true, + }, + description: { + type: String, + }, + hover: { + type: Boolean, + }, + image: { + type: String, + }, + jumpType: { + type: String, + value: 'navigateTo', + }, + leftIcon: { + type: null, + }, + note: { + type: String, + }, + required: { + type: Boolean, + value: false, + }, + rightIcon: { + type: null, + }, + title: { + type: String, + }, + url: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/cell/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/cell/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/col/col.js b/miniprogram/packageAPI/components/tdesign-miniprogram/col/col.js index cbaecddc..ebe5cce9 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/col/col.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/col/col.js @@ -1,31 +1,34 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-col`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-col` let Col = class Col extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.relations = { - '../row/row': { - type: 'parent', - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.properties = props + this.data = { + prefix, + classPrefix: name, } -}; + this.relations = { + '../row/row': { + type: 'parent', + }, + } + } +} Col = __decorate([ - wxComponent() -], Col); -export default Col; + wxComponent() +], Col) +export default Col diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/col/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/col/props.js index 05857f37..3b0f74ec 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/col/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/col/props.js @@ -1,9 +1,9 @@ const props = { - offset: { - type: null, - }, - span: { - type: null, - }, -}; -export default props; + offset: { + type: null, + }, + span: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/col/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/col/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/col/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/col/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/collapse-panel.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/collapse-panel.js index 27b3214f..2ce529a3 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/collapse-panel.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/collapse-panel.js @@ -1,95 +1,96 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { getRect } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-collapse-panel`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {getRect} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-collapse-panel` let CollapsePanel = class CollapsePanel extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`, `${prefix}-class-header`]; - this.options = { - multipleSlots: true, - }; - this.relations = { - '../collapse/collapse': { - type: 'ancestor', - linked(target) { - const { value, expandIcon, disabled } = target.properties; - this.setData({ - ultimateExpandIcon: this.properties.expandIcon == null ? expandIcon : this.properties.expandIcon, - ultimateDisabled: this.properties.disabled == null ? disabled : this.properties.disabled, - }); - this.updateExpanded(value); - }, - }, - }; - this.properties = props; - this.data = { - prefix, - expanded: false, - classPrefix: name, - classBasePrefix: prefix, - ultimateExpandIcon: false, - ultimateDisabled: false, - }; - this.observers = { - disabled(v) { - this.setData({ ultimateDisabled: !!v }); - }, - }; - this.methods = { - updateExpanded(activeValues = []) { - if (!this.$parent) { - return; - } - const { value } = this.properties; - const { defaultExpandAll } = this.$parent.data; - const expanded = defaultExpandAll ? !this.data.expanded : activeValues.includes(value); - if (expanded === this.properties.expanded) - return; - this.setData({ expanded }); - this.updateStyle(expanded); - }, - updateStyle(expanded) { - return getRect(this, `.${name}__content`) - .then((rect) => rect.height) - .then((height) => { - const animation = wx.createAnimation({ - duration: 0, - timingFunction: 'ease-in-out', - }); - if (expanded) { - animation.height(height).top(0).step({ duration: 300 }).height('auto').step(); - } - else { - animation.height(height).top(1).step({ duration: 1 }).height(0).step({ duration: 300 }); - } - this.setData({ animation: animation.export() }); - }); - }, - onClick() { - const { ultimateDisabled } = this.data; - const { value } = this.properties; - if (ultimateDisabled) - return; - if (this.$parent.data.defaultExpandAll) { - this.updateExpanded(); - } - else { - this.$parent.switch(value); - } - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`, `${prefix}-class-header`] + this.options = { + multipleSlots: true, } -}; + this.relations = { + '../collapse/collapse': { + type: 'ancestor', + linked(target) { + const {value, expandIcon, disabled} = target.properties + this.setData({ + ultimateExpandIcon: this.properties.expandIcon == null ? expandIcon : this.properties.expandIcon, + ultimateDisabled: this.properties.disabled == null ? disabled : this.properties.disabled, + }) + this.updateExpanded(value) + }, + }, + } + this.properties = props + this.data = { + prefix, + expanded: false, + classPrefix: name, + classBasePrefix: prefix, + ultimateExpandIcon: false, + ultimateDisabled: false, + } + this.observers = { + disabled(v) { + this.setData({ultimateDisabled: !!v}) + }, + } + this.methods = { + updateExpanded(activeValues = []) { + if (!this.$parent) { + return + } + const {value} = this.properties + const {defaultExpandAll} = this.$parent.data + const expanded = defaultExpandAll ? !this.data.expanded : activeValues.includes(value) + if (expanded === this.properties.expanded) return + this.setData({expanded}) + this.updateStyle(expanded) + }, + updateStyle(expanded) { + return getRect(this, `.${name}__content`) + .then((rect) => rect.height) + .then((height) => { + const animation = wx.createAnimation({ + duration: 0, + timingFunction: 'ease-in-out', + }) + if (expanded) { + animation.height(height).top(0).step({duration: 300}).height('auto') + .step() + } else { + animation.height(height).top(1).step({duration: 1}).height(0) + .step({duration: 300}) + } + this.setData({animation: animation.export()}) + }) + }, + onClick() { + const {ultimateDisabled} = this.data + const {value} = this.properties + if (ultimateDisabled) return + if (this.$parent.data.defaultExpandAll) { + this.updateExpanded() + } else { + this.$parent.switch(value) + } + }, + } + } +} CollapsePanel = __decorate([ - wxComponent() -], CollapsePanel); -export default CollapsePanel; + wxComponent() +], CollapsePanel) +export default CollapsePanel diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/props.js index 429cd0ae..8bca06be 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/props.js @@ -1,33 +1,33 @@ const props = { - content: { - type: String, - }, - disabled: { - type: null, - value: undefined, - }, - expandIcon: { - type: null, - value: undefined, - }, - externalClasses: { - type: Array, - }, - header: { - type: String, - }, - headerLeftIcon: { - type: String, - }, - headerRightContent: { - type: String, - }, - placement: { - type: String, - value: 'bottom', - }, - value: { - type: null, - }, -}; -export default props; + content: { + type: String, + }, + disabled: { + type: null, + value: undefined, + }, + expandIcon: { + type: null, + value: undefined, + }, + externalClasses: { + type: Array, + }, + header: { + type: String, + }, + headerLeftIcon: { + type: String, + }, + headerRightContent: { + type: String, + }, + placement: { + type: String, + value: 'bottom', + }, + value: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse-panel/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/collapse.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/collapse.js index cf6631f1..66f6a7b4 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/collapse.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/collapse.js @@ -1,61 +1,63 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-collapse`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-collapse` let Collapse = class Collapse extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.relations = { - '../collapse-panel/collapse-panel': { - type: 'descendant', - }, - }; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.observers = { - 'value, expandMutex '() { - this.updateExpanded(); - }, - }; - this.methods = { - updateExpanded() { - this.$children.forEach((child) => { - child.updateExpanded(this.properties.value); - }); - }, - switch(panelValue) { - const { expandMutex, value: activeValues } = this.properties; - let value = []; - const hit = activeValues.indexOf(panelValue); - if (hit > -1) { - value = activeValues.filter((item) => item !== panelValue); - } - else { - value = expandMutex ? [panelValue] : activeValues.concat(panelValue); - } - this._trigger('change', { value }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.relations = { + '../collapse-panel/collapse-panel': { + type: 'descendant', + }, } -}; + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.properties = props + this.data = { + prefix, + classPrefix: name, + } + this.observers = { + 'value, expandMutex ': function () { + this.updateExpanded() + }, + } + this.methods = { + updateExpanded() { + this.$children.forEach((child) => { + child.updateExpanded(this.properties.value) + }) + }, + switch(panelValue) { + const {expandMutex, value: activeValues} = this.properties + let value = [] + const hit = activeValues.indexOf(panelValue) + if (hit > -1) { + value = activeValues.filter((item) => item !== panelValue) + } else { + value = expandMutex ? [panelValue] : activeValues.concat(panelValue) + } + this._trigger('change', {value}) + }, + } + } +} Collapse = __decorate([ - wxComponent() -], Collapse); -export default Collapse; + wxComponent() +], Collapse) +export default Collapse diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/index.js index 53d34475..3eb7d727 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/index.js @@ -1,3 +1,3 @@ -export { default as Collapse } from './collapse'; -export * from './type'; -export * from './props'; +export {default as Collapse} from './collapse' +export * from './type' +export * from './props' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/props.js index 3dfb2420..5a47ac11 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/props.js @@ -1,30 +1,30 @@ const props = { - defaultExpandAll: { - type: Boolean, - value: false, - }, - disabled: { - type: Boolean, - }, - expandIcon: { - type: Boolean, - value: true, - }, - expandMutex: { - type: Boolean, - value: false, - }, - theme: { - type: String, - value: 'default', - }, - value: { - type: Array, - value: null, - }, - defaultValue: { - type: Array, - value: [], - }, -}; -export default props; + defaultExpandAll: { + type: Boolean, + value: false, + }, + disabled: { + type: Boolean, + }, + expandIcon: { + type: Boolean, + value: true, + }, + expandMutex: { + type: Boolean, + value: false, + }, + theme: { + type: String, + value: 'default', + }, + value: { + type: Array, + value: null, + }, + defaultValue: { + type: Array, + value: [], + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/collapse/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/bus.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/bus.js index 5a6c8898..ec2b18c9 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/bus.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/bus.js @@ -1,22 +1,24 @@ export default class Bus { - constructor() { - this.listeners = new Map(); - this.emitted = new Set(); + constructor() { + this.listeners = new Map() + this.emitted = new Set() + } + + on(evtName, listener) { + if (this.emitted.has(evtName)) { + listener() + return } - on(evtName, listener) { - if (this.emitted.has(evtName)) { - listener(); - return; - } - const target = this.listeners.get(evtName) || []; - target.push(listener); - this.listeners.set(evtName, target); - } - emit(evtName) { - const listeners = this.listeners.get(evtName); - if (listeners) { - listeners.forEach((func) => func()); - } - this.emitted.add(evtName); + const target = this.listeners.get(evtName) || [] + target.push(listener) + this.listeners.set(evtName, target) + } + + emit(evtName) { + const listeners = this.listeners.get(evtName) + if (listeners) { + listeners.forEach((func) => func()) } + this.emitted.add(evtName) + } } diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/common.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/common.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/common.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/common.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/component.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/component.js index 4e01a69e..2d8e29c9 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/component.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/component.js @@ -1,5 +1,5 @@ const TComponent = (options) => { - options.options = Object.assign({ multipleSlots: true, addGlobalClass: true }, options.options); - return Component(options); -}; -export default TComponent; + options.options = {multipleSlots: true, addGlobalClass: true, ...options.options} + return Component(options) +} +export default TComponent diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/config.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/config.js index c0dfab2b..30db7900 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/config.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/config.js @@ -1,4 +1,4 @@ export default { - prefix: "t", -}; -export const prefix = "t"; + prefix: 't', +} +export const prefix = 't' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/index.js index 0d35176c..c965ce52 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/index.js @@ -1,128 +1,125 @@ -import { getDateRect, isSameDate, getMonthDateRect, isValidDate, getDate } from '../date'; +import { + getDateRect, isSameDate, getMonthDateRect, isValidDate, getDate +} from '../date' + export default class TCalendar { - constructor(options = {}) { - this.type = 'single'; - Object.assign(this, options); - if (!this.minDate) - this.minDate = getDate(); - if (!this.maxDate) - this.maxDate = getDate(6); + constructor(options = {}) { + this.type = 'single' + Object.assign(this, options) + if (!this.minDate) this.minDate = getDate() + if (!this.maxDate) this.maxDate = getDate(6) + } + + getTrimValue() { + const {value, type} = this + const format = (val) => { + if (val instanceof Date) return val + if (typeof val === 'number') return new Date(val) + return new Date() } - getTrimValue() { - const { value, type } = this; - const format = (val) => { - if (val instanceof Date) - return val; - if (typeof val === 'number') - return new Date(val); - return new Date(); - }; - if (type === 'single' && isValidDate(value)) - return format(value); - if (type === 'multiple' || type === 'range') { - if (Array.isArray(value)) { - const isValid = value.every((item) => isValidDate(item)); - return isValid ? value.map((item) => format(item)) : []; - } - return []; - } + if (type === 'single' && isValidDate(value)) return format(value) + if (type === 'multiple' || type === 'range') { + if (Array.isArray(value)) { + const isValid = value.every((item) => isValidDate(item)) + return isValid ? value.map((item) => format(item)) : [] + } + return [] } - getDays() { - const raw = '日一二三四五六'; - const ans = []; - let i = this.firstDayOfWeek % 7; - while (ans.length < 7) { - ans.push(raw[i]); - i = (i + 1) % 7; - } - return ans; + } + + getDays() { + const raw = '日一二三四五六' + const ans = [] + let i = this.firstDayOfWeek % 7 + while (ans.length < 7) { + ans.push(raw[i]) + i = (i + 1) % 7 } - getMonths() { - const ans = []; - const selectedDate = this.getTrimValue(); - const { minDate, maxDate, type, format } = this; - let { year: minYear, month: minMonth, time: minTime } = getDateRect(minDate); - const { year: maxYear, month: maxMonth, time: maxTime } = getDateRect(maxDate); - const calcType = (year, month, date) => { - const curDate = new Date(year, month, date, 23, 59, 59); - if (type === 'single' && selectedDate) { - if (isSameDate({ year, month, date }, selectedDate)) - return 'selected'; - } - if (type === 'multiple' && selectedDate) { - const hit = selectedDate.some((item) => isSameDate({ year, month, date }, item)); - if (hit) { - return 'selected'; - } - } - if (type === 'range' && selectedDate) { - if (Array.isArray(selectedDate)) { - const [startDate, endDate] = selectedDate; - if (startDate && isSameDate({ year, month, date }, startDate)) - return 'start'; - if (endDate && isSameDate({ year, month, date }, endDate)) - return 'end'; - if (startDate && endDate && curDate.getTime() > startDate.getTime() && curDate.getTime() < endDate.getTime()) - return 'centre'; - } - } - const minCurDate = new Date(year, month, date, 0, 0, 0); - if (curDate.getTime() < minTime || minCurDate.getTime() > maxTime) { - return 'disabled'; - } - return ''; - }; - while (minYear < maxYear || (minYear === maxYear && minMonth <= maxMonth)) { - const target = getMonthDateRect(new Date(minYear, minMonth, 1)); - const months = []; - for (let i = 1; i <= 31; i++) { - if (i > target.lastDate) - break; - const dateObj = { - date: new Date(minYear, minMonth, i), - day: i, - type: calcType(minYear, minMonth, i), - }; - months.push(format ? format(dateObj) : dateObj); - } - ans.push({ - year: minYear, - month: minMonth, - months, - weekdayOfFirstDay: target.weekdayOfFirstDay, - }); - const curDate = getDateRect(new Date(minYear, minMonth + 1, 1)); - minYear = curDate.year; - minMonth = curDate.month; + return ans + } + + getMonths() { + const ans = [] + const selectedDate = this.getTrimValue() + const { + minDate, maxDate, type, format + } = this + let {year: minYear, month: minMonth, time: minTime} = getDateRect(minDate) + const {year: maxYear, month: maxMonth, time: maxTime} = getDateRect(maxDate) + const calcType = (year, month, date) => { + const curDate = new Date(year, month, date, 23, 59, 59) + if (type === 'single' && selectedDate) { + if (isSameDate({year, month, date}, selectedDate)) return 'selected' + } + if (type === 'multiple' && selectedDate) { + const hit = selectedDate.some((item) => isSameDate({year, month, date}, item)) + if (hit) { + return 'selected' } - return ans; - } - select({ cellType, year, month, date }) { - const { type } = this; - const selectedDate = this.getTrimValue(); - if (cellType === 'disabled') - return; - const selected = new Date(year, month, date); - this.value = selected; - if (type === 'range' && Array.isArray(selectedDate)) { - if (selectedDate.length === 1 && selected > selectedDate[0]) { - this.value = [selectedDate[0], selected]; - } - else { - this.value = [selected]; - } + } + if (type === 'range' && selectedDate) { + if (Array.isArray(selectedDate)) { + const [startDate, endDate] = selectedDate + if (startDate && isSameDate({year, month, date}, startDate)) return 'start' + if (endDate && isSameDate({year, month, date}, endDate)) return 'end' + if (startDate && endDate && curDate.getTime() > startDate.getTime() && curDate.getTime() < endDate.getTime()) return 'centre' } - else if (type === 'multiple' && Array.isArray(selectedDate)) { - const newVal = [...selectedDate]; - const index = selectedDate.findIndex((item) => isSameDate(item, selected)); - if (index > -1) { - newVal.splice(index, 1); - } - else { - newVal.push(selected); - } - this.value = newVal; + } + const minCurDate = new Date(year, month, date, 0, 0, 0) + if (curDate.getTime() < minTime || minCurDate.getTime() > maxTime) { + return 'disabled' + } + return '' + } + while (minYear < maxYear || (minYear === maxYear && minMonth <= maxMonth)) { + const target = getMonthDateRect(new Date(minYear, minMonth, 1)) + const months = [] + for (let i = 1; i <= 31; i++) { + if (i > target.lastDate) break + const dateObj = { + date: new Date(minYear, minMonth, i), + day: i, + type: calcType(minYear, minMonth, i), } - return this.value; + months.push(format ? format(dateObj) : dateObj) + } + ans.push({ + year: minYear, + month: minMonth, + months, + weekdayOfFirstDay: target.weekdayOfFirstDay, + }) + const curDate = getDateRect(new Date(minYear, minMonth + 1, 1)) + minYear = curDate.year + minMonth = curDate.month + } + return ans + } + + select({ + cellType, year, month, date + }) { + const {type} = this + const selectedDate = this.getTrimValue() + if (cellType === 'disabled') return + const selected = new Date(year, month, date) + this.value = selected + if (type === 'range' && Array.isArray(selectedDate)) { + if (selectedDate.length === 1 && selected > selectedDate[0]) { + this.value = [selectedDate[0], selected] + } else { + this.value = [selected] + } + } else if (type === 'multiple' && Array.isArray(selectedDate)) { + const newVal = [...selectedDate] + const index = selectedDate.findIndex((item) => isSameDate(item, selected)) + if (index > -1) { + newVal.splice(index, 1) + } else { + newVal.push(selected) + } + this.value = newVal } + return this.value + } } diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/calendar/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js index d6273beb..7532cbfd 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js @@ -1,57 +1,57 @@ export const rgb2cmyk = (red, green, blue) => { - let computedC = 0; - let computedM = 0; - let computedY = 0; - let computedK = 0; - const r = parseInt(`${red}`.replace(/\s/g, ''), 10); - const g = parseInt(`${green}`.replace(/\s/g, ''), 10); - const b = parseInt(`${blue}`.replace(/\s/g, ''), 10); - if (r === 0 && g === 0 && b === 0) { - computedK = 1; - return [0, 0, 0, 1]; - } - computedC = 1 - r / 255; - computedM = 1 - g / 255; - computedY = 1 - b / 255; - const minCMY = Math.min(computedC, Math.min(computedM, computedY)); - computedC = (computedC - minCMY) / (1 - minCMY); - computedM = (computedM - minCMY) / (1 - minCMY); - computedY = (computedY - minCMY) / (1 - minCMY); - computedK = minCMY; - return [computedC, computedM, computedY, computedK]; -}; + let computedC = 0 + let computedM = 0 + let computedY = 0 + let computedK = 0 + const r = parseInt(`${red}`.replace(/\s/g, ''), 10) + const g = parseInt(`${green}`.replace(/\s/g, ''), 10) + const b = parseInt(`${blue}`.replace(/\s/g, ''), 10) + if (r === 0 && g === 0 && b === 0) { + computedK = 1 + return [0, 0, 0, 1] + } + computedC = 1 - r / 255 + computedM = 1 - g / 255 + computedY = 1 - b / 255 + const minCMY = Math.min(computedC, Math.min(computedM, computedY)) + computedC = (computedC - minCMY) / (1 - minCMY) + computedM = (computedM - minCMY) / (1 - minCMY) + computedY = (computedY - minCMY) / (1 - minCMY) + computedK = minCMY + return [computedC, computedM, computedY, computedK] +} export const cmyk2rgb = (cyan, magenta, yellow, black) => { - let c = cyan / 100; - let m = magenta / 100; - let y = yellow / 100; - const k = black / 100; - c = c * (1 - k) + k; - m = m * (1 - k) + k; - y = y * (1 - k) + k; - let r = 1 - c; - let g = 1 - m; - let b = 1 - y; - r = Math.round(255 * r); - g = Math.round(255 * g); - b = Math.round(255 * b); - return { - r, - g, - b, - }; -}; -const REG_CMYK_STRING = /cmyk\((\d+%?),(\d+%?),(\d+%?),(\d+%?)\)/; -const toNumber = (str) => Math.max(0, Math.min(255, parseInt(str, 10))); + let c = cyan / 100 + let m = magenta / 100 + let y = yellow / 100 + const k = black / 100 + c = c * (1 - k) + k + m = m * (1 - k) + k + y = y * (1 - k) + k + let r = 1 - c + let g = 1 - m + let b = 1 - y + r = Math.round(255 * r) + g = Math.round(255 * g) + b = Math.round(255 * b) + return { + r, + g, + b, + } +} +const REG_CMYK_STRING = /cmyk\((\d+%?),(\d+%?),(\d+%?),(\d+%?)\)/ +const toNumber = (str) => Math.max(0, Math.min(255, parseInt(str, 10))) export const cmykInputToColor = (input) => { - if (/cmyk/i.test(input)) { - const str = input.replace(/\s/g, ''); - const match = str.match(REG_CMYK_STRING); - const c = toNumber(match[1]); - const m = toNumber(match[2]); - const y = toNumber(match[3]); - const k = toNumber(match[4]); - const { r, g, b } = cmyk2rgb(c, m, y, k); - return `rgb(${r}, ${g}, ${b})`; - } - return input; -}; + if (/cmyk/i.test(input)) { + const str = input.replace(/\s/g, '') + const match = str.match(REG_CMYK_STRING) + const c = toNumber(match[1]) + const m = toNumber(match[2]) + const y = toNumber(match[3]) + const k = toNumber(match[4]) + const {r, g, b} = cmyk2rgb(c, m, y, k) + return `rgb(${r}, ${g}, ${b})` + } + return input +} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/color.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/color.js index 847ec5bd..6c490a7a 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/color.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/color.js @@ -1,334 +1,393 @@ -import tinyColor from 'tinycolor2'; -import { cmykInputToColor, rgb2cmyk } from './cmyk'; -import { parseGradientString, isGradientColor } from './gradient'; -const mathRound = Math.round; -const hsv2rgba = (states) => tinyColor(states).toRgb(); -const hsv2hsva = (states) => tinyColor(states).toHsv(); -const hsv2hsla = (states) => tinyColor(states).toHsl(); +import tinyColor from 'tinycolor2' +import {cmykInputToColor, rgb2cmyk} from './cmyk' +import {parseGradientString, isGradientColor} from './gradient' + +const mathRound = Math.round +const hsv2rgba = (states) => tinyColor(states).toRgb() +const hsv2hsva = (states) => tinyColor(states).toHsv() +const hsv2hsla = (states) => tinyColor(states).toHsl() export const gradientColors2string = (object) => { - const { points, degree } = object; - const colorsStop = points - .sort((pA, pB) => pA.left - pB.left) - .map((p) => `${p.color} ${Math.round(p.left * 100) / 100}%`); - return `linear-gradient(${degree}deg,${colorsStop.join(',')})`; -}; -export const getColorWithoutAlpha = (color) => tinyColor(color).setAlpha(1).toHexString(); -export const genId = () => (1 + Math.random() * 4294967295).toString(16); + const {points, degree} = object + const colorsStop = points + .sort((pA, pB) => pA.left - pB.left) + .map((p) => `${p.color} ${Math.round(p.left * 100) / 100}%`) + return `linear-gradient(${degree}deg,${colorsStop.join(',')})` +} +export const getColorWithoutAlpha = (color) => tinyColor(color).setAlpha(1).toHexString() +export const genId = () => (1 + Math.random() * 4294967295).toString(16) export const genGradientPoint = (left, color) => ({ - id: genId(), - left, - color, -}); + id: genId(), + left, + color, +}) export class Color { - constructor(input) { - this.states = { - s: 100, - v: 100, - h: 100, - a: 1, - }; - this.gradientStates = { - colors: [], - degree: 0, - selectedId: null, - css: '', - }; - this.update(input); - } - update(input) { - var _a, _b; - const gradientColors = parseGradientString(input); - if (this.isGradient && !gradientColors) { - const colorHsv = tinyColor(input).toHsv(); - this.states = colorHsv; - this.updateCurrentGradientColor(); - return; - } - this.originColor = input; - this.isGradient = false; - let colorInput = input; - if (gradientColors) { - this.isGradient = true; - const object = gradientColors; - const points = object.points.map((c) => genGradientPoint(c.left, c.color)); - this.gradientStates = { - colors: points, - degree: object.degree, - selectedId: ((_a = points[0]) === null || _a === void 0 ? void 0 : _a.id) || null, - }; - this.gradientStates.css = this.linearGradient; - colorInput = (_b = this.gradientSelectedPoint) === null || _b === void 0 ? void 0 : _b.color; - } - this.updateStates(colorInput); - } - get saturation() { - return this.states.s; - } - set saturation(value) { - this.states.s = Math.max(0, Math.min(100, value)); - this.updateCurrentGradientColor(); - } - get value() { - return this.states.v; - } - set value(value) { - this.states.v = Math.max(0, Math.min(100, value)); - this.updateCurrentGradientColor(); - } - get hue() { - return this.states.h; - } - set hue(value) { - this.states.h = Math.max(0, Math.min(360, value)); - this.updateCurrentGradientColor(); - } - get alpha() { - return this.states.a; - } - set alpha(value) { - this.states.a = Math.max(0, Math.min(1, Math.round(value * 100) / 100)); - this.updateCurrentGradientColor(); - } - get rgb() { - const { r, g, b } = hsv2rgba(this.states); - return `rgb(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)})`; - } - get rgba() { - const { r, g, b, a } = hsv2rgba(this.states); - return `rgba(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)}, ${a})`; - } - get hsv() { - const { h, s, v } = this.getHsva(); - return `hsv(${h}, ${s}%, ${v}%)`; - } - get hsva() { - const { h, s, v, a } = this.getHsva(); - return `hsva(${h}, ${s}%, ${v}%, ${a})`; - } - get hsl() { - const { h, s, l } = this.getHsla(); - return `hsl(${h}, ${s}%, ${l}%)`; - } - get hsla() { - const { h, s, l, a } = this.getHsla(); - return `hsla(${h}, ${s}%, ${l}%, ${a})`; - } - get hex() { - return tinyColor(this.states).toHexString(); - } - get hex8() { - return tinyColor(this.states).toHex8String(); - } - get cmyk() { - const { c, m, y, k } = this.getCmyk(); - return `cmyk(${c}, ${m}, ${y}, ${k})`; - } - get css() { - if (this.isGradient) { - return this.linearGradient; - } - return this.rgba; - } - get linearGradient() { - const { gradientColors, gradientDegree } = this; - return gradientColors2string({ - points: gradientColors, - degree: gradientDegree, - }); - } - get gradientColors() { - return this.gradientStates.colors; - } - set gradientColors(colors) { - this.gradientStates.colors = colors; - this.gradientStates.css = this.linearGradient; - } - get gradientSelectedId() { - return this.gradientStates.selectedId; - } - set gradientSelectedId(id) { - var _a; - if (id === this.gradientSelectedId) { - return; - } - this.gradientStates.selectedId = id; - this.updateStates((_a = this.gradientSelectedPoint) === null || _a === void 0 ? void 0 : _a.color); - } - get gradientDegree() { - return this.gradientStates.degree; - } - set gradientDegree(degree) { - this.gradientStates.degree = Math.max(0, Math.min(360, degree)); - this.gradientStates.css = this.linearGradient; - } - get gradientSelectedPoint() { - const { gradientColors, gradientSelectedId } = this; - return gradientColors.find((color) => color.id === gradientSelectedId); - } - getFormatsColorMap() { - return { - HEX: this.hex, - CMYK: this.cmyk, - RGB: this.rgb, - RGBA: this.rgba, - HSL: this.hsl, - HSLA: this.hsla, - HSV: this.hsv, - HSVA: this.hsva, - CSS: this.css, - HEX8: this.hex8, - }; - } - updateCurrentGradientColor() { - const { isGradient, gradientColors, gradientSelectedId } = this; - const { length } = gradientColors; - const current = this.gradientSelectedPoint; - if (!isGradient || length === 0 || !current) { - return false; - } - const index = gradientColors.findIndex((color) => color.id === gradientSelectedId); - const newColor = Object.assign(Object.assign({}, current), { color: this.rgba }); - gradientColors.splice(index, 1, newColor); - this.gradientColors = gradientColors.slice(); - return this; - } - updateStates(input) { - const color = tinyColor(cmykInputToColor(input)); - const hsva = color.toHsv(); - this.states = hsva; - } - getRgba() { - const { r, g, b, a } = hsv2rgba(this.states); - return { - r: mathRound(r), - g: mathRound(g), - b: mathRound(b), - a, - }; - } - getCmyk() { - const { r, g, b } = this.getRgba(); - const [c, m, y, k] = rgb2cmyk(r, g, b); - return { - c: mathRound(c * 100), - m: mathRound(m * 100), - y: mathRound(y * 100), - k: mathRound(k * 100), - }; - } - getHsva() { - let { h, s, v, a } = hsv2hsva(this.states); - h = mathRound(h); - s = mathRound(s * 100); - v = mathRound(v * 100); - a *= 1; - return { - h, - s, - v, - a, - }; - } - getHsla() { - let { h, s, l, a } = hsv2hsla(this.states); - h = mathRound(h); - s = mathRound(s * 100); - l = mathRound(l * 100); - a *= 1; - return { - h, - s, - l, - a, - }; - } - equals(color) { - return tinyColor.equals(this.rgba, color); - } - static isValid(color) { - if (parseGradientString(color)) { - return true; - } - return tinyColor(color).isValid(); - } - static hsva2color(h, s, v, a) { - return tinyColor({ - h, - s, - v, - a, - }).toHsvString(); - } - static hsla2color(h, s, l, a) { - return tinyColor({ - h, - s, - l, - a, - }).toHslString(); - } - static rgba2color(r, g, b, a) { - return tinyColor({ - r, - g, - b, - a, - }).toHsvString(); - } - static hex2color(hex, a) { - const color = tinyColor(hex); - color.setAlpha(a); - return color.toHexString(); - } - static object2color(object, format) { - if (format === 'CMYK') { - const { c, m, y, k } = object; - return `cmyk(${c}, ${m}, ${y}, ${k})`; - } - const color = tinyColor(object, { - format, - }); - return color.toRgbString(); - } + constructor(input) { + this.states = { + s: 100, + v: 100, + h: 100, + a: 1, + } + this.gradientStates = { + colors: [], + degree: 0, + selectedId: null, + css: '', + } + this.update(input) + } + + update(input) { + let _a; let + _b + const gradientColors = parseGradientString(input) + if (this.isGradient && !gradientColors) { + const colorHsv = tinyColor(input).toHsv() + this.states = colorHsv + this.updateCurrentGradientColor() + return + } + this.originColor = input + this.isGradient = false + let colorInput = input + if (gradientColors) { + this.isGradient = true + const object = gradientColors + const points = object.points.map((c) => genGradientPoint(c.left, c.color)) + this.gradientStates = { + colors: points, + degree: object.degree, + selectedId: ((_a = points[0]) === null || _a === void 0 ? void 0 : _a.id) || null, + } + this.gradientStates.css = this.linearGradient + colorInput = (_b = this.gradientSelectedPoint) === null || _b === void 0 ? void 0 : _b.color + } + this.updateStates(colorInput) + } + + get saturation() { + return this.states.s + } + + set saturation(value) { + this.states.s = Math.max(0, Math.min(100, value)) + this.updateCurrentGradientColor() + } + + get value() { + return this.states.v + } + + set value(value) { + this.states.v = Math.max(0, Math.min(100, value)) + this.updateCurrentGradientColor() + } + + get hue() { + return this.states.h + } + + set hue(value) { + this.states.h = Math.max(0, Math.min(360, value)) + this.updateCurrentGradientColor() + } + + get alpha() { + return this.states.a + } + + set alpha(value) { + this.states.a = Math.max(0, Math.min(1, Math.round(value * 100) / 100)) + this.updateCurrentGradientColor() + } + + get rgb() { + const {r, g, b} = hsv2rgba(this.states) + return `rgb(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)})` + } + + get rgba() { + const { + r, g, b, a + } = hsv2rgba(this.states) + return `rgba(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)}, ${a})` + } + + get hsv() { + const {h, s, v} = this.getHsva() + return `hsv(${h}, ${s}%, ${v}%)` + } + + get hsva() { + const { + h, s, v, a + } = this.getHsva() + return `hsva(${h}, ${s}%, ${v}%, ${a})` + } + + get hsl() { + const {h, s, l} = this.getHsla() + return `hsl(${h}, ${s}%, ${l}%)` + } + + get hsla() { + const { + h, s, l, a + } = this.getHsla() + return `hsla(${h}, ${s}%, ${l}%, ${a})` + } + + get hex() { + return tinyColor(this.states).toHexString() + } + + get hex8() { + return tinyColor(this.states).toHex8String() + } + + get cmyk() { + const { + c, m, y, k + } = this.getCmyk() + return `cmyk(${c}, ${m}, ${y}, ${k})` + } + + get css() { + if (this.isGradient) { + return this.linearGradient + } + return this.rgba + } + + get linearGradient() { + const {gradientColors, gradientDegree} = this + return gradientColors2string({ + points: gradientColors, + degree: gradientDegree, + }) + } + + get gradientColors() { + return this.gradientStates.colors + } + + set gradientColors(colors) { + this.gradientStates.colors = colors + this.gradientStates.css = this.linearGradient + } + + get gradientSelectedId() { + return this.gradientStates.selectedId + } + + set gradientSelectedId(id) { + let _a + if (id === this.gradientSelectedId) { + return + } + this.gradientStates.selectedId = id + this.updateStates((_a = this.gradientSelectedPoint) === null || _a === void 0 ? void 0 : _a.color) + } + + get gradientDegree() { + return this.gradientStates.degree + } + + set gradientDegree(degree) { + this.gradientStates.degree = Math.max(0, Math.min(360, degree)) + this.gradientStates.css = this.linearGradient + } + + get gradientSelectedPoint() { + const {gradientColors, gradientSelectedId} = this + return gradientColors.find((color) => color.id === gradientSelectedId) + } + + getFormatsColorMap() { + return { + HEX: this.hex, + CMYK: this.cmyk, + RGB: this.rgb, + RGBA: this.rgba, + HSL: this.hsl, + HSLA: this.hsla, + HSV: this.hsv, + HSVA: this.hsva, + CSS: this.css, + HEX8: this.hex8, + } + } + + updateCurrentGradientColor() { + const {isGradient, gradientColors, gradientSelectedId} = this + const {length} = gradientColors + const current = this.gradientSelectedPoint + if (!isGradient || length === 0 || !current) { + return false + } + const index = gradientColors.findIndex((color) => color.id === gradientSelectedId) + const newColor = {...current, color: this.rgba} + gradientColors.splice(index, 1, newColor) + this.gradientColors = gradientColors.slice() + return this + } + + updateStates(input) { + const color = tinyColor(cmykInputToColor(input)) + const hsva = color.toHsv() + this.states = hsva + } + + getRgba() { + const { + r, g, b, a + } = hsv2rgba(this.states) + return { + r: mathRound(r), + g: mathRound(g), + b: mathRound(b), + a, + } + } + + getCmyk() { + const {r, g, b} = this.getRgba() + const [c, m, y, k] = rgb2cmyk(r, g, b) + return { + c: mathRound(c * 100), + m: mathRound(m * 100), + y: mathRound(y * 100), + k: mathRound(k * 100), + } + } + + getHsva() { + let { + h, s, v, a + } = hsv2hsva(this.states) + h = mathRound(h) + s = mathRound(s * 100) + v = mathRound(v * 100) + a *= 1 + return { + h, + s, + v, + a, + } + } + + getHsla() { + let { + h, s, l, a + } = hsv2hsla(this.states) + h = mathRound(h) + s = mathRound(s * 100) + l = mathRound(l * 100) + a *= 1 + return { + h, + s, + l, + a, + } + } + + equals(color) { + return tinyColor.equals(this.rgba, color) + } + + static isValid(color) { + if (parseGradientString(color)) { + return true + } + return tinyColor(color).isValid() + } + + static hsva2color(h, s, v, a) { + return tinyColor({ + h, + s, + v, + a, + }).toHsvString() + } + + static hsla2color(h, s, l, a) { + return tinyColor({ + h, + s, + l, + a, + }).toHslString() + } + + static rgba2color(r, g, b, a) { + return tinyColor({ + r, + g, + b, + a, + }).toHsvString() + } + + static hex2color(hex, a) { + const color = tinyColor(hex) + color.setAlpha(a) + return color.toHexString() + } + + static object2color(object, format) { + if (format === 'CMYK') { + const { + c, m, y, k + } = object + return `cmyk(${c}, ${m}, ${y}, ${k})` + } + const color = tinyColor(object, { + format, + }) + return color.toRgbString() + } } -Color.isGradientColor = (input) => !!isGradientColor(input); +Color.isGradientColor = (input) => !!isGradientColor(input) Color.compare = (color1, color2) => { - const isGradientColor1 = Color.isGradientColor(color1); - const isGradientColor2 = Color.isGradientColor(color2); - if (isGradientColor1 && isGradientColor2) { - const gradientColor1 = gradientColors2string(parseGradientString(color1)); - const gradientColor2 = gradientColors2string(parseGradientString(color2)); - return gradientColor1 === gradientColor2; - } - if (!isGradientColor1 && !isGradientColor2) { - return tinyColor.equals(color1, color2); - } - return false; -}; + const isGradientColor1 = Color.isGradientColor(color1) + const isGradientColor2 = Color.isGradientColor(color2) + if (isGradientColor1 && isGradientColor2) { + const gradientColor1 = gradientColors2string(parseGradientString(color1)) + const gradientColor2 = gradientColors2string(parseGradientString(color2)) + return gradientColor1 === gradientColor2 + } + if (!isGradientColor1 && !isGradientColor2) { + return tinyColor.equals(color1, color2) + } + return false +} const COLOR_OBJECT_OUTPUT_KEYS = [ - 'alpha', - 'css', - 'hex', - 'hex8', - 'hsl', - 'hsla', - 'hsv', - 'hsva', - 'rgb', - 'rgba', - 'saturation', - 'value', - 'isGradient', -]; + 'alpha', + 'css', + 'hex', + 'hex8', + 'hsl', + 'hsla', + 'hsv', + 'hsva', + 'rgb', + 'rgba', + 'saturation', + 'value', + 'isGradient', +] export const getColorObject = (color) => { - if (!color) { - return null; - } - const colorObject = Object.create(null); - COLOR_OBJECT_OUTPUT_KEYS.forEach((key) => (colorObject[key] = color[key])); - if (color.isGradient) { - colorObject.linearGradient = color.linearGradient; - } - return colorObject; -}; -export default Color; + if (!color) { + return null + } + const colorObject = Object.create(null) + COLOR_OBJECT_OUTPUT_KEYS.forEach((key) => (colorObject[key] = color[key])) + if (color.isGradient) { + colorObject.linearGradient = color.linearGradient + } + return colorObject +} +export default Color diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/gradient.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/gradient.js index 18eacb20..4f364bd4 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/gradient.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/gradient.js @@ -1,119 +1,119 @@ -import isString from 'lodash/isString'; -import isNull from 'lodash/isNull'; -import tinyColor from 'tinycolor2'; +import isString from 'lodash/isString' +import isNull from 'lodash/isNull' +import tinyColor from 'tinycolor2' + const combineRegExp = (regexpList, flags) => { - let source = ''; - for (let i = 0; i < regexpList.length; i++) { - if (isString(regexpList[i])) { - source += regexpList[i]; - } - else { - source += regexpList[i].source; - } + let source = '' + for (let i = 0; i < regexpList.length; i++) { + if (isString(regexpList[i])) { + source += regexpList[i] + } else { + source += regexpList[i].source } - return new RegExp(source, flags); -}; + } + return new RegExp(source, flags) +} const generateRegExp = () => { - const searchFlags = 'gi'; - const rAngle = /(?:[+-]?\d*\.?\d+)(?:deg|grad|rad|turn)/; - const rSideCornerCapture = /to\s+((?:(?:left|right|top|bottom)(?:\s+(?:top|bottom|left|right))?))/; - const rComma = /\s*,\s*/; - const rColorHex = /#(?:[a-f0-9]{6}|[a-f0-9]{3})/; - const rDigits3 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*\)/; - const rDigits4 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*,\s*\d*\.?\d+\)/; - const rValue = /(?:[+-]?\d*\.?\d+)(?:%|[a-z]+)?/; - const rKeyword = /[_a-z-][_a-z0-9-]*/; - const rColor = combineRegExp(['(?:', rColorHex, '|', '(?:rgb|hsl)', rDigits3, '|', '(?:rgba|hsla)', rDigits4, '|', rKeyword, ')'], ''); - const rColorStop = combineRegExp([rColor, '(?:\\s+', rValue, '(?:\\s+', rValue, ')?)?'], ''); - const rColorStopList = combineRegExp(['(?:', rColorStop, rComma, ')*', rColorStop], ''); - const rLineCapture = combineRegExp(['(?:(', rAngle, ')|', rSideCornerCapture, ')'], ''); - const rGradientSearch = combineRegExp(['(?:(', rLineCapture, ')', rComma, ')?(', rColorStopList, ')'], searchFlags); - const rColorStopSearch = combineRegExp(['\\s*(', rColor, ')', '(?:\\s+', '(', rValue, '))?', '(?:', rComma, '\\s*)?'], searchFlags); - return { - gradientSearch: rGradientSearch, - colorStopSearch: rColorStopSearch, - }; -}; + const searchFlags = 'gi' + const rAngle = /(?:[+-]?\d*\.?\d+)(?:deg|grad|rad|turn)/ + const rSideCornerCapture = /to\s+((?:(?:left|right|top|bottom)(?:\s+(?:top|bottom|left|right))?))/ + const rComma = /\s*,\s*/ + const rColorHex = /#(?:[a-f0-9]{6}|[a-f0-9]{3})/ + const rDigits3 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*\)/ + const rDigits4 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*,\s*\d*\.?\d+\)/ + const rValue = /(?:[+-]?\d*\.?\d+)(?:%|[a-z]+)?/ + const rKeyword = /[_a-z-][_a-z0-9-]*/ + const rColor = combineRegExp(['(?:', rColorHex, '|', '(?:rgb|hsl)', rDigits3, '|', '(?:rgba|hsla)', rDigits4, '|', rKeyword, ')'], '') + const rColorStop = combineRegExp([rColor, '(?:\\s+', rValue, '(?:\\s+', rValue, ')?)?'], '') + const rColorStopList = combineRegExp(['(?:', rColorStop, rComma, ')*', rColorStop], '') + const rLineCapture = combineRegExp(['(?:(', rAngle, ')|', rSideCornerCapture, ')'], '') + const rGradientSearch = combineRegExp(['(?:(', rLineCapture, ')', rComma, ')?(', rColorStopList, ')'], searchFlags) + const rColorStopSearch = combineRegExp(['\\s*(', rColor, ')', '(?:\\s+', '(', rValue, '))?', '(?:', rComma, '\\s*)?'], searchFlags) + return { + gradientSearch: rGradientSearch, + colorStopSearch: rColorStopSearch, + } +} const parseGradient = (regExpLib, input) => { - let result; - let matchColorStop; - let stopResult; - regExpLib.gradientSearch.lastIndex = 0; - const matchGradient = regExpLib.gradientSearch.exec(input); - if (!isNull(matchGradient)) { - result = { - original: matchGradient[0], - colorStopList: [], - }; - if (matchGradient[1]) { - result.line = matchGradient[1]; - } - if (matchGradient[2]) { - result.angle = matchGradient[2]; - } - if (matchGradient[3]) { - result.sideCorner = matchGradient[3]; - } - regExpLib.colorStopSearch.lastIndex = 0; - matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]); - while (!isNull(matchColorStop)) { - stopResult = { - color: matchColorStop[1], - }; - if (matchColorStop[2]) { - stopResult.position = matchColorStop[2]; - } - result.colorStopList.push(stopResult); - matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]); - } + let result + let matchColorStop + let stopResult + regExpLib.gradientSearch.lastIndex = 0 + const matchGradient = regExpLib.gradientSearch.exec(input) + if (!isNull(matchGradient)) { + result = { + original: matchGradient[0], + colorStopList: [], } - return result; -}; -const REGEXP_LIB = generateRegExp(); -const REG_GRADIENT = /.*gradient\s*\(((?:\([^)]*\)|[^)(]*)*)\)/gim; -export const isGradientColor = (input) => { - REG_GRADIENT.lastIndex = 0; - return REG_GRADIENT.exec(input); -}; -const sideCornerDegreeMap = { - top: 0, - right: 90, - bottom: 180, - left: 270, - 'top left': 225, - 'left top': 225, - 'top right': 135, - 'right top': 135, - 'bottom left': 315, - 'left bottom': 315, - 'bottom right': 45, - 'right bottom': 45, -}; -export const parseGradientString = (input) => { - const match = isGradientColor(input); - if (!match) { - return false; + if (matchGradient[1]) { + result.line = matchGradient[1] + } + if (matchGradient[2]) { + result.angle = matchGradient[2] } - const gradientColors = { - points: [], - degree: 0, - }; - const result = parseGradient(REGEXP_LIB, match[1]); - if (result.original.trim() !== match[1].trim()) { - return false; + if (matchGradient[3]) { + result.sideCorner = matchGradient[3] } - const points = result.colorStopList.map(({ color, position }) => { - const point = Object.create(null); - point.color = tinyColor(color).toRgbString(); - point.left = parseFloat(position); - return point; - }); - gradientColors.points = points; - let degree = parseInt(result.angle, 10); - if (Number.isNaN(degree)) { - degree = sideCornerDegreeMap[result.sideCorner] || 90; + regExpLib.colorStopSearch.lastIndex = 0 + matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]) + while (!isNull(matchColorStop)) { + stopResult = { + color: matchColorStop[1], + } + if (matchColorStop[2]) { + stopResult.position = matchColorStop[2] + } + result.colorStopList.push(stopResult) + matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]) } - gradientColors.degree = degree; - return gradientColors; -}; -export default parseGradientString; + } + return result +} +const REGEXP_LIB = generateRegExp() +const REG_GRADIENT = /.*gradient\s*\(((?:\([^)]*\)|[^)(]*)*)\)/gim +export const isGradientColor = (input) => { + REG_GRADIENT.lastIndex = 0 + return REG_GRADIENT.exec(input) +} +const sideCornerDegreeMap = { + top: 0, + right: 90, + bottom: 180, + left: 270, + 'top left': 225, + 'left top': 225, + 'top right': 135, + 'right top': 135, + 'bottom left': 315, + 'left bottom': 315, + 'bottom right': 45, + 'right bottom': 45, +} +export const parseGradientString = (input) => { + const match = isGradientColor(input) + if (!match) { + return false + } + const gradientColors = { + points: [], + degree: 0, + } + const result = parseGradient(REGEXP_LIB, match[1]) + if (result.original.trim() !== match[1].trim()) { + return false + } + const points = result.colorStopList.map(({color, position}) => { + const point = Object.create(null) + point.color = tinyColor(color).toRgbString() + point.left = parseFloat(position) + return point + }) + gradientColors.points = points + let degree = parseInt(result.angle, 10) + if (Number.isNaN(degree)) { + degree = sideCornerDegreeMap[result.sideCorner] || 90 + } + gradientColors.degree = degree + return gradientColors +} +export default parseGradientString diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/index.js index ad18475c..1ed542a9 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/shared/color-picker/index.js @@ -1,3 +1,3 @@ -export * from './cmyk'; -export * from './color'; -export * from './gradient'; +export * from './cmyk' +export * from './color' +export * from './gradient' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/control.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/control.js index 03c9e772..4bb6ee12 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/control.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/control.js @@ -1,40 +1,39 @@ const defaultOption = { - valueKey: 'value', - defaultValueKey: 'defaultValue', - changeEventName: 'change', - strict: true, -}; + valueKey: 'value', + defaultValueKey: 'defaultValue', + changeEventName: 'change', + strict: true, +} function useControl(option = {}) { - const { valueKey, defaultValueKey, changeEventName, strict } = Object.assign(Object.assign({}, defaultOption), option); - const props = this.properties || {}; - const value = props[valueKey]; - const defaultValue = props[strict ? defaultValueKey : valueKey]; - let controlled = false; - if (strict && typeof value !== 'undefined' && value !== null) { - controlled = true; - } - const set = (newVal, extObj, fn) => { - this.setData(Object.assign({ [`_${valueKey}`]: newVal }, extObj), fn); - }; - return { - controlled, - initValue: controlled ? value : defaultValue, - set, - get: () => { - return this.data[`_${valueKey}`]; - }, - change: (newVal, customChangeData, customUpdateFn) => { - this.triggerEvent(changeEventName, typeof customChangeData !== 'undefined' ? customChangeData : newVal); - if (controlled) { - return; - } - if (typeof customUpdateFn === 'function') { - customUpdateFn(); - } - else { - set(newVal); - } - }, - }; + const { + valueKey, defaultValueKey, changeEventName, strict + } = {...defaultOption, ...option} + const props = this.properties || {} + const value = props[valueKey] + const defaultValue = props[strict ? defaultValueKey : valueKey] + let controlled = false + if (strict && typeof value !== 'undefined' && value !== null) { + controlled = true + } + const set = (newVal, extObj, fn) => { + this.setData({[`_${valueKey}`]: newVal, ...extObj}, fn) + } + return { + controlled, + initValue: controlled ? value : defaultValue, + set, + get: () => this.data[`_${valueKey}`], + change: (newVal, customChangeData, customUpdateFn) => { + this.triggerEvent(changeEventName, typeof customChangeData !== 'undefined' ? customChangeData : newVal) + if (controlled) { + return + } + if (typeof customUpdateFn === 'function') { + customUpdateFn() + } else { + set(newVal) + } + }, + } } -export { useControl }; +export {useControl} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/flatTool.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/flatTool.js index 045abd77..27ad2833 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/flatTool.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/flatTool.js @@ -1,57 +1,48 @@ export const getPrototypeOf = function (obj) { - return Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.__proto__; -}; + return Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.__proto__ +} export const isObject = function isObject(something) { - const type = typeof something; - return something !== null && (type === 'function' || type === 'object'); -}; + const type = typeof something + return something !== null && (type === 'function' || type === 'object') +} export const iterateInheritedPrototype = function iterateInheritedPrototype(callback, fromCtor, toCtor, includeToCtor = true) { - let proto = fromCtor.prototype || fromCtor; - const toProto = toCtor.prototype || toCtor; - while (proto) { - if (!includeToCtor && proto === toProto) - break; - if (callback(proto) === false) - break; - if (proto === toProto) - break; - proto = getPrototypeOf(proto); - } -}; + let proto = fromCtor.prototype || fromCtor + const toProto = toCtor.prototype || toCtor + while (proto) { + if (!includeToCtor && proto === toProto) break + if (callback(proto) === false) break + if (proto === toProto) break + proto = getPrototypeOf(proto) + } +} export const toObject = function toObject(something, options = {}) { - const obj = {}; - if (!isObject(something)) - return obj; - const excludes = options.excludes || ['constructor']; - const { enumerable = true, configurable = 0, writable = 0 } = options; - const defaultDesc = {}; - if (enumerable !== 0) - defaultDesc.enumerable = enumerable; - if (configurable !== 0) - defaultDesc.configurable = configurable; - if (writable !== 0) - defaultDesc.writable = writable; - iterateInheritedPrototype((proto) => { - Object.getOwnPropertyNames(proto).forEach((key) => { - if (excludes.indexOf(key) >= 0) - return; - if (Object.prototype.hasOwnProperty.call(obj, key)) - return; - const desc = Object.getOwnPropertyDescriptor(proto, key); - const fnKeys = ['get', 'set', 'value']; - fnKeys.forEach((k) => { - if (typeof desc[k] === 'function') { - const oldFn = desc[k]; - desc[k] = function (...args) { - return oldFn.apply(Object.prototype.hasOwnProperty.call(options, 'bindTo') ? options.bindTo : this, args); - }; - } - }); - Object.defineProperty(obj, key, Object.assign(Object.assign({}, desc), defaultDesc)); - }); - }, something, options.till || Object, false); - return obj; -}; + const obj = {} + if (!isObject(something)) return obj + const excludes = options.excludes || ['constructor'] + const {enumerable = true, configurable = 0, writable = 0} = options + const defaultDesc = {} + if (enumerable !== 0) defaultDesc.enumerable = enumerable + if (configurable !== 0) defaultDesc.configurable = configurable + if (writable !== 0) defaultDesc.writable = writable + iterateInheritedPrototype((proto) => { + Object.getOwnPropertyNames(proto).forEach((key) => { + if (excludes.indexOf(key) >= 0) return + if (Object.prototype.hasOwnProperty.call(obj, key)) return + const desc = Object.getOwnPropertyDescriptor(proto, key) + const fnKeys = ['get', 'set', 'value'] + fnKeys.forEach((k) => { + if (typeof desc[k] === 'function') { + const oldFn = desc[k] + desc[k] = function (...args) { + return oldFn.apply(Object.prototype.hasOwnProperty.call(options, 'bindTo') ? options.bindTo : this, args) + } + } + }) + Object.defineProperty(obj, key, {...desc, ...defaultDesc}) + }) + }, something, options.till || Object, false) + return obj +} export const isPlainObject = function isPlainObject(something) { - return Object.prototype.toString.call(something) === '[object Object]'; -}; + return Object.prototype.toString.call(something) === '[object Object]' +} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/index.js index 94e7ce12..9b7ff8b8 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/index.js @@ -1,4 +1,4 @@ -export * from './superComponent'; -export * from './flatTool'; -export * from './instantiationDecorator'; -export * from './control'; +export * from './superComponent' +export * from './flatTool' +export * from './instantiationDecorator' +export * from './control' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/instantiationDecorator.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/instantiationDecorator.js index d9b15b72..eabf691a 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/instantiationDecorator.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/instantiationDecorator.js @@ -1,139 +1,133 @@ -import { isPlainObject, toObject } from './flatTool'; -import { canUseVirtualHost } from '../version'; -const RawLifeCycles = ['Created', 'Attached', 'Ready', 'Moved', 'Detached', 'Error']; -const NativeLifeCycles = RawLifeCycles.map((k) => k.toLowerCase()); +import {isPlainObject, toObject} from './flatTool' +import {canUseVirtualHost} from '../version' + +const RawLifeCycles = ['Created', 'Attached', 'Ready', 'Moved', 'Detached', 'Error'] +const NativeLifeCycles = RawLifeCycles.map((k) => k.toLowerCase()) const ComponentNativeProps = [ - 'properties', - 'data', - 'observers', - 'methods', - 'behaviors', - ...NativeLifeCycles, - 'relations', - 'externalClasses', - 'options', - 'lifetimes', - 'pageLifeTimes', - 'definitionFilter', -]; + 'properties', + 'data', + 'observers', + 'methods', + 'behaviors', + ...NativeLifeCycles, + 'relations', + 'externalClasses', + 'options', + 'lifetimes', + 'pageLifeTimes', + 'definitionFilter', +] export const toComponent = function toComponent(options) { - const { relations, behaviors = [], externalClasses = [] } = options; - if (options.properties) { - Object.keys(options.properties).forEach((k) => { - let opt = options.properties[k]; - if (!isPlainObject(opt)) { - opt = { type: opt }; - } - options.properties[k] = opt; - }); - const ariaProps = [ - { key: 'ariaHidden', type: Boolean }, - { key: 'ariaRole', type: String }, - { key: 'ariaLabel', type: String }, - { key: 'ariaLabelledby', type: String }, - { key: 'ariaDescribedby', type: String }, - { key: 'ariaBusy', type: Boolean }, - ]; - ariaProps.forEach(({ key, type }) => { - options.properties[key] = { - type, - }; - }); - options.properties.style = { type: String, value: '' }; - options.properties.customStyle = { type: String, value: '' }; + const {relations, behaviors = [], externalClasses = []} = options + if (options.properties) { + Object.keys(options.properties).forEach((k) => { + let opt = options.properties[k] + if (!isPlainObject(opt)) { + opt = {type: opt} + } + options.properties[k] = opt + }) + const ariaProps = [ + {key: 'ariaHidden', type: Boolean}, + {key: 'ariaRole', type: String}, + {key: 'ariaLabel', type: String}, + {key: 'ariaLabelledby', type: String}, + {key: 'ariaDescribedby', type: String}, + {key: 'ariaBusy', type: Boolean}, + ] + ariaProps.forEach(({key, type}) => { + options.properties[key] = { + type, + } + }) + options.properties.style = {type: String, value: ''} + options.properties.customStyle = {type: String, value: ''} + } + if (!options.methods) options.methods = {} + if (!options.lifetimes) options.lifetimes = {} + const inits = {} + if (relations) { + const getRelations = (relation, path) => Behavior({ + created() { + Object.defineProperty(this, `$${relation}`, { + get: () => { + const nodes = this.getRelationNodes(path) || [] + return relation === 'parent' ? nodes[0] : nodes + }, + }) + }, + }) + const map = {} + Object.keys(relations).forEach((path) => { + const comp = relations[path] + const relation = ['parent', 'ancestor'].includes(comp.type) ? 'parent' : 'children' + const mixin = getRelations(relation, path) + map[relation] = mixin + }) + behaviors.push(...Object.keys(map).map((key) => map[key])) + } + options.behaviors = [...behaviors] + options.externalClasses = ['class', ...externalClasses] + Object.getOwnPropertyNames(options).forEach((k) => { + const desc = Object.getOwnPropertyDescriptor(options, k) + if (!desc) return + if (NativeLifeCycles.indexOf(k) < 0 && typeof desc.value === 'function') { + Object.defineProperty(options.methods, k, desc) + delete options[k] + } else if (ComponentNativeProps.indexOf(k) < 0) { + inits[k] = desc + } else if (NativeLifeCycles.indexOf(k) >= 0) { + options.lifetimes[k] = options[k] } - if (!options.methods) - options.methods = {}; - if (!options.lifetimes) - options.lifetimes = {}; - const inits = {}; - if (relations) { - const getRelations = (relation, path) => Behavior({ - created() { - Object.defineProperty(this, `$${relation}`, { - get: () => { - const nodes = this.getRelationNodes(path) || []; - return relation === 'parent' ? nodes[0] : nodes; - }, - }); - }, - }); - const map = {}; - Object.keys(relations).forEach((path) => { - const comp = relations[path]; - const relation = ['parent', 'ancestor'].includes(comp.type) ? 'parent' : 'children'; - const mixin = getRelations(relation, path); - map[relation] = mixin; - }); - behaviors.push(...Object.keys(map).map((key) => map[key])); + }) + if (Object.keys(inits).length) { + const oldCreated = options.lifetimes.created + const oldAttached = options.lifetimes.attached + const {controlledProps = []} = options + options.lifetimes.created = function (...args) { + Object.defineProperties(this, inits) + if (oldCreated) oldCreated.apply(this, args) } - options.behaviors = [...behaviors]; - options.externalClasses = ['class', ...externalClasses]; - Object.getOwnPropertyNames(options).forEach((k) => { - const desc = Object.getOwnPropertyDescriptor(options, k); - if (!desc) - return; - if (NativeLifeCycles.indexOf(k) < 0 && typeof desc.value === 'function') { - Object.defineProperty(options.methods, k, desc); - delete options[k]; + options.lifetimes.attached = function (...args) { + if (oldAttached) oldAttached.apply(this, args) + controlledProps.forEach(({key}) => { + const defaultKey = `default${key.replace(/^(\w)/, (m, m1) => m1.toUpperCase())}` + const props = this.properties + if (props[key] == null) { + this._selfControlled = true } - else if (ComponentNativeProps.indexOf(k) < 0) { - inits[k] = desc; + if (props[key] == null && props[defaultKey] != null) { + this.setData({ + [key]: props[defaultKey], + }) } - else if (NativeLifeCycles.indexOf(k) >= 0) { - options.lifetimes[k] = options[k]; + }) + } + options.methods._trigger = function (evtName, detail, opts) { + const target = controlledProps.find((item) => item.event == evtName) + if (target) { + const {key} = target + if (this._selfControlled) { + this.setData({ + [key]: detail[key], + }) } - }); - if (Object.keys(inits).length) { - const oldCreated = options.lifetimes.created; - const oldAttached = options.lifetimes.attached; - const { controlledProps = [] } = options; - options.lifetimes.created = function (...args) { - Object.defineProperties(this, inits); - if (oldCreated) - oldCreated.apply(this, args); - }; - options.lifetimes.attached = function (...args) { - if (oldAttached) - oldAttached.apply(this, args); - controlledProps.forEach(({ key }) => { - const defaultKey = `default${key.replace(/^(\w)/, (m, m1) => m1.toUpperCase())}`; - const props = this.properties; - if (props[key] == null) { - this._selfControlled = true; - } - if (props[key] == null && props[defaultKey] != null) { - this.setData({ - [key]: props[defaultKey], - }); - } - }); - }; - options.methods._trigger = function (evtName, detail, opts) { - const target = controlledProps.find((item) => item.event == evtName); - if (target) { - const { key } = target; - if (this._selfControlled) { - this.setData({ - [key]: detail[key], - }); - } - } - this.triggerEvent(evtName, detail, opts); - }; + } + this.triggerEvent(evtName, detail, opts) } - return options; -}; + } + return options +} export const wxComponent = function wxComponent() { - return function (constructor) { - class WxComponent extends constructor { - } - const current = new WxComponent(); - current.options = current.options || {}; - if (canUseVirtualHost()) { - current.options.virtualHost = true; - } - const obj = toComponent(toObject(current)); - Component(obj); - }; -}; + return function (constructor) { + class WxComponent extends constructor { + } + const current = new WxComponent() + current.options = current.options || {} + if (canUseVirtualHost()) { + current.options.virtualHost = true + } + const obj = toComponent(toObject(current)) + Component(obj) + } +} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/superComponent.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/superComponent.js index 3cb17dc7..b4e78cb4 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/superComponent.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/src/superComponent.js @@ -1,5 +1,5 @@ export class SuperComponent { - constructor() { - this.app = getApp(); - } + constructor() { + this.app = getApp() + } } diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/utils.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/utils.js index 920b3ca4..0cb6bb57 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/utils.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/utils.js @@ -1,248 +1,237 @@ -import { prefix } from './config'; -import { getWindowInfo, getAppBaseInfo, getDeviceInfo } from './wechat'; -export const systemInfo = getWindowInfo(); -export const appBaseInfo = getAppBaseInfo(); -export const deviceInfo = getDeviceInfo(); +import {prefix} from './config' +import {getWindowInfo, getAppBaseInfo, getDeviceInfo} from './wechat' + +export const systemInfo = getWindowInfo() +export const appBaseInfo = getAppBaseInfo() +export const deviceInfo = getDeviceInfo() export const debounce = function (func, wait = 500) { - let timerId; - return function (...rest) { - if (timerId) { - clearTimeout(timerId); - } - timerId = setTimeout(() => { - func.apply(this, rest); - }, wait); - }; -}; + let timerId + return function (...rest) { + if (timerId) { + clearTimeout(timerId) + } + timerId = setTimeout(() => { + func.apply(this, rest) + }, wait) + } +} export const throttle = (func, wait = 100, options = null) => { - let previous = 0; - let timerid = null; - if (!options) { - options = { - leading: true, - }; + let previous = 0 + let timerid = null + if (!options) { + options = { + leading: true, } - return function (...args) { - const now = Date.now(); - if (!previous && !options.leading) - previous = now; - const remaining = wait - (now - previous); - const context = this; - if (remaining <= 0) { - if (timerid) { - clearTimeout(timerid); - timerid = null; - } - previous = now; - func.apply(context, args); - } - }; -}; + } + return function (...args) { + const now = Date.now() + if (!previous && !options.leading) previous = now + const remaining = wait - (now - previous) + const context = this + if (remaining <= 0) { + if (timerid) { + clearTimeout(timerid) + timerid = null + } + previous = now + func.apply(context, args) + } + } +} export const classNames = function (...args) { - const hasOwn = {}.hasOwnProperty; - const classes = []; - args.forEach((arg) => { - if (!arg) - return; - const argType = typeof arg; - if (argType === 'string' || argType === 'number') { - classes.push(arg); + const hasOwn = {}.hasOwnProperty + const classes = [] + args.forEach((arg) => { + if (!arg) return + const argType = typeof arg + if (argType === 'string' || argType === 'number') { + classes.push(arg) + } else if (Array.isArray(arg) && arg.length) { + const inner = classNames(...arg) + if (inner) { + classes.push(inner) + } + } else if (argType === 'object') { + for (const key in arg) { + if (hasOwn.call(arg, key) && arg[key]) { + classes.push(key) } - else if (Array.isArray(arg) && arg.length) { - const inner = classNames(...arg); - if (inner) { - classes.push(inner); - } - } - else if (argType === 'object') { - for (const key in arg) { - if (hasOwn.call(arg, key) && arg[key]) { - classes.push(key); - } - } - } - }); - return classes.join(' '); -}; + } + } + }) + return classes.join(' ') +} export const styles = function (styleObj) { - return Object.keys(styleObj) - .map((styleKey) => `${styleKey}: ${styleObj[styleKey]}`) - .join('; '); -}; + return Object.keys(styleObj) + .map((styleKey) => `${styleKey}: ${styleObj[styleKey]}`) + .join('; ') +} export const getAnimationFrame = function (context, cb) { - return context - .createSelectorQuery() - .selectViewport() - .boundingClientRect() - .exec(() => { - cb(); - }); -}; + return context + .createSelectorQuery() + .selectViewport() + .boundingClientRect() + .exec(() => { + cb() + }) +} export const getRect = function (context, selector, needAll = false) { - return new Promise((resolve, reject) => { - context - .createSelectorQuery()[needAll ? 'selectAll' : 'select'](selector) - .boundingClientRect((rect) => { - if (rect) { - resolve(rect); - } - else { - reject(rect); - } - }) - .exec(); - }); -}; + return new Promise((resolve, reject) => { + context + .createSelectorQuery()[needAll ? 'selectAll' : 'select'](selector) + .boundingClientRect((rect) => { + if (rect) { + resolve(rect) + } else { + reject(rect) + } + }) + .exec() + }) +} export const isNumber = function (value) { - return /^\d+(\.\d+)?$/.test(value); -}; + return /^\d+(\.\d+)?$/.test(value) +} export const isNull = function (value) { - return value === null; -}; -export const isUndefined = (value) => typeof value === 'undefined'; + return value === null +} +export const isUndefined = (value) => typeof value === 'undefined' export const isDef = function (value) { - return !isUndefined(value) && !isNull(value); -}; + return !isUndefined(value) && !isNull(value) +} export const addUnit = function (value) { - if (!isDef(value)) { - return undefined; - } - value = String(value); - return isNumber(value) ? `${value}px` : value; -}; + if (!isDef(value)) { + return undefined + } + value = String(value) + return isNumber(value) ? `${value}px` : value +} export const getCharacterLength = (type, char, max) => { - const str = String(char !== null && char !== void 0 ? char : ''); - if (str.length === 0) { - return { - length: 0, - characters: '', - }; - } - if (type === 'maxcharacter') { - let len = 0; - for (let i = 0; i < str.length; i += 1) { - let currentStringLength = 0; - if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) { - currentStringLength = 2; - } - else { - currentStringLength = 1; - } - if (len + currentStringLength > max) { - return { - length: len, - characters: str.slice(0, i), - }; - } - len += currentStringLength; - } - return { - length: len, - characters: str, - }; + const str = String(char !== null && char !== void 0 ? char : '') + if (str.length === 0) { + return { + length: 0, + characters: '', } - else if (type === 'maxlength') { - const length = str.length > max ? max : str.length; + } + if (type === 'maxcharacter') { + let len = 0 + for (let i = 0; i < str.length; i += 1) { + let currentStringLength = 0 + if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) { + currentStringLength = 2 + } else { + currentStringLength = 1 + } + if (len + currentStringLength > max) { return { - length, - characters: str.slice(0, length), - }; + length: len, + characters: str.slice(0, i), + } + } + len += currentStringLength } return { - length: str.length, - characters: str, - }; -}; -export const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size)); -export const getInstance = function (context, selector) { - if (!context) { - const pages = getCurrentPages(); - const page = pages[pages.length - 1]; - context = page.$$basePage || page; + length: len, + characters: str, } - const instance = context ? context.selectComponent(selector) : null; - if (!instance) { - console.warn('未找到组件,请检查selector是否正确'); - return null; + } else if (type === 'maxlength') { + const length = str.length > max ? max : str.length + return { + length, + characters: str.slice(0, length), } - return instance; -}; + } + return { + length: str.length, + characters: str, + } +} +export const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)) +export const getInstance = function (context, selector) { + if (!context) { + const pages = getCurrentPages() + const page = pages[pages.length - 1] + context = page.$$basePage || page + } + const instance = context ? context.selectComponent(selector) : null + if (!instance) { + console.warn('未找到组件,请检查selector是否正确') + return null + } + return instance +} export const unitConvert = (value) => { - var _a; - if (typeof value === 'string') { - if (value.includes('rpx')) { - return (parseInt(value, 10) * ((_a = systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.screenWidth) !== null && _a !== void 0 ? _a : 750)) / 750; - } - return parseInt(value, 10); + let _a + if (typeof value === 'string') { + if (value.includes('rpx')) { + return (parseInt(value, 10) * ((_a = systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.screenWidth) !== null && _a !== void 0 ? _a : 750)) / 750 } - return value !== null && value !== void 0 ? value : 0; -}; + return parseInt(value, 10) + } + return value !== null && value !== void 0 ? value : 0 +} export const setIcon = (iconName, icon, defaultIcon) => { - if (icon) { - if (typeof icon === 'string') { - return { - [`${iconName}Name`]: icon, - [`${iconName}Data`]: {}, - }; - } - else if (typeof icon === 'object') { - return { - [`${iconName}Name`]: '', - [`${iconName}Data`]: icon, - }; - } - else { - return { - [`${iconName}Name`]: defaultIcon, - [`${iconName}Data`]: {}, - }; - } - } - return { + if (icon) { + if (typeof icon === 'string') { + return { + [`${iconName}Name`]: icon, + [`${iconName}Data`]: {}, + } + } else if (typeof icon === 'object') { + return { [`${iconName}Name`]: '', + [`${iconName}Data`]: icon, + } + } else { + return { + [`${iconName}Name`]: defaultIcon, [`${iconName}Data`]: {}, - }; -}; -export const isBool = (val) => typeof val === 'boolean'; -export const isObject = (val) => typeof val === 'object' && val != null; -export const isString = (val) => typeof val === 'string'; -export const toCamel = (str) => str.replace(/-(\w)/g, (match, m1) => m1.toUpperCase()); + } + } + } + return { + [`${iconName}Name`]: '', + [`${iconName}Data`]: {}, + } +} +export const isBool = (val) => typeof val === 'boolean' +export const isObject = (val) => typeof val === 'object' && val != null +export const isString = (val) => typeof val === 'string' +export const toCamel = (str) => str.replace(/-(\w)/g, (match, m1) => m1.toUpperCase()) export const getCurrentPage = function () { - const pages = getCurrentPages(); - return pages[pages.length - 1]; -}; + const pages = getCurrentPages() + return pages[pages.length - 1] +} export const uniqueFactory = (compName) => { - let number = 0; - return () => `${prefix}_${compName}_${number++}`; -}; + let number = 0 + return () => `${prefix}_${compName}_${number++}` +} export const calcIcon = (icon, defaultIcon) => { - if (icon && ((isBool(icon) && defaultIcon) || isString(icon))) { - return { name: isBool(icon) ? defaultIcon : icon }; - } - if (isObject(icon)) { - return icon; - } - return null; -}; + if (icon && ((isBool(icon) && defaultIcon) || isString(icon))) { + return {name: isBool(icon) ? defaultIcon : icon} + } + if (isObject(icon)) { + return icon + } + return null +} export const isOverSize = (size, sizeLimit) => { - var _a; - if (!sizeLimit) - return false; - const base = 1000; - const unitMap = { - B: 1, - KB: base, - MB: base * base, - GB: base * base * base, - }; - const computedSize = typeof sizeLimit === 'number' ? sizeLimit * base : (sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size) * unitMap[(_a = sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.unit) !== null && _a !== void 0 ? _a : 'KB']; - return size > computedSize; -}; -export const rpx2px = (rpx) => Math.floor((systemInfo.windowWidth * rpx) / 750); -export const nextTick = () => { - return new Promise((resolve) => { - wx.nextTick(() => { - resolve(); - }); - }); -}; + let _a + if (!sizeLimit) return false + const base = 1000 + const unitMap = { + B: 1, + KB: base, + MB: base * base, + GB: base * base * base, + } + const computedSize = typeof sizeLimit === 'number' ? sizeLimit * base : (sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size) * unitMap[(_a = sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.unit) !== null && _a !== void 0 ? _a : 'KB'] + return size > computedSize +} +export const rpx2px = (rpx) => Math.floor((systemInfo.windowWidth * rpx) / 750) +export const nextTick = () => new Promise((resolve) => { + wx.nextTick(() => { + resolve() + }) +}) diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/version.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/version.js index 2dc8e6b2..1a1e5225 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/version.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/version.js @@ -1,40 +1,40 @@ -import { getAppBaseInfo } from './wechat'; -let systemInfo; +import {getAppBaseInfo} from './wechat' + +let systemInfo function getSystemInfo() { - if (systemInfo == null) { - systemInfo = getAppBaseInfo(); - } - return systemInfo; + if (systemInfo == null) { + systemInfo = getAppBaseInfo() + } + return systemInfo } export function compareVersion(v1, v2) { - v1 = v1.split('.'); - v2 = v2.split('.'); - const len = Math.max(v1.length, v2.length); - while (v1.length < len) { - v1.push('0'); - } - while (v2.length < len) { - v2.push('0'); - } - for (let i = 0; i < len; i++) { - const num1 = parseInt(v1[i]); - const num2 = parseInt(v2[i]); - if (num1 > num2) { - return 1; - } - else if (num1 < num2) { - return -1; - } + v1 = v1.split('.') + v2 = v2.split('.') + const len = Math.max(v1.length, v2.length) + while (v1.length < len) { + v1.push('0') + } + while (v2.length < len) { + v2.push('0') + } + for (let i = 0; i < len; i++) { + const num1 = parseInt(v1[i]) + const num2 = parseInt(v2[i]) + if (num1 > num2) { + return 1 + } else if (num1 < num2) { + return -1 } - return 0; + } + return 0 } function judgeByVersion(version) { - const currentSDKVersion = getSystemInfo().SDKVersion; - return compareVersion(currentSDKVersion, version) >= 0; + const currentSDKVersion = getSystemInfo().SDKVersion + return compareVersion(currentSDKVersion, version) >= 0 } export function canIUseFormFieldButton() { - return judgeByVersion('2.10.3'); + return judgeByVersion('2.10.3') } export function canUseVirtualHost() { - return judgeByVersion('2.19.2'); + return judgeByVersion('2.19.2') } diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/common/wechat.js b/miniprogram/packageAPI/components/tdesign-miniprogram/common/wechat.js index 7feabc93..c166d728 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/common/wechat.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/common/wechat.js @@ -1,19 +1,11 @@ -export const getObserver = (context, selector) => { - return new Promise((resolve, reject) => { - context - .createIntersectionObserver(context) - .relativeToViewport() - .observe(selector, (res) => { - resolve(res); - }); - }); -}; -export const getWindowInfo = () => { - return wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync(); -}; -export const getAppBaseInfo = () => { - return wx.getAppBaseInfo ? wx.getAppBaseInfo() : wx.getSystemInfoSync(); -}; -export const getDeviceInfo = () => { - return wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync(); -}; +export const getObserver = (context, selector) => new Promise((resolve, reject) => { + context + .createIntersectionObserver(context) + .relativeToViewport() + .observe(selector, (res) => { + resolve(res) + }) +}) +export const getWindowInfo = () => (wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync()) +export const getAppBaseInfo = () => (wx.getAppBaseInfo ? wx.getAppBaseInfo() : wx.getSystemInfoSync()) +export const getDeviceInfo = () => (wx.getDeviceInfo ? wx.getDeviceInfo() : wx.getSystemInfoSync()) diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/count-down.js b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/count-down.js index 3582cb4e..b63c5a8e 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/count-down.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/count-down.js @@ -1,100 +1,104 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { isSameSecond, parseFormat, parseTimeData, TimeDataUnit } from './utils'; -const { prefix } = config; -const name = `${prefix}-count-down`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import { + isSameSecond, parseFormat, parseTimeData, TimeDataUnit +} from './utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-count-down` let CountDown = class CountDown extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-count`, `${prefix}-class-split`]; - this.properties = props; - this.observers = { - time() { - this.reset(); - }, - }; - this.data = { - prefix, - classPrefix: name, - timeDataUnit: TimeDataUnit, - timeData: parseTimeData(0), - formattedTime: '0', - }; - this.timeoutId = null; - this.lifetimes = { - detached() { - if (this.timeoutId) { - clearTimeout(this.timeoutId); - this.timeoutId = null; - } - }, - }; - this.methods = { - start() { - if (this.counting) { - return; - } - this.counting = true; - this.endTime = Date.now() + this.remain; - this.doCount(); - }, - pause() { - this.counting = false; - this.timeoutId && clearTimeout(this.timeoutId); - }, - reset() { - this.pause(); - this.remain = this.properties.time; - this.updateTime(this.remain); - if (this.properties.autoStart) { - this.start(); - } - }, - getTime() { - return Math.max(this.endTime - Date.now(), 0); - }, - updateTime(remain) { - const { format } = this.properties; - this.remain = remain; - const timeData = parseTimeData(remain); - this.triggerEvent('change', timeData); - const { timeText } = parseFormat(remain, format); - const timeRange = format.split(':'); - this.setData({ - timeRange, - timeData, - formattedTime: timeText.replace(/:/g, ' : '), - }); - if (remain === 0) { - this.pause(); - this.triggerEvent('finish'); - } - }, - doCount() { - this.timeoutId = setTimeout(() => { - const time = this.getTime(); - if (this.properties.millisecond) { - this.updateTime(time); - } - else if (!isSameSecond(time, this.remain) || time === 0) { - this.updateTime(time); - } - if (time !== 0) { - this.doCount(); - } - }, 33); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-count`, `${prefix}-class-split`] + this.properties = props + this.observers = { + time() { + this.reset() + }, } -}; + this.data = { + prefix, + classPrefix: name, + timeDataUnit: TimeDataUnit, + timeData: parseTimeData(0), + formattedTime: '0', + } + this.timeoutId = null + this.lifetimes = { + detached() { + if (this.timeoutId) { + clearTimeout(this.timeoutId) + this.timeoutId = null + } + }, + } + this.methods = { + start() { + if (this.counting) { + return + } + this.counting = true + this.endTime = Date.now() + this.remain + this.doCount() + }, + pause() { + this.counting = false + this.timeoutId && clearTimeout(this.timeoutId) + }, + reset() { + this.pause() + this.remain = this.properties.time + this.updateTime(this.remain) + if (this.properties.autoStart) { + this.start() + } + }, + getTime() { + return Math.max(this.endTime - Date.now(), 0) + }, + updateTime(remain) { + const {format} = this.properties + this.remain = remain + const timeData = parseTimeData(remain) + this.triggerEvent('change', timeData) + const {timeText} = parseFormat(remain, format) + const timeRange = format.split(':') + this.setData({ + timeRange, + timeData, + formattedTime: timeText.replace(/:/g, ' : '), + }) + if (remain === 0) { + this.pause() + this.triggerEvent('finish') + } + }, + doCount() { + this.timeoutId = setTimeout(() => { + const time = this.getTime() + if (this.properties.millisecond) { + this.updateTime(time) + } else if (!isSameSecond(time, this.remain) || time === 0) { + this.updateTime(time) + } + if (time !== 0) { + this.doCount() + } + }, 33) + }, + } + } +} CountDown = __decorate([ - wxComponent() -], CountDown); -export default CountDown; + wxComponent() +], CountDown) +export default CountDown diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/props.js index 3b67feaf..482189d3 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/props.js @@ -1,36 +1,36 @@ const props = { - autoStart: { - type: Boolean, - value: true, - }, - content: { - type: String, - value: 'default', - }, - format: { - type: String, - value: 'HH:mm:ss', - }, - millisecond: { - type: Boolean, - value: false, - }, - size: { - type: String, - value: 'medium', - }, - splitWithUnit: { - type: Boolean, - value: false, - }, - theme: { - type: String, - value: 'default', - }, - time: { - type: Number, - value: 0, - required: true, - }, -}; -export default props; + autoStart: { + type: Boolean, + value: true, + }, + content: { + type: String, + value: 'default', + }, + format: { + type: String, + value: 'HH:mm:ss', + }, + millisecond: { + type: Boolean, + value: false, + }, + size: { + type: String, + value: 'medium', + }, + splitWithUnit: { + type: Boolean, + value: false, + }, + theme: { + type: String, + value: 'default', + }, + time: { + type: Number, + value: 0, + required: true, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/utils.js b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/utils.js index 4aa6dc31..63e2da67 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/utils.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/count-down/utils.js @@ -1,61 +1,61 @@ export const TimeDataUnit = { - DD: '天', - HH: '时', - mm: '分', - ss: '秒', - SSS: '毫秒', -}; -const SECOND = 1000; -const MINUTE = 60 * SECOND; -const HOUR = 60 * MINUTE; -const DAY = 24 * HOUR; + DD: '天', + HH: '时', + mm: '分', + ss: '秒', + SSS: '毫秒', +} +const SECOND = 1000 +const MINUTE = 60 * SECOND +const HOUR = 60 * MINUTE +const DAY = 24 * HOUR export const parseTimeData = function (time) { - const days = Math.floor(time / DAY); - const hours = Math.floor((time % DAY) / HOUR); - const minutes = Math.floor((time % HOUR) / MINUTE); - const seconds = Math.floor((time % MINUTE) / SECOND); - const milliseconds = Math.floor(time % SECOND); - return { - DD: days, - HH: hours, - mm: minutes, - ss: seconds, - SSS: milliseconds, - }; -}; + const days = Math.floor(time / DAY) + const hours = Math.floor((time % DAY) / HOUR) + const minutes = Math.floor((time % HOUR) / MINUTE) + const seconds = Math.floor((time % MINUTE) / SECOND) + const milliseconds = Math.floor(time % SECOND) + return { + DD: days, + HH: hours, + mm: minutes, + ss: seconds, + SSS: milliseconds, + } +} export const isSameSecond = function (time1, time2) { - return Math.floor(time1 / 1000) === Math.floor(time2 / 1000); -}; + return Math.floor(time1 / 1000) === Math.floor(time2 / 1000) +} export const parseFormat = function (time, format) { - const obj = { - 'D+': Math.floor(time / 86400000), - 'H+': Math.floor((time % 86400000) / 3600000), - 'm+': Math.floor((time % 3600000) / 60000), - 's+': Math.floor((time % 60000) / 1000), - 'S+': Math.floor(time % 1000), - }; - const timeList = []; - let timeText = format; - Object.keys(obj).forEach((prop) => { - if (new RegExp(`(${prop})`).test(timeText)) { - timeText = timeText.replace(RegExp.$1, (match, offset, source) => { - const v = `${obj[prop]}`; - let digit = v; - if (match.length > 1) { - digit = (match.replace(new RegExp(match[0], 'g'), '0') + v).substr(v.length); - } - const unit = source.substr(offset + match.length); - const last = timeList[timeList.length - 1]; - if (last) { - const index = last.unit.indexOf(match); - if (index !== -1) { - last.unit = last.unit.substr(0, index); - } - } - timeList.push({ digit, unit, match }); - return digit; - }); + const obj = { + 'D+': Math.floor(time / 86400000), + 'H+': Math.floor((time % 86400000) / 3600000), + 'm+': Math.floor((time % 3600000) / 60000), + 's+': Math.floor((time % 60000) / 1000), + 'S+': Math.floor(time % 1000), + } + const timeList = [] + let timeText = format + Object.keys(obj).forEach((prop) => { + if (new RegExp(`(${prop})`).test(timeText)) { + timeText = timeText.replace(RegExp.$1, (match, offset, source) => { + const v = `${obj[prop]}` + let digit = v + if (match.length > 1) { + digit = (match.replace(new RegExp(match[0], 'g'), '0') + v).substr(v.length) } - }); - return { timeText, timeList }; -}; + const unit = source.substr(offset + match.length) + const last = timeList[timeList.length - 1] + if (last) { + const index = last.unit.indexOf(match) + if (index !== -1) { + last.unit = last.unit.substr(0, index) + } + } + timeList.push({digit, unit, match}) + return digit + }) + } + }) + return {timeText, timeList} +} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/icon.js b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/icon.js index 935f9d40..2780b686 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/icon.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/icon.js @@ -1,68 +1,73 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { styles, addUnit, getRect } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-icon`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {styles, addUnit, getRect} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } + function rejected(value) { try { step(generator.throw(value)) } catch (e) { reject(e) } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } + step((generator = generator.apply(thisArg, _arguments || [])).next()) + }) +} + +const {prefix} = config +const name = `${prefix}-icon` let Icon = class Icon extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.properties = props; - this.data = { - componentPrefix: prefix, - classPrefix: name, - isImage: false, - iconStyle: undefined, - }; - this.observers = { - 'name, color, size, style'() { - this.setIconStyle(); - }, - }; - this.methods = { - onTap(event) { - this.triggerEvent('click', event.detail); - }, - setIconStyle() { - return __awaiter(this, void 0, void 0, function* () { - const { name, color, size, classPrefix } = this.data; - const isImage = name.indexOf('/') !== -1; - const sizeValue = addUnit(size); - const colorStyle = color ? { color: color } : {}; - const fontStyle = size ? { 'font-size': sizeValue } : {}; - const iconStyle = Object.assign(Object.assign({}, colorStyle), fontStyle); - if (isImage) { - const { height } = yield getRect(this, `.${classPrefix}`); - const iconSize = sizeValue || addUnit(height); - iconStyle.width = iconSize; - iconStyle.height = iconSize; - } - this.setData({ - isImage, - iconStyle: `${styles(iconStyle)}`, - }); - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.properties = props + this.data = { + componentPrefix: prefix, + classPrefix: name, + isImage: false, + iconStyle: undefined, } -}; + this.observers = { + 'name, color, size, style': function () { + this.setIconStyle() + }, + } + this.methods = { + onTap(event) { + this.triggerEvent('click', event.detail) + }, + setIconStyle() { + return __awaiter(this, void 0, void 0, function* () { + const { + name, color, size, classPrefix + } = this.data + const isImage = name.indexOf('/') !== -1 + const sizeValue = addUnit(size) + const colorStyle = color ? {color} : {} + const fontStyle = size ? {'font-size': sizeValue} : {} + const iconStyle = {...colorStyle, ...fontStyle} + if (isImage) { + const {height} = yield getRect(this, `.${classPrefix}`) + const iconSize = sizeValue || addUnit(height) + iconStyle.width = iconSize + iconStyle.height = iconSize + } + this.setData({ + isImage, + iconStyle: `${styles(iconStyle)}`, + }) + }) + }, + } + } +} Icon = __decorate([ - wxComponent() -], Icon); -export default Icon; + wxComponent() +], Icon) +export default Icon diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/props.js index 4d0ffa25..a7ebfa6a 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/props.js @@ -1,19 +1,19 @@ const props = { - color: { - type: String, - value: '', - }, - name: { - type: String, - value: '', - required: true, - }, - prefix: { - type: String, - value: '', - }, - size: { - type: null, - }, -}; -export default props; + color: { + type: String, + value: '', + }, + name: { + type: String, + value: '', + required: true, + }, + prefix: { + type: String, + value: '', + }, + size: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/icon/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/icon/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/image/image.js b/miniprogram/packageAPI/components/tdesign-miniprogram/image/image.js index 0cc93cac..6a15561d 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/image/image.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/image/image.js @@ -1,97 +1,98 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import ImageProps from './props'; -import config from '../common/config'; -import { addUnit, getRect, appBaseInfo } from '../common/utils'; -import { compareVersion } from '../common/version'; -const { prefix } = config; -const name = `${prefix}-image`; +import {SuperComponent, wxComponent} from '../common/src/index' +import ImageProps from './props' +import config from '../common/config' +import {addUnit, getRect, appBaseInfo} from '../common/utils' +import {compareVersion} from '../common/version' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-image` let Image = class Image extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-load`, `${prefix}-class-image`, `${prefix}-class-error`]; - this.options = { - multipleSlots: true, - }; - this.properties = ImageProps; - this.data = { - prefix, + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-load`, `${prefix}-class-image`, `${prefix}-class-error`] + this.options = { + multipleSlots: true, + } + this.properties = ImageProps + this.data = { + prefix, + isLoading: true, + isFailed: false, + innerStyle: '', + classPrefix: name, + } + this.preSrc = '' + this.observers = { + src() { + if (this.preSrc === this.properties.src) return + this.update() + }, + 'width, height': function (width, height) { + this.calcSize(width, height) + }, + } + this.methods = { + onLoaded(e) { + const sdkVersion = appBaseInfo.SDKVersion + const {mode, tId} = this.properties + const isInCompatible = compareVersion(sdkVersion, '2.10.3') < 0 + if (mode === 'heightFix' && isInCompatible) { + const {height: picHeight, width: picWidth} = e.detail + getRect(this, `#${tId || 'image'}`).then((rect) => { + const {height} = rect + const resultWidth = ((height / picHeight) * picWidth).toFixed(2) + this.setData({innerStyle: `height: ${addUnit(height)}; width: ${resultWidth}px;`}) + }) + } + this.setData({ + isLoading: false, + isFailed: false, + }) + this.triggerEvent('load', e.detail) + }, + onLoadError(e) { + this.setData({ + isLoading: false, + isFailed: true, + }) + this.triggerEvent('error', e.detail) + }, + calcSize(width, height) { + let innerStyle = '' + if (width) { + innerStyle += `width: ${addUnit(width)};` + } + if (height) { + innerStyle += `height: ${addUnit(height)};` + } + this.setData({ + innerStyle, + }) + }, + update() { + const {src} = this.properties + this.preSrc = src + if (!src) { + this.onLoadError({errMsg: '图片链接为空'}) + } else { + this.setData({ isLoading: true, isFailed: false, - innerStyle: '', - classPrefix: name, - }; - this.preSrc = ''; - this.observers = { - src() { - if (this.preSrc === this.properties.src) - return; - this.update(); - }, - 'width, height'(width, height) { - this.calcSize(width, height); - }, - }; - this.methods = { - onLoaded(e) { - const sdkVersion = appBaseInfo.SDKVersion; - const { mode, tId } = this.properties; - const isInCompatible = compareVersion(sdkVersion, '2.10.3') < 0; - if (mode === 'heightFix' && isInCompatible) { - const { height: picHeight, width: picWidth } = e.detail; - getRect(this, `#${tId || 'image'}`).then((rect) => { - const { height } = rect; - const resultWidth = ((height / picHeight) * picWidth).toFixed(2); - this.setData({ innerStyle: `height: ${addUnit(height)}; width: ${resultWidth}px;` }); - }); - } - this.setData({ - isLoading: false, - isFailed: false, - }); - this.triggerEvent('load', e.detail); - }, - onLoadError(e) { - this.setData({ - isLoading: false, - isFailed: true, - }); - this.triggerEvent('error', e.detail); - }, - calcSize(width, height) { - let innerStyle = ''; - if (width) { - innerStyle += `width: ${addUnit(width)};`; - } - if (height) { - innerStyle += `height: ${addUnit(height)};`; - } - this.setData({ - innerStyle, - }); - }, - update() { - const { src } = this.properties; - this.preSrc = src; - if (!src) { - this.onLoadError({ errMsg: '图片链接为空' }); - } - else { - this.setData({ - isLoading: true, - isFailed: false, - }); - } - }, - }; + }) + } + }, } -}; + } +} Image = __decorate([ - wxComponent() -], Image); -export default Image; + wxComponent() +], Image) +export default Image diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/image/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/image/index.js index 4fd39538..1f3ee0de 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/image/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/image/index.js @@ -1,2 +1,2 @@ -export * from './props'; -export * from './image'; +export * from './props' +export * from './image' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/image/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/image/props.js index b2a17dac..5c2b5ae1 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/image/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/image/props.js @@ -1,45 +1,45 @@ const props = { - error: { - type: String, - value: 'default', - }, - height: { - type: null, - }, - lazy: { - type: Boolean, - value: false, - }, - loading: { - type: String, - value: 'default', - }, - mode: { - type: String, - value: 'scaleToFill', - }, - shape: { - type: String, - value: 'square', - }, - showMenuByLongpress: { - type: Boolean, - value: false, - }, - src: { - type: String, - value: '', - }, - tId: { - type: String, - value: '', - }, - webp: { - type: Boolean, - value: false, - }, - width: { - type: null, - }, -}; -export default props; + error: { + type: String, + value: 'default', + }, + height: { + type: null, + }, + lazy: { + type: Boolean, + value: false, + }, + loading: { + type: String, + value: 'default', + }, + mode: { + type: String, + value: 'scaleToFill', + }, + shape: { + type: String, + value: 'square', + }, + showMenuByLongpress: { + type: Boolean, + value: false, + }, + src: { + type: String, + value: '', + }, + tId: { + type: String, + value: '', + }, + webp: { + type: Boolean, + value: false, + }, + width: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/image/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/image/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/image/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/image/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/index.js index 9af8cc5b..8bf2eb23 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/index.js @@ -1,4 +1,4 @@ -export { default as ActionSheet, ActionSheetTheme } from './action-sheet/index'; -export { default as Dialog } from './dialog/index'; -export { default as Message } from './message/index'; -export { default as Toast } from './toast/index'; +export {default as ActionSheet, ActionSheetTheme} from './action-sheet/index' +export {default as Dialog} from './dialog/index' +export {default as Message} from './message/index' +export {default as Toast} from './toast/index' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/index.js index 2806bd66..075515f6 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/index.js @@ -1,3 +1,3 @@ -export * from './props'; -export * from './type'; -export * from './loading'; +export * from './props' +export * from './type' +export * from './loading' diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/loading.js b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/loading.js index f59a423d..2a5dd7fa 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/loading.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/loading.js @@ -1,61 +1,63 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-loading`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-loading` let Loading = class Loading extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-text`, `${prefix}-class-indicator`]; - this.data = { - prefix, - classPrefix: name, - show: true, - }; - this.options = { - multipleSlots: true, - }; - this.properties = Object.assign({}, props); - this.timer = null; - this.observers = { - loading(cur) { - const { delay } = this.properties; - if (this.timer) { - clearTimeout(this.timer); - } - if (cur) { - if (delay) { - this.timer = setTimeout(() => { - this.setData({ show: cur }); - this.timer = null; - }, delay); - } - else { - this.setData({ show: cur }); - } - } - else { - this.setData({ show: cur }); - } - }, - }; - this.lifetimes = { - detached() { - clearTimeout(this.timer); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-text`, `${prefix}-class-indicator`] + this.data = { + prefix, + classPrefix: name, + show: true, } - refreshPage() { - this.triggerEvent('reload'); + this.options = { + multipleSlots: true, } -}; + this.properties = {...props} + this.timer = null + this.observers = { + loading(cur) { + const {delay} = this.properties + if (this.timer) { + clearTimeout(this.timer) + } + if (cur) { + if (delay) { + this.timer = setTimeout(() => { + this.setData({show: cur}) + this.timer = null + }, delay) + } else { + this.setData({show: cur}) + } + } else { + this.setData({show: cur}) + } + }, + } + this.lifetimes = { + detached() { + clearTimeout(this.timer) + }, + } + } + + refreshPage() { + this.triggerEvent('reload') + } +} Loading = __decorate([ - wxComponent() -], Loading); -export default Loading; + wxComponent() +], Loading) +export default Loading diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/props.js index d86ae7a4..70e5e761 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/props.js @@ -1,51 +1,51 @@ const props = { - delay: { - type: Number, - value: 0, - }, - duration: { - type: Number, - value: 800, - }, - externalClasses: { - type: Array, - }, - indicator: { - type: Boolean, - value: true, - }, - inheritColor: { - type: Boolean, - value: false, - }, - layout: { - type: String, - value: 'horizontal', - }, - loading: { - type: Boolean, - value: true, - }, - pause: { - type: Boolean, - value: false, - }, - progress: { - type: Number, - }, - reverse: { - type: Boolean, - }, - size: { - type: String, - value: '40rpx', - }, - text: { - type: String, - }, - theme: { - type: String, - value: 'circular', - }, -}; -export default props; + delay: { + type: Number, + value: 0, + }, + duration: { + type: Number, + value: 800, + }, + externalClasses: { + type: Array, + }, + indicator: { + type: Boolean, + value: true, + }, + inheritColor: { + type: Boolean, + value: false, + }, + layout: { + type: String, + value: 'horizontal', + }, + loading: { + type: Boolean, + value: true, + }, + pause: { + type: Boolean, + value: false, + }, + progress: { + type: Number, + }, + reverse: { + type: Boolean, + }, + size: { + type: String, + value: '40rpx', + }, + text: { + type: String, + }, + theme: { + type: String, + value: 'circular', + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/loading/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/loading/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/page-scroll.js b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/page-scroll.js index 1d0dcba8..4217ce35 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/page-scroll.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/page-scroll.js @@ -1,41 +1,36 @@ -import { getCurrentPage } from '../common/utils'; +import {getCurrentPage} from '../common/utils' + const onPageScroll = function (event) { - const page = getCurrentPage(); - if (!page) - return; - const { pageScroller } = page; - pageScroller === null || pageScroller === void 0 ? void 0 : pageScroller.forEach((scroller) => { - if (typeof scroller === 'function') { - scroller(event); - } - }); -}; -export default (funcName = 'onScroll') => { - return Behavior({ - attached() { - var _a; - const page = getCurrentPage(); - if (!page) - return; - const bindScroller = (_a = this[funcName]) === null || _a === void 0 ? void 0 : _a.bind(this); - if (bindScroller) { - this._pageScroller = bindScroller; - } - if (Array.isArray(page.pageScroller)) { - page.pageScroller.push(bindScroller); - } - else { - page.pageScroller = - typeof page.onPageScroll === 'function' ? [page.onPageScroll.bind(page), bindScroller] : [bindScroller]; - } - page.onPageScroll = onPageScroll; - }, - detached() { - var _a; - const page = getCurrentPage(); - if (!page) - return; - page.pageScroller = ((_a = page.pageScroller) === null || _a === void 0 ? void 0 : _a.filter((item) => item !== this._pageScroller)) || []; - }, - }); -}; + const page = getCurrentPage() + if (!page) return + const {pageScroller} = page + pageScroller === null || pageScroller === void 0 ? void 0 : pageScroller.forEach((scroller) => { + if (typeof scroller === 'function') { + scroller(event) + } + }) +} +export default (funcName = 'onScroll') => Behavior({ + attached() { + let _a + const page = getCurrentPage() + if (!page) return + const bindScroller = (_a = this[funcName]) === null || _a === void 0 ? void 0 : _a.bind(this) + if (bindScroller) { + this._pageScroller = bindScroller + } + if (Array.isArray(page.pageScroller)) { + page.pageScroller.push(bindScroller) + } else { + page.pageScroller = + typeof page.onPageScroll === 'function' ? [page.onPageScroll.bind(page), bindScroller] : [bindScroller] + } + page.onPageScroll = onPageScroll + }, + detached() { + let _a + const page = getCurrentPage() + if (!page) return + page.pageScroller = ((_a = page.pageScroller) === null || _a === void 0 ? void 0 : _a.filter((item) => item !== this._pageScroller)) || [] + }, +}) diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/theme-change.js b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/theme-change.js index 70e44edf..cada70e1 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/theme-change.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/theme-change.js @@ -1,23 +1,24 @@ -import { appBaseInfo } from '../common/utils'; +import {appBaseInfo} from '../common/utils' + const themeChangeBehavior = Behavior({ - data: { - theme: 'light', + data: { + theme: 'light', + }, + attached() { + this._initTheme() + }, + methods: { + _initTheme() { + const that = this + that.setData({ + theme: appBaseInfo.theme, + }) + wx.onThemeChange((res) => { + that.setData({ + theme: res.theme, + }) + }) }, - attached() { - this._initTheme(); - }, - methods: { - _initTheme() { - const that = this; - that.setData({ - theme: appBaseInfo.theme, - }); - wx.onThemeChange((res) => { - that.setData({ - theme: res.theme, - }); - }); - }, - }, -}); -export default themeChangeBehavior; + }, +}) +export default themeChangeBehavior diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/touch.js b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/touch.js index cbabccc0..49a6f981 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/touch.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/touch.js @@ -1,35 +1,35 @@ -const MinDistance = 10; +const MinDistance = 10 const getDirection = (x, y) => { - if (x > y && x > MinDistance) { - return 'horizontal'; - } - if (y > x && y > MinDistance) { - return 'vertical'; - } - return ''; -}; + if (x > y && x > MinDistance) { + return 'horizontal' + } + if (y > x && y > MinDistance) { + return 'vertical' + } + return '' +} export default Behavior({ - methods: { - resetTouchStatus() { - this.direction = ''; - this.deltaX = 0; - this.deltaY = 0; - this.offsetX = 0; - this.offsetY = 0; - }, - touchStart(event) { - this.resetTouchStatus(); - const [touch] = event.touches; - this.startX = touch.clientX; - this.startY = touch.clientY; - }, - touchMove(event) { - const [touch] = event.touches; - this.deltaX = touch.clientX - this.startX; - this.deltaY = touch.clientY - this.startY; - this.offsetX = Math.abs(this.deltaX); - this.offsetY = Math.abs(this.deltaY); - this.direction = getDirection(this.offsetX, this.offsetY); - }, + methods: { + resetTouchStatus() { + this.direction = '' + this.deltaX = 0 + this.deltaY = 0 + this.offsetX = 0 + this.offsetY = 0 }, -}); + touchStart(event) { + this.resetTouchStatus() + const [touch] = event.touches + this.startX = touch.clientX + this.startY = touch.clientY + }, + touchMove(event) { + const [touch] = event.touches + this.deltaX = touch.clientX - this.startX + this.deltaY = touch.clientY - this.startY + this.offsetX = Math.abs(this.deltaX) + this.offsetY = Math.abs(this.deltaY) + this.direction = getDirection(this.offsetX, this.offsetY) + }, + }, +}) diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/transition.js b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/transition.js index ee5215ae..ac115365 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/transition.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/transition.js @@ -1,123 +1,123 @@ -import config from '../common/config'; -const { prefix } = config; +import config from '../common/config' + +const {prefix} = config export default function transition() { - return Behavior({ - properties: { - visible: { - type: Boolean, - value: null, - observer: 'watchVisible', - }, - appear: Boolean, - name: { - type: String, - value: 'fade', - }, - durations: { - type: Number, - optionalTypes: [Array], - }, - }, - data: { - transitionClass: '', - transitionDurations: 300, - className: '', + return Behavior({ + properties: { + visible: { + type: Boolean, + value: null, + observer: 'watchVisible', + }, + appear: Boolean, + name: { + type: String, + value: 'fade', + }, + durations: { + type: Number, + optionalTypes: [Array], + }, + }, + data: { + transitionClass: '', + transitionDurations: 300, + className: '', + realVisible: false, + }, + created() { + this.status = '' + this.transitionT = 0 + }, + attached() { + this.durations = this.getDurations() + if (this.data.visible) { + this.enter() + } + this.inited = true + }, + detached() { + clearTimeout(this.transitionT) + }, + methods: { + watchVisible(curr, prev) { + if (this.inited && curr !== prev) { + curr ? this.enter() : this.leave() + } + }, + getDurations() { + const {durations} = this.data + if (Array.isArray(durations)) { + return durations.map((item) => Number(item)) + } + return [Number(durations), Number(durations)] + }, + enter() { + const {name} = this.data + const [duration] = this.durations + this.status = 'entering' + this.setData({ + realVisible: true, + transitionClass: `${prefix}-${name}-enter ${prefix}-${name}-enter-active`, + }) + setTimeout(() => { + this.setData({ + transitionClass: `${prefix}-${name}-enter-active ${prefix}-${name}-enter-to`, + }) + }, 30) + if (typeof duration === 'number' && duration > 0) { + this.transitionT = setTimeout(this.entered.bind(this), duration + 30) + } + }, + entered() { + this.customDuration = false + clearTimeout(this.transitionT) + this.status = 'entered' + this.setData({ + transitionClass: '', + }) + }, + leave() { + const {name} = this.data + const [, duration] = this.durations + this.status = 'leaving' + this.setData({ + transitionClass: `${prefix}-${name}-leave ${prefix}-${name}-leave-active`, + }) + clearTimeout(this.transitionT) + setTimeout(() => { + this.setData({ + transitionClass: `${prefix}-${name}-leave-active ${prefix}-${name}-leave-to`, + }) + }, 30) + if (typeof duration === 'number' && duration > 0) { + this.customDuration = true + this.transitionT = setTimeout(this.leaved.bind(this), duration + 30) + } + }, + leaved() { + this.customDuration = false + this.triggerEvent('leaved') + clearTimeout(this.transitionT) + this.status = 'leaved' + this.setData({ + transitionClass: '', + }) + }, + onTransitionEnd() { + if (this.customDuration) { + return + } + clearTimeout(this.transitionT) + if (this.status === 'entering' && this.data.visible) { + this.entered() + } else if (this.status === 'leaving' && !this.data.visible) { + this.leaved() + this.setData({ realVisible: false, - }, - created() { - this.status = ''; - this.transitionT = 0; - }, - attached() { - this.durations = this.getDurations(); - if (this.data.visible) { - this.enter(); - } - this.inited = true; - }, - detached() { - clearTimeout(this.transitionT); - }, - methods: { - watchVisible(curr, prev) { - if (this.inited && curr !== prev) { - curr ? this.enter() : this.leave(); - } - }, - getDurations() { - const { durations } = this.data; - if (Array.isArray(durations)) { - return durations.map((item) => Number(item)); - } - return [Number(durations), Number(durations)]; - }, - enter() { - const { name } = this.data; - const [duration] = this.durations; - this.status = 'entering'; - this.setData({ - realVisible: true, - transitionClass: `${prefix}-${name}-enter ${prefix}-${name}-enter-active`, - }); - setTimeout(() => { - this.setData({ - transitionClass: `${prefix}-${name}-enter-active ${prefix}-${name}-enter-to`, - }); - }, 30); - if (typeof duration === 'number' && duration > 0) { - this.transitionT = setTimeout(this.entered.bind(this), duration + 30); - } - }, - entered() { - this.customDuration = false; - clearTimeout(this.transitionT); - this.status = 'entered'; - this.setData({ - transitionClass: '', - }); - }, - leave() { - const { name } = this.data; - const [, duration] = this.durations; - this.status = 'leaving'; - this.setData({ - transitionClass: `${prefix}-${name}-leave ${prefix}-${name}-leave-active`, - }); - clearTimeout(this.transitionT); - setTimeout(() => { - this.setData({ - transitionClass: `${prefix}-${name}-leave-active ${prefix}-${name}-leave-to`, - }); - }, 30); - if (typeof duration === 'number' && duration > 0) { - this.customDuration = true; - this.transitionT = setTimeout(this.leaved.bind(this), duration + 30); - } - }, - leaved() { - this.customDuration = false; - this.triggerEvent('leaved'); - clearTimeout(this.transitionT); - this.status = 'leaved'; - this.setData({ - transitionClass: '', - }); - }, - onTransitionEnd() { - if (this.customDuration) { - return; - } - clearTimeout(this.transitionT); - if (this.status === 'entering' && this.data.visible) { - this.entered(); - } - else if (this.status === 'leaving' && !this.data.visible) { - this.leaved(); - this.setData({ - realVisible: false, - }); - } - }, - }, - }); + }) + } + }, + }, + }) } diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/using-custom-navbar.js b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/using-custom-navbar.js index e9bf8e3c..7c247cf3 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/using-custom-navbar.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/mixins/using-custom-navbar.js @@ -1,34 +1,35 @@ -import { systemInfo } from '../common/utils'; +import {systemInfo} from '../common/utils' + const useCustomNavbarBehavior = Behavior({ - properties: { - usingCustomNavbar: { - type: Boolean, - value: false, - }, - customNavbarHeight: { - type: Number, - value: 0, - }, + properties: { + usingCustomNavbar: { + type: Boolean, + value: false, }, - data: { - distanceTop: 0, + customNavbarHeight: { + type: Number, + value: 0, }, - lifetimes: { - attached() { - if (this.properties.usingCustomNavbar) { - this.calculateCustomNavbarDistanceTop(); - } - }, + }, + data: { + distanceTop: 0, + }, + lifetimes: { + attached() { + if (this.properties.usingCustomNavbar) { + this.calculateCustomNavbarDistanceTop() + } }, - methods: { - calculateCustomNavbarDistanceTop() { - const { statusBarHeight } = systemInfo; - const menuButton = wx.getMenuButtonBoundingClientRect(); - const distance = menuButton.top + menuButton.bottom - statusBarHeight; - this.setData({ - distanceTop: Math.max(distance, this.properties.customNavbarHeight + statusBarHeight), - }); - }, + }, + methods: { + calculateCustomNavbarDistanceTop() { + const {statusBarHeight} = systemInfo + const menuButton = wx.getMenuButtonBoundingClientRect() + const distance = menuButton.top + menuButton.bottom - statusBarHeight + this.setData({ + distanceTop: Math.max(distance, this.properties.customNavbarHeight + statusBarHeight), + }) }, -}); -export default useCustomNavbarBehavior; + }, +}) +export default useCustomNavbarBehavior diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/navbar.js b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/navbar.js index 32a7cd80..0c12d2b5 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/navbar.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/navbar.js @@ -1,163 +1,164 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import { getRect, systemInfo } from '../common/utils'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-navbar`; +import {SuperComponent, wxComponent} from '../common/src/index' +import {getRect, systemInfo} from '../common/utils' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } + function rejected(value) { try { step(generator.throw(value)) } catch (e) { reject(e) } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } + step((generator = generator.apply(thisArg, _arguments || [])).next()) + }) +} + +const {prefix} = config +const name = `${prefix}-navbar` let Navbar = class Navbar extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-placeholder`, - `${prefix}-class-content`, - `${prefix}-class-title`, - `${prefix}-class-left`, - `${prefix}-class-center`, - `${prefix}-class-left-icon`, - `${prefix}-class-home-icon`, - `${prefix}-class-capsule`, - `${prefix}-class-nav-btn`, - ]; - this.timer = null; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.observers = { - visible(visible) { - const { animation } = this.properties; - const visibleClass = `${name}${visible ? '--visible' : '--hide'}`; - this.setData({ - visibleClass: `${visibleClass}${animation ? '-animation' : ''}`, - }); - if (this.timer) { - clearTimeout(this.timer); - } - if (animation) { - this.timer = setTimeout(() => { - this.setData({ - visibleClass, - }); - }, 300); - } - }, - 'title,titleMaxLength'() { - const { title } = this.properties; - const titleMaxLength = this.properties.titleMaxLength || Number.MAX_SAFE_INTEGER; - let temp = title.slice(0, titleMaxLength); - if (titleMaxLength < title.length) - temp += '...'; - this.setData({ - showTitle: temp, - }); - }, - }; - this.data = { - prefix, - classPrefix: name, - boxStyle: '', - showTitle: '', - hideLeft: false, - hideCenter: false, - }; - this.methods = { - queryElements(capsuleRect) { - Promise.all([ - getRect(this, `.${this.data.classPrefix}__left`), - getRect(this, `.${this.data.classPrefix}__center`), - ]).then(([leftRect, centerRect]) => { - if (leftRect.right > capsuleRect.left) { - this.setData({ - hideLeft: true, - hideCenter: true, - }); - } - else if (centerRect.right > capsuleRect.left) { - this.setData({ - hideLeft: false, - hideCenter: true, - }); - } - else { - this.setData({ - hideLeft: false, - hideCenter: false, - }); - } - }); - }, - goBack() { - const { delta } = this.data; - const that = this; - this.triggerEvent('go-back'); - if (delta > 0) { - wx.navigateBack({ - delta, - fail(e) { - that.triggerEvent('fail', e); - }, - complete(e) { - that.triggerEvent('complete', e); - }, - success(e) { - that.triggerEvent('success', e); - }, - }); - } - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-placeholder`, + `${prefix}-class-content`, + `${prefix}-class-title`, + `${prefix}-class-left`, + `${prefix}-class-center`, + `${prefix}-class-left-icon`, + `${prefix}-class-home-icon`, + `${prefix}-class-capsule`, + `${prefix}-class-nav-btn`, + ] + this.timer = null + this.options = { + multipleSlots: true, } - attached() { - return __awaiter(this, void 0, void 0, function* () { - let rect = null; - if (wx.getMenuButtonBoundingClientRect) { - rect = wx.getMenuButtonBoundingClientRect(); - } - if (!rect || !systemInfo) - return; - const { right } = yield getRect(this, `.${name}__left`); - const boxStyleList = []; - boxStyleList.push(`--td-navbar-padding-top: ${systemInfo.statusBarHeight}px`); - if (rect && (systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.windowWidth)) { - const maxSpacing = Math.max(right, systemInfo.windowWidth - rect.left); - boxStyleList.push(`--td-navbar-center-left: ${maxSpacing}px`); - boxStyleList.push(`--td-navbar-center-width: ${rect.left - maxSpacing}px`); - boxStyleList.push(`--td-navbar-right: ${systemInfo.windowWidth - rect.left}px`); - } - boxStyleList.push(`--td-navbar-capsule-height: ${rect.height}px`); - boxStyleList.push(`--td-navbar-capsule-width: ${rect.width}px`); - boxStyleList.push(`--td-navbar-height: ${(rect.top - systemInfo.statusBarHeight) * 2 + rect.height}px`); + this.properties = props + this.observers = { + visible(visible) { + const {animation} = this.properties + const visibleClass = `${name}${visible ? '--visible' : '--hide'}` + this.setData({ + visibleClass: `${visibleClass}${animation ? '-animation' : ''}`, + }) + if (this.timer) { + clearTimeout(this.timer) + } + if (animation) { + this.timer = setTimeout(() => { this.setData({ - boxStyle: `${boxStyleList.join('; ')}`, - }); - if (wx.onMenuButtonBoundingClientRectWeightChange) { - wx.onMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)); - } - }); + visibleClass, + }) + }, 300) + } + }, + 'title,titleMaxLength': function () { + const {title} = this.properties + const titleMaxLength = this.properties.titleMaxLength || Number.MAX_SAFE_INTEGER + let temp = title.slice(0, titleMaxLength) + if (titleMaxLength < title.length) temp += '...' + this.setData({ + showTitle: temp, + }) + }, + } + this.data = { + prefix, + classPrefix: name, + boxStyle: '', + showTitle: '', + hideLeft: false, + hideCenter: false, } - detached() { - if (wx.offMenuButtonBoundingClientRectWeightChange) { - wx.offMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)); + this.methods = { + queryElements(capsuleRect) { + Promise.all([ + getRect(this, `.${this.data.classPrefix}__left`), + getRect(this, `.${this.data.classPrefix}__center`), + ]).then(([leftRect, centerRect]) => { + if (leftRect.right > capsuleRect.left) { + this.setData({ + hideLeft: true, + hideCenter: true, + }) + } else if (centerRect.right > capsuleRect.left) { + this.setData({ + hideLeft: false, + hideCenter: true, + }) + } else { + this.setData({ + hideLeft: false, + hideCenter: false, + }) + } + }) + }, + goBack() { + const {delta} = this.data + const that = this + this.triggerEvent('go-back') + if (delta > 0) { + wx.navigateBack({ + delta, + fail(e) { + that.triggerEvent('fail', e) + }, + complete(e) { + that.triggerEvent('complete', e) + }, + success(e) { + that.triggerEvent('success', e) + }, + }) } + }, + } + } + + attached() { + return __awaiter(this, void 0, void 0, function* () { + let rect = null + if (wx.getMenuButtonBoundingClientRect) { + rect = wx.getMenuButtonBoundingClientRect() + } + if (!rect || !systemInfo) return + const {right} = yield getRect(this, `.${name}__left`) + const boxStyleList = [] + boxStyleList.push(`--td-navbar-padding-top: ${systemInfo.statusBarHeight}px`) + if (rect && (systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.windowWidth)) { + const maxSpacing = Math.max(right, systemInfo.windowWidth - rect.left) + boxStyleList.push(`--td-navbar-center-left: ${maxSpacing}px`) + boxStyleList.push(`--td-navbar-center-width: ${rect.left - maxSpacing}px`) + boxStyleList.push(`--td-navbar-right: ${systemInfo.windowWidth - rect.left}px`) + } + boxStyleList.push(`--td-navbar-capsule-height: ${rect.height}px`) + boxStyleList.push(`--td-navbar-capsule-width: ${rect.width}px`) + boxStyleList.push(`--td-navbar-height: ${(rect.top - systemInfo.statusBarHeight) * 2 + rect.height}px`) + this.setData({ + boxStyle: `${boxStyleList.join('; ')}`, + }) + if (wx.onMenuButtonBoundingClientRectWeightChange) { + wx.onMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)) + } + }) + } + + detached() { + if (wx.offMenuButtonBoundingClientRectWeightChange) { + wx.offMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)) } -}; + } +} Navbar = __decorate([ - wxComponent() -], Navbar); -export default Navbar; + wxComponent() +], Navbar) +export default Navbar diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/props.js index 3906316e..cb208aac 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/props.js @@ -1,29 +1,29 @@ const props = { - animation: { - type: Boolean, - value: true, - }, - delta: { - type: Number, - value: 1, - }, - fixed: { - type: Boolean, - value: true, - }, - leftArrow: { - type: Boolean, - value: false, - }, - title: { - type: String, - }, - titleMaxLength: { - type: Number, - }, - visible: { - type: Boolean, - value: true, - }, -}; -export default props; + animation: { + type: Boolean, + value: true, + }, + delta: { + type: Number, + value: 1, + }, + fixed: { + type: Boolean, + value: true, + }, + leftArrow: { + type: Boolean, + value: false, + }, + title: { + type: String, + }, + titleMaxLength: { + type: Number, + }, + visible: { + type: Boolean, + value: true, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/navbar/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/row/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/row/props.js index 2faa4980..5efae84b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/row/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/row/props.js @@ -1,6 +1,6 @@ const props = { - gutter: { - type: null, - }, -}; -export default props; + gutter: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/row/row.js b/miniprogram/packageAPI/components/tdesign-miniprogram/row/row.js index a82c5c87..d71f3dbc 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/row/row.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/row/row.js @@ -1,49 +1,52 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config let Row = class Row extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = []; - this.properties = props; - this.data = { - prefix, - }; - this.relations = { - '../col/col': { - type: 'child', - linked(target) { - const { gutter } = this.data; - if (gutter) { - target.setData({ gutter }); - } - }, - }, - }; - this.observers = { - gutter() { - this.setGutter(); - }, - }; - this.methods = { - setGutter() { - const { gutter } = this.data; - const cols = this.$children; - cols.forEach((col) => { - col.setData({ gutter }); - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [] + this.properties = props + this.data = { + prefix, } -}; + this.relations = { + '../col/col': { + type: 'child', + linked(target) { + const {gutter} = this.data + if (gutter) { + target.setData({gutter}) + } + }, + }, + } + this.observers = { + gutter() { + this.setGutter() + }, + } + this.methods = { + setGutter() { + const {gutter} = this.data + const cols = this.$children + cols.forEach((col) => { + col.setData({gutter}) + }) + }, + } + } +} Row = __decorate([ - wxComponent() -], Row); -export default Row; + wxComponent() +], Row) +export default Row diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/row/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/row/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/row/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/row/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/search/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/search/props.js index 61b3da8d..09072608 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/search/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/search/props.js @@ -1,103 +1,103 @@ const props = { - action: { - type: String, - value: '', - }, - adjustPosition: { - type: Boolean, - value: true, - }, - alwaysEmbed: { - type: Boolean, - value: false, - }, - center: { - type: Boolean, - value: false, - }, - clearable: { - type: Boolean, - value: true, - }, - confirmHold: { - type: Boolean, - value: false, - }, - confirmType: { - type: String, - value: 'search', - }, - cursor: { - type: Number, - required: true, - }, - cursorSpacing: { - type: Number, - value: 0, - }, - disabled: { - type: Boolean, - value: false, - }, - focus: { - type: Boolean, - value: false, - }, - holdKeyboard: { - type: Boolean, - value: false, - }, - leftIcon: { - type: String, - value: 'search', - }, - maxcharacter: { - type: Number, - }, - maxlength: { - type: Number, - value: -1, - }, - placeholder: { - type: String, - value: '', - }, - placeholderClass: { - type: String, - value: 'input-placeholder', - }, - placeholderStyle: { - type: String, - value: '', - required: true, - }, - resultList: { - type: Array, - value: [], - }, - selectionEnd: { - type: Number, - value: -1, - }, - selectionStart: { - type: Number, - value: -1, - }, - shape: { - type: String, - value: 'square', - }, - style: { - type: String, - value: '', - }, - type: { - type: String, - value: 'text', - }, - value: { - type: String, - value: '', - }, -}; -export default props; + action: { + type: String, + value: '', + }, + adjustPosition: { + type: Boolean, + value: true, + }, + alwaysEmbed: { + type: Boolean, + value: false, + }, + center: { + type: Boolean, + value: false, + }, + clearable: { + type: Boolean, + value: true, + }, + confirmHold: { + type: Boolean, + value: false, + }, + confirmType: { + type: String, + value: 'search', + }, + cursor: { + type: Number, + required: true, + }, + cursorSpacing: { + type: Number, + value: 0, + }, + disabled: { + type: Boolean, + value: false, + }, + focus: { + type: Boolean, + value: false, + }, + holdKeyboard: { + type: Boolean, + value: false, + }, + leftIcon: { + type: String, + value: 'search', + }, + maxcharacter: { + type: Number, + }, + maxlength: { + type: Number, + value: -1, + }, + placeholder: { + type: String, + value: '', + }, + placeholderClass: { + type: String, + value: 'input-placeholder', + }, + placeholderStyle: { + type: String, + value: '', + required: true, + }, + resultList: { + type: Array, + value: [], + }, + selectionEnd: { + type: Number, + value: -1, + }, + selectionStart: { + type: Number, + value: -1, + }, + shape: { + type: String, + value: 'square', + }, + style: { + type: String, + value: '', + }, + type: { + type: String, + value: 'text', + }, + value: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/search/search.js b/miniprogram/packageAPI/components/tdesign-miniprogram/search/search.js index bc6e9f67..55ce6a2e 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/search/search.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/search/search.js @@ -1,104 +1,112 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { getCharacterLength } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-search`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {getCharacterLength} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-search` let Search = class Search extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-input-container`, - `${prefix}-class-input`, - `${prefix}-class-action`, - `${prefix}-class-left`, - `${prefix}-class-clear`, - ]; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.observers = { - resultList(val) { - const { isSelected } = this.data; - if (val.length) { - if (isSelected) { - this.setData({ - isShowResultList: false, - isSelected: false, - }); - } - else { - this.setData({ - isShowResultList: true, - }); - } - } - else { - this.setData({ - isShowResultList: false, - }); - } - }, - }; - this.data = { - classPrefix: name, - prefix, - isShowResultList: false, - isSelected: false, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-input-container`, + `${prefix}-class-input`, + `${prefix}-class-action`, + `${prefix}-class-left`, + `${prefix}-class-clear`, + ] + this.options = { + multipleSlots: true, } - onInput(e) { - let { value } = e.detail; - const { maxcharacter } = this.properties; - if (maxcharacter && typeof maxcharacter === 'number' && maxcharacter > 0) { - const { characters } = getCharacterLength('maxcharacter', value, maxcharacter); - value = characters; + this.properties = props + this.observers = { + resultList(val) { + const {isSelected} = this.data + if (val.length) { + if (isSelected) { + this.setData({ + isShowResultList: false, + isSelected: false, + }) + } else { + this.setData({ + isShowResultList: true, + }) + } + } else { + this.setData({ + isShowResultList: false, + }) } - this.setData({ - value, - }); - this.triggerEvent('change', { value }); - } - onFocus(e) { - const { value } = e.detail; - this.triggerEvent('focus', { value }); - } - onBlur(e) { - const { value } = e.detail; - this.triggerEvent('blur', { value }); - } - handleClear() { - this.setData({ value: '' }); - this.triggerEvent('clear', { value: '' }); - this.triggerEvent('change', { value: '' }); - } - onConfirm(e) { - const { value } = e.detail; - this.triggerEvent('submit', { value }); + }, } - onActionClick() { - this.triggerEvent('action-click'); + this.data = { + classPrefix: name, + prefix, + isShowResultList: false, + isSelected: false, } - onSelectResultItem(e) { - const { index } = e.currentTarget.dataset; - const item = this.properties.resultList[index]; - this.setData({ - value: item, - isSelected: true, - }); - this.triggerEvent('change', { value: item }); - this.triggerEvent('selectresult', { index, item }); + } + + onInput(e) { + let {value} = e.detail + const {maxcharacter} = this.properties + if (maxcharacter && typeof maxcharacter === 'number' && maxcharacter > 0) { + const {characters} = getCharacterLength('maxcharacter', value, maxcharacter) + value = characters } -}; + this.setData({ + value, + }) + this.triggerEvent('change', {value}) + } + + onFocus(e) { + const {value} = e.detail + this.triggerEvent('focus', {value}) + } + + onBlur(e) { + const {value} = e.detail + this.triggerEvent('blur', {value}) + } + + handleClear() { + this.setData({value: ''}) + this.triggerEvent('clear', {value: ''}) + this.triggerEvent('change', {value: ''}) + } + + onConfirm(e) { + const {value} = e.detail + this.triggerEvent('submit', {value}) + } + + onActionClick() { + this.triggerEvent('action-click') + } + + onSelectResultItem(e) { + const {index} = e.currentTarget.dataset + const item = this.properties.resultList[index] + this.setData({ + value: item, + isSelected: true, + }) + this.triggerEvent('change', {value: item}) + this.triggerEvent('selectresult', {index, item}) + } +} Search = __decorate([ - wxComponent() -], Search); -export default Search; + wxComponent() +], Search) +export default Search diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/search/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/search/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/search/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/search/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/props.js index 37b936b6..514d19b5 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/props.js @@ -1,36 +1,36 @@ const props = { - closable: { - type: null, - value: false, - }, - disabled: { - type: Boolean, - value: false, - }, - externalClasses: { - type: Array, - }, - icon: { - type: null, - }, - maxWidth: { - type: null, - }, - shape: { - type: String, - value: 'square', - }, - size: { - type: String, - value: 'medium', - }, - theme: { - type: String, - value: 'default', - }, - variant: { - type: String, - value: 'dark', - }, -}; -export default props; + closable: { + type: null, + value: false, + }, + disabled: { + type: Boolean, + value: false, + }, + externalClasses: { + type: Array, + }, + icon: { + type: null, + }, + maxWidth: { + type: null, + }, + shape: { + type: String, + value: 'square', + }, + size: { + type: String, + value: 'medium', + }, + theme: { + type: String, + value: 'default', + }, + variant: { + type: String, + value: 'dark', + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/tag.js b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/tag.js index da271cdd..cb769cf4 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/tag.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/tag.js @@ -1,93 +1,96 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { wxComponent, SuperComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { classNames, isNumber, calcIcon } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-tag`; +import {wxComponent, SuperComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {classNames, isNumber, calcIcon} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-tag` let Tag = class Tag extends SuperComponent { - constructor() { - super(...arguments); - this.data = { - prefix, - classPrefix: name, - className: '', - tagStyle: '', - }; - this.properties = props; - this.externalClasses = [`${prefix}-class`]; - this.options = { - multipleSlots: true, - }; - this.lifetimes = { - attached() { - this.setClass(); - this.setTagStyle(); - }, - }; - this.observers = { - 'size, shape, theme, variant, closable, disabled'() { - this.setClass(); - }, - maxWidth() { - this.setTagStyle(); - }, - icon(v) { - this.setData({ - _icon: calcIcon(v), - }); - }, - closable(v) { - this.setData({ - _closable: calcIcon(v, 'close'), - }); - }, - }; - this.methods = { - setClass() { - const { prefix, classPrefix } = this.data; - const { size, shape, theme, variant, closable, disabled } = this.properties; - const tagClass = [ - classPrefix, - `${classPrefix}--${theme || 'default'}`, - `${classPrefix}--${variant}`, - closable ? `${classPrefix}--closable ${prefix}-is-closable` : '', - disabled ? `${classPrefix}--disabled ${prefix}-is-disabled` : '', - `${classPrefix}--${size}`, - `${classPrefix}--${shape}`, - ]; - const className = classNames(tagClass); - this.setData({ - className, - }); - }, - setTagStyle() { - const { maxWidth } = this.properties; - if (!maxWidth) { - return ''; - } - const width = isNumber(maxWidth) ? `${maxWidth}px` : maxWidth; - this.setData({ tagStyle: `max-width:${width};` }); - }, - handleClick(e) { - if (this.data.disabled) - return; - this.triggerEvent('click', e); - }, - handleClose(e) { - if (this.data.disabled) - return; - this.triggerEvent('close', e); - }, - }; + constructor() { + super(...arguments) + this.data = { + prefix, + classPrefix: name, + className: '', + tagStyle: '', } -}; + this.properties = props + this.externalClasses = [`${prefix}-class`] + this.options = { + multipleSlots: true, + } + this.lifetimes = { + attached() { + this.setClass() + this.setTagStyle() + }, + } + this.observers = { + 'size, shape, theme, variant, closable, disabled': function () { + this.setClass() + }, + maxWidth() { + this.setTagStyle() + }, + icon(v) { + this.setData({ + _icon: calcIcon(v), + }) + }, + closable(v) { + this.setData({ + _closable: calcIcon(v, 'close'), + }) + }, + } + this.methods = { + setClass() { + const {prefix, classPrefix} = this.data + const { + size, shape, theme, variant, closable, disabled + } = this.properties + const tagClass = [ + classPrefix, + `${classPrefix}--${theme || 'default'}`, + `${classPrefix}--${variant}`, + closable ? `${classPrefix}--closable ${prefix}-is-closable` : '', + disabled ? `${classPrefix}--disabled ${prefix}-is-disabled` : '', + `${classPrefix}--${size}`, + `${classPrefix}--${shape}`, + ] + const className = classNames(tagClass) + this.setData({ + className, + }) + }, + setTagStyle() { + const {maxWidth} = this.properties + if (!maxWidth) { + return '' + } + const width = isNumber(maxWidth) ? `${maxWidth}px` : maxWidth + this.setData({tagStyle: `max-width:${width};`}) + }, + handleClick(e) { + if (this.data.disabled) return + this.triggerEvent('click', e) + }, + handleClose(e) { + if (this.data.disabled) return + this.triggerEvent('close', e) + }, + } + } +} Tag = __decorate([ - wxComponent() -], Tag); -export default Tag; + wxComponent() +], Tag) +export default Tag diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/tag/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/tag/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/index.js b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/index.js index 216f2083..14add231 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/index.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/index.js @@ -1,31 +1,33 @@ -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -import { getInstance } from '../common/utils'; -function Toast(options) { - var _a; - const { context, selector = '#t-toast' } = options, Options = __rest(options, ["context", "selector"]); - const instance = getInstance(context, selector); - if (instance) { - instance.show(Object.assign(Object.assign({}, Options), { duration: (_a = Options.duration) !== null && _a !== void 0 ? _a : 2000 })); +import {getInstance} from '../common/utils' + +const __rest = (this && this.__rest) || function (s, e) { + const t = {} + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p] } + if (s != null && typeof Object.getOwnPropertySymbols === 'function') { + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]] } + } + return t +} + +function Toast(options) { + let _a + const {context, selector = '#t-toast'} = options; const + Options = __rest(options, ['context', 'selector']) + const instance = getInstance(context, selector) + if (instance) { + instance.show({...Options, duration: (_a = Options.duration) !== null && _a !== void 0 ? _a : 2000}) + } } function showToast(options = {}) { - Toast(options); + Toast(options) } function hideToast(options = {}) { - const { context, selector = '#t-toast' } = options; - const instance = getInstance(context, selector); - if (instance) { - instance.hide(); - } + const {context, selector = '#t-toast'} = options + const instance = getInstance(context, selector) + if (instance) { + instance.hide() + } } -export { Toast as default, showToast, hideToast }; +export {Toast as default, showToast, hideToast} diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/props.js b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/props.js index cbdfd0cd..e4d6180f 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/props.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/props.js @@ -1,39 +1,39 @@ const props = { - direction: { - type: String, - value: 'row', - }, - duration: { - type: Number, - value: 2000, - }, - icon: { - type: null, - }, - message: { - type: String, - }, - overlayProps: { - type: Object, - }, - placement: { - type: String, - value: 'middle', - }, - preventScrollThrough: { - type: Boolean, - value: false, - }, - showOverlay: { - type: Boolean, - value: false, - }, - theme: { - type: String, - }, - usingCustomNavbar: { - type: Boolean, - value: false, - }, -}; -export default props; + direction: { + type: String, + value: 'row', + }, + duration: { + type: Number, + value: 2000, + }, + icon: { + type: null, + }, + message: { + type: String, + }, + overlayProps: { + type: Object, + }, + placement: { + type: String, + value: 'middle', + }, + preventScrollThrough: { + type: Boolean, + value: false, + }, + showOverlay: { + type: Boolean, + value: false, + }, + theme: { + type: String, + }, + usingCustomNavbar: { + type: Boolean, + value: false, + }, +} +export default props diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/toast.js b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/toast.js index be660e53..486565d0 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/toast.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/toast.js @@ -1,91 +1,95 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import transition from '../mixins/transition'; -import { calcIcon } from '../common/utils'; -import useCustomNavbar from '../mixins/using-custom-navbar'; -const { prefix } = config; -const name = `${prefix}-toast`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import transition from '../mixins/transition' +import {calcIcon} from '../common/utils' +import useCustomNavbar from '../mixins/using-custom-navbar' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-toast` let Toast = class Toast extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.options = { - multipleSlots: true, - }; - this.behaviors = [transition(), useCustomNavbar]; - this.hideTimer = null; - this.data = { - prefix, - classPrefix: name, - typeMapIcon: '', - }; - this.properties = props; - this.lifetimes = { - detached() { - this.destroyed(); - }, - }; - this.pageLifetimes = { - hide() { - this.hide(); - }, - }; - this.methods = { - show(options) { - if (this.hideTimer) - clearTimeout(this.hideTimer); - const iconMap = { - loading: 'loading', - success: 'check-circle', - warning: 'error-circle', - error: 'close-circle', - }; - const typeMapIcon = iconMap[options === null || options === void 0 ? void 0 : options.theme]; - const defaultOptions = { - direction: props.direction.value, - duration: props.duration.value, - icon: props.icon.value, - message: props.message.value, - placement: props.placement.value, - preventScrollThrough: props.preventScrollThrough.value, - theme: props.theme.value, - }; - const data = Object.assign(Object.assign(Object.assign({}, defaultOptions), options), { visible: true, isLoading: (options === null || options === void 0 ? void 0 : options.theme) === 'loading', _icon: calcIcon(typeMapIcon !== null && typeMapIcon !== void 0 ? typeMapIcon : options.icon) }); - const { duration } = data; - this.setData(data); - if (duration > 0) { - this.hideTimer = setTimeout(() => { - this.hide(); - }, duration); - } - }, - hide() { - var _a, _b; - if (!this.data.visible) - return; - this.setData({ visible: false }); - (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a); - this.triggerEvent('close'); - }, - destroyed() { - if (this.hideTimer) { - clearTimeout(this.hideTimer); - this.hideTimer = null; - } - this.triggerEvent('destory'); - }, - loop() { }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.options = { + multipleSlots: true, } -}; + this.behaviors = [transition(), useCustomNavbar] + this.hideTimer = null + this.data = { + prefix, + classPrefix: name, + typeMapIcon: '', + } + this.properties = props + this.lifetimes = { + detached() { + this.destroyed() + }, + } + this.pageLifetimes = { + hide() { + this.hide() + }, + } + this.methods = { + show(options) { + if (this.hideTimer) clearTimeout(this.hideTimer) + const iconMap = { + loading: 'loading', + success: 'check-circle', + warning: 'error-circle', + error: 'close-circle', + } + const typeMapIcon = iconMap[options === null || options === void 0 ? void 0 : options.theme] + const defaultOptions = { + direction: props.direction.value, + duration: props.duration.value, + icon: props.icon.value, + message: props.message.value, + placement: props.placement.value, + preventScrollThrough: props.preventScrollThrough.value, + theme: props.theme.value, + } + const data = { + ...defaultOptions, ...options, visible: true, isLoading: (options === null || options === void 0 ? void 0 : options.theme) === 'loading', _icon: calcIcon(typeMapIcon !== null && typeMapIcon !== void 0 ? typeMapIcon : options.icon) + } + const {duration} = data + this.setData(data) + if (duration > 0) { + this.hideTimer = setTimeout(() => { + this.hide() + }, duration) + } + }, + hide() { + let _a; let + _b + if (!this.data.visible) return + this.setData({visible: false}); + (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.close) === null || _b === void 0 ? void 0 : _b.call(_a) + this.triggerEvent('close') + }, + destroyed() { + if (this.hideTimer) { + clearTimeout(this.hideTimer) + this.hideTimer = null + } + this.triggerEvent('destory') + }, + loop() { }, + } + } +} Toast = __decorate([ - wxComponent() -], Toast); -export default Toast; + wxComponent() +], Toast) +export default Toast diff --git a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/type.js b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageAPI/components/tdesign-miniprogram/toast/type.js +++ b/miniprogram/packageAPI/components/tdesign-miniprogram/toast/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageAPI/pages/ai/mobilenet/index.js b/miniprogram/packageAPI/pages/ai/mobilenet/index.js index 89ef3291..4f6794a4 100644 --- a/miniprogram/packageAPI/pages/ai/mobilenet/index.js +++ b/miniprogram/packageAPI/pages/ai/mobilenet/index.js @@ -1,26 +1,26 @@ // pages/mobilenet/index.ts -import { Classifier } from './classify' +import {Classifier} from './classify' -import { FpsHelper } from '../../../../util/fps_helper' +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..f4aa3e74 100644 --- a/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js +++ b/miniprogram/packageAPI/pages/ai/mobilenet_int8/index.js @@ -1,26 +1,26 @@ // pages/mobilenet/index.ts -import { Classifier } from './classify' +import {Classifier} from './classify' -import { FpsHelper } from '../../../../util/fps_helper' +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..763466bc 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', @@ -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..9714658b 100644 --- a/miniprogram/packageAPI/pages/api/choose-address/choose-address.js +++ b/miniprogram/packageAPI/pages/api/choose-address/choose-address.js @@ -29,7 +29,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..84a0b2d4 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,7 +41,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/custom-message/custom-message.js b/miniprogram/packageAPI/pages/api/custom-message/custom-message.js index d4e307ac..f28d3631 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,7 +16,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..2173c850 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,7 +45,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/jump/jump.js b/miniprogram/packageAPI/pages/api/jump/jump.js index 70c62018..d8607d0e 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,7 +62,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/login/login.js b/miniprogram/packageAPI/pages/api/login/login.js index 3baeb750..cd28615c 100644 --- a/miniprogram/packageAPI/pages/api/login/login.js +++ b/miniprogram/packageAPI/pages/api/login/login.js @@ -14,7 +14,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -26,8 +26,7 @@ Page({ 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..161af355 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,7 +15,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -40,7 +39,7 @@ Page({ wx.cloud.callFunction({ name: 'pay', data: { - theme: 'light', + theme: 'light', action: 'unifiedorder', userInfo: { openId: openid diff --git a/miniprogram/packageAPI/pages/api/setting/setting.js b/miniprogram/packageAPI/pages/api/setting/setting.js index 7fdff7b9..3d4abed6 100644 --- a/miniprogram/packageAPI/pages/api/setting/setting.js +++ b/miniprogram/packageAPI/pages/api/setting/setting.js @@ -26,7 +26,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/share-button/share-button.js b/miniprogram/packageAPI/pages/api/share-button/share-button.js index 7d8a20eb..a50acdf6 100644 --- a/miniprogram/packageAPI/pages/api/share-button/share-button.js +++ b/miniprogram/packageAPI/pages/api/share-button/share-button.js @@ -21,7 +21,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/share/share.js b/miniprogram/packageAPI/pages/api/share/share.js index b70870d7..0b059414 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,7 +15,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js b/miniprogram/packageAPI/pages/api/soter-authentication/soter-authentication.js index 23d91313..4f31aaff 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,7 +82,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js b/miniprogram/packageAPI/pages/api/subscribe-message/subscribe-message.js index 52a4fac3..8aada640 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,14 +54,9 @@ Page({ /** * 生命周期函数--监听页面加载 */ - onUnload() { - if (wx.offThemeChange) { - wx.offThemeChange() - } - }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -69,7 +64,6 @@ Page({ 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..954ebfe4 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..c57ccd7e 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..2e09a9f7 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/Components/arModelComponent.js @@ -1,6 +1,6 @@ Component({ behaviors: ['wx://component-export'], - export(){ + export() { return {getARModelList: this.getARModelList.bind(this)} }, data: { @@ -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/3dmarker-ar/protobuf/protobuf.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/protobuf.js index 54c943d2..195d5a74 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/protobuf.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/protobuf.js @@ -2,134 +2,124 @@ * Created by zhangmiao on 2018/3/13. */ - - -(function (protobufFactory){ - //if (typeof define === 'function')//这里会不会定义重复呢?怎么去掉呢 - // define('protobuf', protobufFactory); - //else - module.exports = protobufFactory(); -})(function(){ - var protobuf = {}; -//app.globalData.protobuf = protobuf; - - /** +(function (protobufFactory) { + // if (typeof define === 'function')//这里会不会定义重复呢?怎么去掉呢 + // define('protobuf', protobufFactory); + // else + module.exports = protobufFactory() +}(function () { + const protobuf = {} + // app.globalData.protobuf = protobuf; + + /** * Build type, one of `"full"`, `"light"` or `"minimal"`. * @name build * @type {string} * @const */ - protobuf.build = "minimal"; - -// Serialization - protobuf.Writer = require("./src/writer"); - protobuf.encoder = require("./src/encoder"); - protobuf.Reader = require("./src/reader"); - -// Utility - protobuf.util = require("./src/util"); - protobuf.rpc = require("./src/rpc/service"); - protobuf.roots = require("./src/roots"); - protobuf.verifier = require("./src/verifier"); - - protobuf.tokenize = require("./src/tokenize"); - protobuf.parse = require("./src/parse"); - protobuf.common = require("./src/common"); - - protobuf.ReflectionObject = require("./src/object"); - protobuf.Namespace = require("./src/namespace"); - protobuf.Root = require("./src/root"); - protobuf.Enum = require("./src/enum"); - protobuf.Type = require("./src/type"); - protobuf.Field = require("./src/field"); - protobuf.OneOf = require("./src/oneof"); - protobuf.MapField = require("./src/mapField"); - protobuf.Service = require("./src/service"); - protobuf.Method = require("./src/method"); - protobuf.converter = require("./src/converter"); - protobuf.decoder = require("./src/decoder"); - -// Runtime - protobuf.Message = require("./src/message"); - protobuf.wrappers = require("./src/wrappers"); - -// Utility - protobuf.types = require("./src/types"); - protobuf.util = require("./src/util"); - - protobuf.configure = configure; - - - function load(filename, root, callback) { - if (typeof root === "function") { - callback = root; - root = new protobuf.Root(); - } else if (!root) - root = new protobuf.Root(); - return root.load(filename, callback); - } - - protobuf.load = load; - - function loadSync(filename, root) { - if (!root) - root = new protobuf.Root(); - return root.loadSync(filename); - } - - protobuf.loadSync = loadSync; - - -//新增weichat支持的解析pbConfig接口 - function parseFromPbString(pbString, root, callback){ - if (typeof root === "function") { - callback = root; - root = new protobuf.Root(); - } else if (!root) - root = new protobuf.Root(); - return root.parseFromPbString(pbString, callback); - } - - protobuf.parseFromPbString = parseFromPbString; - - /** + protobuf.build = 'minimal' + + // Serialization + protobuf.Writer = require('./src/writer') + protobuf.encoder = require('./src/encoder') + protobuf.Reader = require('./src/reader') + + // Utility + protobuf.util = require('./src/util') + protobuf.rpc = require('./src/rpc/service') + protobuf.roots = require('./src/roots') + protobuf.verifier = require('./src/verifier') + + protobuf.tokenize = require('./src/tokenize') + protobuf.parse = require('./src/parse') + protobuf.common = require('./src/common') + + protobuf.ReflectionObject = require('./src/object') + protobuf.Namespace = require('./src/namespace') + protobuf.Root = require('./src/root') + protobuf.Enum = require('./src/enum') + protobuf.Type = require('./src/type') + protobuf.Field = require('./src/field') + protobuf.OneOf = require('./src/oneof') + protobuf.MapField = require('./src/mapField') + protobuf.Service = require('./src/service') + protobuf.Method = require('./src/method') + protobuf.converter = require('./src/converter') + protobuf.decoder = require('./src/decoder') + + // Runtime + protobuf.Message = require('./src/message') + protobuf.wrappers = require('./src/wrappers') + + // Utility + protobuf.types = require('./src/types') + protobuf.util = require('./src/util') + + protobuf.configure = configure + + function load(filename, root, callback) { + if (typeof root === 'function') { + callback = root + root = new protobuf.Root() + } else if (!root) root = new protobuf.Root() + return root.load(filename, callback) + } + + protobuf.load = load + + function loadSync(filename, root) { + if (!root) root = new protobuf.Root() + return root.loadSync(filename) + } + + protobuf.loadSync = loadSync + + // 新增weichat支持的解析pbConfig接口 + function parseFromPbString(pbString, root, callback) { + if (typeof root === 'function') { + callback = root + root = new protobuf.Root() + } else if (!root) root = new protobuf.Root() + return root.parseFromPbString(pbString, callback) + } + + protobuf.parseFromPbString = parseFromPbString + + /** * Reconfigures the library according to the environment. * @returns {undefined} */ - function configure() { - - protobuf.converter._configure(); - protobuf.decoder._configure(); - protobuf.encoder._configure(); - protobuf.Field._configure(); - protobuf.MapField._configure(); - protobuf.Message._configure(); - protobuf.Namespace._configure(); - protobuf.Method._configure(); - protobuf.ReflectionObject._configure(); - protobuf.OneOf._configure(); - protobuf.parse._configure(); - protobuf.Reader._configure(); - protobuf.Root._configure(); - protobuf.Service._configure(); - protobuf.verifier._configure(); - protobuf.Type._configure(); - protobuf.types._configure(); - protobuf.wrappers._configure(); - protobuf.Writer._configure(); - } - configure(); - - if(arguments&&arguments.length){ - for (var i = 0 ;i < arguments.length; i++){ - var argument = arguments[i]; - if(argument.hasOwnProperty("exports")){ - argument.exports = protobuf; - return; - } - } + function configure() { + protobuf.converter._configure() + protobuf.decoder._configure() + protobuf.encoder._configure() + protobuf.Field._configure() + protobuf.MapField._configure() + protobuf.Message._configure() + protobuf.Namespace._configure() + protobuf.Method._configure() + protobuf.ReflectionObject._configure() + protobuf.OneOf._configure() + protobuf.parse._configure() + protobuf.Reader._configure() + protobuf.Root._configure() + protobuf.Service._configure() + protobuf.verifier._configure() + protobuf.Type._configure() + protobuf.types._configure() + protobuf.wrappers._configure() + protobuf.Writer._configure() + } + configure() + + if (arguments && arguments.length) { + for (let i = 0; i < arguments.length; i++) { + const argument = arguments[i] + if (argument.hasOwnProperty('exports')) { + argument.exports = protobuf + return + } } - return protobuf; -}); - - + } + return protobuf +})) diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/EventEmitter.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/EventEmitter.js index f766fd07..08d2e649 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/EventEmitter.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/EventEmitter.js @@ -1,5 +1,4 @@ -"use strict"; -module.exports = EventEmitter; +module.exports = EventEmitter /** * Constructs a new event emitter instance. @@ -8,13 +7,12 @@ module.exports = EventEmitter; * @constructor */ function EventEmitter() { - - /** + /** * Registered listeners. * @type {Object.} * @private */ - this._listeners = {}; + this._listeners = {} } /** @@ -25,12 +23,12 @@ function EventEmitter() { * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn : fn, - ctx : ctx || this - }); - return this; -}; + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn, + ctx: ctx || this + }) + return this +} /** * Removes an event listener or any matching listeners if arguments are omitted. @@ -39,22 +37,17 @@ EventEmitter.prototype.on = function on(evt, fn, ctx) { * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.off = function off(evt, fn) { - if (evt === undefined) - this._listeners = {}; - else { - if (fn === undefined) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length;) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } + if (evt === undefined) this._listeners = {} + else if (fn === undefined) this._listeners[evt] = [] + else { + const listeners = this._listeners[evt] + for (let i = 0; i < listeners.length;) { + if (listeners[i].fn === fn) listeners.splice(i, 1) + else ++i } - return this; -}; + } + return this +} /** * Emits an event by calling its listeners with the specified arguments. @@ -63,14 +56,12 @@ EventEmitter.prototype.off = function off(evt, fn) { * @returns {util.EventEmitter} `this` */ EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], - i = 1; - for (; i < arguments.length;) - args.push(arguments[i++]); - for (i = 0; i < listeners.length;) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; -}; + const listeners = this._listeners[evt] + if (listeners) { + const args = [] + let i = 1 + for (; i < arguments.length;) args.push(arguments[i++]) + for (i = 0; i < listeners.length;) listeners[i].fn.apply(listeners[i++].ctx, args) + } + return this +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/asPromise.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/asPromise.js index d6f642cb..dff6ff46 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/asPromise.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/asPromise.js @@ -1,5 +1,4 @@ -"use strict"; -module.exports = asPromise; +module.exports = asPromise /** * Callback as used by {@link util.asPromise}. @@ -18,35 +17,32 @@ module.exports = asPromise; * @param {...*} params Function arguments * @returns {Promise<*>} Promisified function */ -function asPromise(fn, ctx/*, varargs */) { - var params = new Array(arguments.length - 1), - offset = 0, - index = 2, - pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err/*, varargs */) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params = new Array(arguments.length - 1), - offset = 0; - while (offset < params.length) - params[offset++] = arguments[offset]; - resolve.apply(null, params); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } +function asPromise(fn, ctx/* , varargs */) { + const params = new Array(arguments.length - 1) + let offset = 0 + let index = 2 + let pending = true + while (index < arguments.length) params[offset++] = arguments[index++] + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/* , varargs */) { + if (pending) { + pending = false + if (err) reject(err) + else { + const params = new Array(arguments.length - 1) + let offset = 0 + while (offset < params.length) params[offset++] = arguments[offset] + resolve.apply(null, params) } - }); + } + } + try { + fn.apply(ctx || null, params) + } catch (err) { + if (pending) { + pending = false + reject(err) + } + } + }) } diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/base64.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/base64.js index dd2855bd..14792bc0 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/base64.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/base64.js @@ -1,11 +1,9 @@ -"use strict"; - /** * A minimal base64 implementation for number arrays. * @memberof util * @namespace */ -var base64 = module.exports; +const base64 = module.exports /** * Calculates the byte length of a base64 encoded string. @@ -13,24 +11,21 @@ var base64 = module.exports; * @returns {number} Byte length */ base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; -}; + let p = string.length + if (!p) return 0 + let n = 0 + while (--p % 4 > 1 && string.charAt(p) === '=') ++n + return Math.ceil(string.length * 3) / 4 - n +} // Base64 encoding table -var b64 = new Array(64); +const b64 = new Array(64) // Base64 decoding table -var s64 = new Array(123); +const s64 = new Array(123) // 65..90, 97..122, 48..57, 43, 47 -for (var i = 0; i < 64;) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; +for (let i = 0; i < 64;) s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++ /** * Encodes a buffer to a base64 encoded string. @@ -40,50 +35,48 @@ for (var i = 0; i < 64;) * @returns {string} Base64 encoded string */ base64.encode = function encode(buffer, start, end) { - var parts = null, - chunk = []; - var i = 0, // output index - j = 0, // goto index - t; // temporary - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i++] = b64[t | b >> 6]; - chunk[i++] = b64[b & 63]; - j = 0; - break; - } - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (j) { - chunk[i++] = b64[t]; - chunk[i++] = 61; - if (j === 1) - chunk[i++] = 61; + let parts = null + const chunk = [] + let i = 0 // output index + let j = 0 // goto index + let t // temporary + while (start < end) { + const b = buffer[start++] + switch (j) { + case 0: + chunk[i++] = b64[b >> 2] + t = (b & 3) << 4 + j = 1 + break + case 1: + chunk[i++] = b64[t | b >> 4] + t = (b & 15) << 2 + j = 2 + break + case 2: + chunk[i++] = b64[t | b >> 6] + chunk[i++] = b64[b & 63] + j = 0 + break } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)) + i = 0 } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; + } + if (j) { + chunk[i++] = b64[t] + chunk[i++] = 61 + if (j === 1) chunk[i++] = 61 + } + if (parts) { + if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))) + return parts.join('') + } + return String.fromCharCode.apply(String, chunk.slice(0, i)) +} -var invalidEncoding = "invalid encoding"; +const invalidEncoding = 'invalid encoding' /** * Decodes a base64 encoded string to a buffer. @@ -94,40 +87,37 @@ var invalidEncoding = "invalid encoding"; * @throws {Error} If encoding is invalid */ base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, // goto index - t; // temporary - for (var i = 0; i < string.length;) { - var c = string.charCodeAt(i++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === undefined) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } + const start = offset + let j = 0 // goto index + let t // temporary + for (let i = 0; i < string.length;) { + let c = string.charCodeAt(i++) + if (c === 61 && j > 1) break + if ((c = s64[c]) === undefined) throw Error(invalidEncoding) + switch (j) { + case 0: + t = c + j = 1 + break + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4 + t = c + j = 2 + break + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2 + t = c + j = 3 + break + case 3: + buffer[offset++] = (t & 3) << 6 | c + j = 0 + break } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; -}; + } + if (j === 1) throw Error(invalidEncoding) + return offset - start +} /** * Tests if the specified string appears to be base64 encoded. @@ -135,5 +125,5 @@ base64.decode = function decode(string, buffer, offset) { * @returns {boolean} `true` if probably base64 encoded, otherwise false */ base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); -}; + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string) +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/common.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/common.js index fbf4e959..f3335590 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/common.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/common.js @@ -1,6 +1,6 @@ -module.exports = common; +module.exports = common -var commonRe = /\/|\./; +const commonRe = /\/|\./ /** * Provides common type definitions. @@ -23,11 +23,11 @@ var commonRe = /\/|\./; * protobuf.common("my/foo/bar.proto", myFooBarJson); */ function common(name, json) { - if (!commonRe.test(name)) { - name = "google/protobuf/" + name + ".proto"; - json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; - } - common[name] = json; + if (!commonRe.test(name)) { + name = 'google/protobuf/' + name + '.proto' + json = {nested: {google: {nested: {protobuf: {nested: json}}}}} + } + common[name] = json } // Not provided because of limited use (feel free to discuss or to provide yourself): @@ -39,9 +39,9 @@ function common(name, json) { // Stripped and pre-parsed versions of these non-bundled files are instead available as part of // the repository or package within the google/protobuf directory. -common("any", { +common('any', { - /** + /** * Properties of a google.protobuf.Any message. * @interface IAny * @type {Object} @@ -49,25 +49,25 @@ common("any", { * @property {Uint8Array} [bytes] * @memberof common */ - Any: { - fields: { - type_url: { - type: "string", - id: 1 - }, - value: { - type: "bytes", - id: 2 - } - } + Any: { + fields: { + type_url: { + type: 'string', + id: 1 + }, + value: { + type: 'bytes', + id: 2 + } } -}); + } +}) -var timeType; +let timeType -common("duration", { +common('duration', { - /** + /** * Properties of a google.protobuf.Duration message. * @interface IDuration * @type {Object} @@ -75,23 +75,23 @@ common("duration", { * @property {number} [nanos] * @memberof common */ - Duration: timeType = { - fields: { - seconds: { - type: "int64", - id: 1 - }, - nanos: { - type: "int32", - id: 2 - } - } + Duration: timeType = { + fields: { + seconds: { + type: 'int64', + id: 1 + }, + nanos: { + type: 'int32', + id: 2 + } } -}); + } +}) -common("timestamp", { +common('timestamp', { - /** + /** * Properties of a google.protobuf.Timestamp message. * @interface ITimestamp * @type {Object} @@ -99,41 +99,41 @@ common("timestamp", { * @property {number} [nanos] * @memberof common */ - Timestamp: timeType -}); + Timestamp: timeType +}) -common("empty", { +common('empty', { - /** + /** * Properties of a google.protobuf.Empty message. * @interface IEmpty * @memberof common */ - Empty: { - fields: {} - } -}); + Empty: { + fields: {} + } +}) -common("struct", { +common('struct', { - /** + /** * Properties of a google.protobuf.Struct message. * @interface IStruct * @type {Object} * @property {Object.} [fields] * @memberof common */ - Struct: { - fields: { - fields: { - keyType: "string", - type: "Value", - id: 1 - } - } - }, + Struct: { + fields: { + fields: { + keyType: 'string', + type: 'Value', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.Value message. * @interface IValue * @type {Object} @@ -146,237 +146,237 @@ common("struct", { * @property {IListValue} [listValue] * @memberof common */ - Value: { - oneofs: { - kind: { - oneof: [ - "nullValue", - "numberValue", - "stringValue", - "boolValue", - "structValue", - "listValue" - ] - } - }, - fields: { - nullValue: { - type: "NullValue", - id: 1 - }, - numberValue: { - type: "double", - id: 2 - }, - stringValue: { - type: "string", - id: 3 - }, - boolValue: { - type: "bool", - id: 4 - }, - structValue: { - type: "Struct", - id: 5 - }, - listValue: { - type: "ListValue", - id: 6 - } - } + Value: { + oneofs: { + kind: { + oneof: [ + 'nullValue', + 'numberValue', + 'stringValue', + 'boolValue', + 'structValue', + 'listValue' + ] + } }, + fields: { + nullValue: { + type: 'NullValue', + id: 1 + }, + numberValue: { + type: 'double', + id: 2 + }, + stringValue: { + type: 'string', + id: 3 + }, + boolValue: { + type: 'bool', + id: 4 + }, + structValue: { + type: 'Struct', + id: 5 + }, + listValue: { + type: 'ListValue', + id: 6 + } + } + }, - NullValue: { - values: { - NULL_VALUE: 0 - } - }, + NullValue: { + values: { + NULL_VALUE: 0 + } + }, - /** + /** * Properties of a google.protobuf.ListValue message. * @interface IListValue * @type {Object} * @property {Array.} [values] * @memberof common */ - ListValue: { - fields: { - values: { - rule: "repeated", - type: "Value", - id: 1 - } - } + ListValue: { + fields: { + values: { + rule: 'repeated', + type: 'Value', + id: 1 + } } -}); + } +}) -common("wrappers", { +common('wrappers', { - /** + /** * Properties of a google.protobuf.DoubleValue message. * @interface IDoubleValue * @type {Object} * @property {number} [value] * @memberof common */ - DoubleValue: { - fields: { - value: { - type: "double", - id: 1 - } - } - }, + DoubleValue: { + fields: { + value: { + type: 'double', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.FloatValue message. * @interface IFloatValue * @type {Object} * @property {number} [value] * @memberof common */ - FloatValue: { - fields: { - value: { - type: "float", - id: 1 - } - } - }, + FloatValue: { + fields: { + value: { + type: 'float', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.Int64Value message. * @interface IInt64Value * @type {Object} * @property {number|Long} [value] * @memberof common */ - Int64Value: { - fields: { - value: { - type: "int64", - id: 1 - } - } - }, + Int64Value: { + fields: { + value: { + type: 'int64', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.UInt64Value message. * @interface IUInt64Value * @type {Object} * @property {number|Long} [value] * @memberof common */ - UInt64Value: { - fields: { - value: { - type: "uint64", - id: 1 - } - } - }, + UInt64Value: { + fields: { + value: { + type: 'uint64', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.Int32Value message. * @interface IInt32Value * @type {Object} * @property {number} [value] * @memberof common */ - Int32Value: { - fields: { - value: { - type: "int32", - id: 1 - } - } - }, + Int32Value: { + fields: { + value: { + type: 'int32', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.UInt32Value message. * @interface IUInt32Value * @type {Object} * @property {number} [value] * @memberof common */ - UInt32Value: { - fields: { - value: { - type: "uint32", - id: 1 - } - } - }, + UInt32Value: { + fields: { + value: { + type: 'uint32', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.BoolValue message. * @interface IBoolValue * @type {Object} * @property {boolean} [value] * @memberof common */ - BoolValue: { - fields: { - value: { - type: "bool", - id: 1 - } - } - }, + BoolValue: { + fields: { + value: { + type: 'bool', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.StringValue message. * @interface IStringValue * @type {Object} * @property {string} [value] * @memberof common */ - StringValue: { - fields: { - value: { - type: "string", - id: 1 - } - } - }, + StringValue: { + fields: { + value: { + type: 'string', + id: 1 + } + } + }, - /** + /** * Properties of a google.protobuf.BytesValue message. * @interface IBytesValue * @type {Object} * @property {Uint8Array} [value] * @memberof common */ - BytesValue: { - fields: { - value: { - type: "bytes", - id: 1 - } - } + BytesValue: { + fields: { + value: { + type: 'bytes', + id: 1 + } } -}); + } +}) -common("field_mask", { +common('field_mask', { - /** + /** * Properties of a google.protobuf.FieldMask message. * @interface IDoubleValue * @type {Object} * @property {number} [value] * @memberof common */ - FieldMask: { - fields: { - paths: { - rule: "repeated", - type: "string", - id: 1 - } - } + FieldMask: { + fields: { + paths: { + rule: 'repeated', + type: 'string', + id: 1 + } } -}); + } +}) /** * Gets the root definition of the specified common proto file. @@ -394,5 +394,5 @@ common("field_mask", { * @returns {INamespace|null} Root definition or `null` if not defined */ common.get = function get(file) { - return common[file] || null; -}; + return common[file] || null +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/converter.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/converter.js index 67e1f601..e6474ce8 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/converter.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/converter.js @@ -2,329 +2,322 @@ * Created by zhangmiao on 2018/3/14. * 写这个,有点难;有错误请指出 ,微信中不能Function.Apply 和evl,所以去掉其中所有的gen() */ -var converter = module.exports; - -var Enum, - util; +const converter = module.exports +let Enum +let util converter._configure = function () { - Enum = require('./enum'); - util = require('./util'); -}; + Enum = require('./enum') + util = require('./util') +} -function valuePartial_fromObject(field, fieldIndex, propName, options){ - var m = options['m']; - var d = options['d']; - var _types = options['types']; - var ksi = options['ksi']; - var ksiFlag = typeof ksi != 'undefined'; - if(field.resolvedType){ - if(field.resolvedType instanceof Enum){ - var prop = ksiFlag ? d[propName][ksi] : d[propName]; - var values = field.resolvedType.values, - keys = Object.keys(values); - for (var i = 0; i < keys.length; i++){ - if(field.repeated && values[keys[i]] === field.typeDefault){ - continue; - } - if(keys[i] == prop || values[keys[i]] == prop){ - ksiFlag ? - m[propName][ksi] = values[keys[i]] : - m[propName] = values[keys[i]]; - break - } - } - }else { - if(typeof (ksiFlag ? d[propName][ksi] : d[propName]) !== 'object') - throw TypeError(field.fullName + ": object expected"); - ksiFlag ? - m[propName][ksi] = _types[fieldIndex].fromObject(d[propName][ksi]): - m[propName] = _types[fieldIndex].fromObject(d[propName]); +function valuePartial_fromObject(field, fieldIndex, propName, options) { + const m = options.m + const d = options.d + const _types = options.types + const ksi = options.ksi + const ksiFlag = typeof ksi !== 'undefined' + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + const prop = ksiFlag ? d[propName][ksi] : d[propName] + const values = field.resolvedType.values + const keys = Object.keys(values) + for (let i = 0; i < keys.length; i++) { + if (field.repeated && values[keys[i]] === field.typeDefault) { + continue } + if (keys[i] == prop || values[keys[i]] == prop) { + ksiFlag + ? m[propName][ksi] = values[keys[i]] + : m[propName] = values[keys[i]] + break + } + } } else { - var isUnsigned = false; - switch (field.type){ - case "double": - case "float": - ksiFlag ? - m[propName][ksi] = Number(d[propName][ksi]) : - m[propName] = Number(d[propName]); - break; - case "uint32": - case "fixed32": - ksiFlag ? - m[propName][ksi] = d[propName][ksi] >>> 0: - m[propName] = d[propName] >>> 0; - break; - case "int32": - case "sint32": - case "sfixed32": - ksiFlag ? - m[propName][ksi] = d[propName][ksi] | 0 : - m[propName] = d[propName] |0; - break; - case "uint64": - isUnsigned = true; - // eslint-disable-line no-fallthrough - case "int64": - case "sint64": - case "fixed64": - case "sfixed64": - if(util.Long) - ksiFlag ? - m[propName][ksi] = util.Long.fromValue(d[propName][ksi]).unsigned = isUnsigned : - m[propName] = util.Long.fromValue(d[propName]).unsigned = isUnsigned; - else if(typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'string') - ksiFlag ? - m[propName][ksi] =parseInt(d[propName][ksi], 10) : - m[propName] =parseInt(d[propName], 10); - else if(typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'number') - ksiFlag ? - m[propName][ksi] = d[propName][ksi] : - m[propName] = d[propName]; - else if(typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'object') - ksiFlag ? - m[propName][ksi] = new util.LongBits(d[propName][ksi].low >>> 0, d[propName][ksi].high >>> 0).toNumber(isUnsigned) : - m[propName] = new util.LongBits(d[propName].low >>> 0, d[propName].high >>> 0).toNumber(isUnsigned); - break; - case "bytes": - if(typeof (ksiFlag ? d[propName][ksi] : d[propName]) ==="string") - ksiFlag ? - util.base64.decode(d[propName][ksi],m[propName][ksi]=util.newBuffer(util.base64.length(d[propName][ksi])),0) : - util.base64.decode(d[propName],m[propName]=util.newBuffer(util.base64.length(d[propName])),0); - else if((ksiFlag ? d[propName][ksi] : d[propName]).length) - ksiFlag? - m[propName][ksi]=d[propName][ksi] : - m[propName]=d[propName]; - break; - case "string": - ksiFlag? - m[propName][ksi]=String(d[propName][ksi]) : - m[propName]=String(d[propName]); - break; - case "bool": - ksiFlag? - m[propName][ksi]=Boolean(d[propName][ksi]): - m[propName]=Boolean(d[propName]); - break; + if (typeof (ksiFlag ? d[propName][ksi] : d[propName]) !== 'object') throw TypeError(field.fullName + ': object expected') + ksiFlag + ? m[propName][ksi] = _types[fieldIndex].fromObject(d[propName][ksi]) + : m[propName] = _types[fieldIndex].fromObject(d[propName]) + } + } else { + let isUnsigned = false + switch (field.type) { + case 'double': + case 'float': + ksiFlag + ? m[propName][ksi] = Number(d[propName][ksi]) + : m[propName] = Number(d[propName]) + break + case 'uint32': + case 'fixed32': + ksiFlag + ? m[propName][ksi] = d[propName][ksi] >>> 0 + : m[propName] = d[propName] >>> 0 + break + case 'int32': + case 'sint32': + case 'sfixed32': + ksiFlag + ? m[propName][ksi] = d[propName][ksi] | 0 + : m[propName] = d[propName] | 0 + break + case 'uint64': + isUnsigned = true + // eslint-disable-line no-fallthrough + case 'int64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (util.Long) { + ksiFlag + ? m[propName][ksi] = util.Long.fromValue(d[propName][ksi]).unsigned = isUnsigned + : m[propName] = util.Long.fromValue(d[propName]).unsigned = isUnsigned + } else if (typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'string') { + ksiFlag + ? m[propName][ksi] = parseInt(d[propName][ksi], 10) + : m[propName] = parseInt(d[propName], 10) + } else if (typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'number') { + ksiFlag + ? m[propName][ksi] = d[propName][ksi] + : m[propName] = d[propName] + } else if (typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'object') { + ksiFlag + ? m[propName][ksi] = new util.LongBits(d[propName][ksi].low >>> 0, d[propName][ksi].high >>> 0).toNumber(isUnsigned) + : m[propName] = new util.LongBits(d[propName].low >>> 0, d[propName].high >>> 0).toNumber(isUnsigned) + } + break + case 'bytes': + if (typeof (ksiFlag ? d[propName][ksi] : d[propName]) === 'string') { + ksiFlag + ? util.base64.decode(d[propName][ksi], m[propName][ksi] = util.newBuffer(util.base64.length(d[propName][ksi])), 0) + : util.base64.decode(d[propName], m[propName] = util.newBuffer(util.base64.length(d[propName])), 0) + } else if ((ksiFlag ? d[propName][ksi] : d[propName]).length) { + ksiFlag + ? m[propName][ksi] = d[propName][ksi] + : m[propName] = d[propName] } + break + case 'string': + ksiFlag + ? m[propName][ksi] = String(d[propName][ksi]) + : m[propName] = String(d[propName]) + break + case 'bool': + ksiFlag + ? m[propName][ksi] = Boolean(d[propName][ksi]) + : m[propName] = Boolean(d[propName]) + break } + } } /* * @param {Type} mtype Message type * @returns {Function} Function instance */ -converter.fromObject = function fromObject(mtype){ - var fields = mtype.fieldsArray; - return function (options){ - return function (d){ - if(d instanceof this.ctor) - return d; - if(!fields.length) - return new this.ctor; +converter.fromObject = function fromObject(mtype) { + const fields = mtype.fieldsArray + return function (options) { + return function (d) { + if (d instanceof this.ctor) return d + if (!fields.length) return new this.ctor() - var m = new this.ctor; - for (var i = 0; i < fields.length; ++i){ - var field = fields[i].resolve(); - var propName = field.name; - var _i; - if(field.map){ - if(d[propName]){ - if(typeof d[propName] !== 'object') - throw TypeError(field.fullName + ": object expected"); - m[propName] = {}; - } - var ks = Object.keys(d[propName]); - for ( _i = 0; _i>> 0, m[propName][ksi].high >>> 0).toNumber(isUnsigned) : m[propName][ksi]): - (d[propName] = - o.longs === String ? - util.Long.prototype.toString.call(m[propName]) : - o.longs === Number ? new util.LongBits(m[propName].low >>> 0, m[propName].high >>> 0).toNumber(isUnsigned) : m[propName]); - break; - case "bytes": - ksiFlag? - (d[propName][ksi] = - o.bytes === String ? - util.base64.encode(m[propName][ksi], 0, m[propName][ksi].length) : - o.bytes === Array ? Array.prototype.slice.call(m[propName][ksi]) : m[propName][ksi]): - (d[propName] = - o.bytes === String ? - util.base64.encode(m[propName], 0, m[propName].length) : - o.bytes === Array ? Array.prototype.slice.call(m[propName]) : m[propName]); - break; - default: - ksiFlag ? d[propName][ksi] = m[propName][ksi] : d[propName] = m[propName]; - break; +function valuePartial_toObject(field, fieldIndex, propName, options) { + const m = options.m + const d = options.d + const _types = options.types + const ksi = options.ksi + const o = options.o + const ksiFlag = typeof ksi !== 'undefined' + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + ksiFlag + ? (d[propName][ksi] = o.enums === String ? _types[fieldIndex].values[m[propName][ksi]] : m[propName][ksi]) + : (d[propName] = o.enums === String ? _types[fieldIndex].values[m[propName]] : m[propName]) + } else { + ksiFlag + ? d[propName][ksi] = _types[fieldIndex].toObject(m[propName][ksi], o) + : d[propName] = _types[fieldIndex].toObject(m[propName], o) + } + } else { + let isUnsigned = false + switch (field.type) { + case 'double': + case 'float': + ksiFlag ? (d[propName][ksi] = o.json && !isFinite(m[propName][ksi]) ? String(m[propName][ksi]) : m[propName][ksi]) + : (d[propName] = o.json && !isFinite(m[propName]) ? String(m[propName]) : m[propName]) + break + case 'uint64': + isUnsigned = true + // eslint-disable-line no-fallthrough + case 'int64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (typeof m[propName][ksi] === 'number') { + ksiFlag + ? (d[propName][ksi] = o.longs === String ? String(m[propName][ksi]) : m[propName][ksi]) + : (d[propName] = o.longs === String ? String(m[propName]) : m[propName]) + } else { + ksiFlag + ? (d[propName][ksi] = + o.longs === String + ? util.Long.prototype.toString.call(m[propName][ksi]) + : o.longs === Number ? new util.LongBits(m[propName][ksi].low >>> 0, m[propName][ksi].high >>> 0).toNumber(isUnsigned) : m[propName][ksi]) + : (d[propName] = + o.longs === String + ? util.Long.prototype.toString.call(m[propName]) + : o.longs === Number ? new util.LongBits(m[propName].low >>> 0, m[propName].high >>> 0).toNumber(isUnsigned) : m[propName]) } + break + case 'bytes': + ksiFlag + ? (d[propName][ksi] = + o.bytes === String + ? util.base64.encode(m[propName][ksi], 0, m[propName][ksi].length) + : o.bytes === Array ? Array.prototype.slice.call(m[propName][ksi]) : m[propName][ksi]) + : (d[propName] = + o.bytes === String + ? util.base64.encode(m[propName], 0, m[propName].length) + : o.bytes === Array ? Array.prototype.slice.call(m[propName]) : m[propName]) + break + default: + ksiFlag ? d[propName][ksi] = m[propName][ksi] : d[propName] = m[propName] + break } + } } +converter.toObject = function toObject(mtype) { + const fields = mtype.fieldsArray.slice().sort(util.compareFieldsById) + return function (options) { + if (!fields.length) { + return function () { + return {} + } + } + return function (m, o) { + o = o || {} + const d = {} + const repeatedFields = [] + const mapFields = [] + const normalFields = [] + let field + let propName + let i = 0 + for (; i < fields.length; ++i) { + if (!fields[i].partOf) { + (fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]) + } + } -converter.toObject = function toObject(mtype){ - var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); - return function (options){ - if(!fields.length) - return function (){ - return {}; - }; - return function (m, o){ - o = o || {}; - var d = {}; - var repeatedFields = [], - mapFields = [], - normalFields = [], - field, - propName, - i = 0; - for (; i < fields.length; ++i) - if (!fields[i].partOf) - ( fields[i].resolve().repeated ? repeatedFields - : fields[i].map ? mapFields - : normalFields).push(fields[i]); + if (repeatedFields.length) { + if (o.arrays || o.defaults) { + for (i = 0; i < repeatedFields.length; ++i) d[repeatedFields[i].name] = [] + } + } - if (repeatedFields.length) { - if(o.arrays || o.defaults ){ - for (i = 0; i < repeatedFields.length; ++i) - d[repeatedFields[i].name] = []; - } - } + if (mapFields.length) { + if (o.objects || o.defaults) { + for (i = 0; i < mapFields.length; ++i) d[mapFields[i].name] = {} + } + } - if (mapFields.length) { - if(o.objects || o.defaults){ - for (i = 0; i < mapFields.length; ++i) - d[mapFields[i].name] = {}; - } + if (normalFields.length) { + if (o.defaults) { + for (i = 0; i < normalFields.length; ++i) { + field = normalFields[i], + propName = field.name + if (field.resolvedType instanceof Enum) d[propName] = o.enums = String ? field.resolvedType.valuesById[field.typeDefault] : field.typeDefault + else if (field.long) { + if (util.Long) { + const n = new util.Long(field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + d[propName] = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber() : n + } else { + d[propName] = o.longs === String ? field.typeDefault.toString() : field.typeDefault.toNumber() + } + } else if (field.bytes) { + d[propName] = o.bytes === String ? String.fromCharCode.apply(String, field.typeDefault) : Array.prototype.slice.call(field.typeDefault).join('*..*').split('*..*') + } else { + d[propName] = field.typeDefault } - - if(normalFields.length){ - if(o.defaults){ - for (i = 0; i < normalFields.length; ++i){ - field = normalFields[i], - propName = field.name; - if(field.resolvedType instanceof Enum) - d[propName] = o.enums = String ? field.resolvedType.valuesById[field.typeDefault] : field.typeDefault; - else if(field.long){ - if(util.Long){ - var n = new util.Long(field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned); - d[propName] = o.longs === String ? n.toString() : o.longs === Number ? n.toNumber():n; - }else { - d[propName] = o.longs === String ? field.typeDefault.toString() : field.typeDefault.toNumber(); - } - }else if(field.bytes){ - d[propName] = o.bytes === String ? String.fromCharCode.apply(String, field.typeDefault) : Array.prototype.slice.call(field.typeDefault).join('*..*').split("*..*"); - }else { - d[propName] =field.typeDefault; - } - - } - } + } + } + } + let hasKs2 = false + for (i = 0; i < fields.length; ++i) { + field = fields[i] + propName = field.name + const index = mtype._fieldsArray.indexOf(field) + var ks2 + var j + if (field.map) { + if (!hasKs2) { + hasKs2 = true + } + if (m[propName] && (ks2 = Object.keys(m[propName]).length)) { + d[propName] = {} + for (j = 0; j < ks2.length; ++j) { + valuePartial_toObject(field, index, propName, util.merge(util.copy(options), { + m, d, ksi: ks2[j], o + })) } - var hasKs2 = false; - for (i = 0; i < fields.length; ++i){ - field = fields[i]; - propName = field.name; - var index = mtype._fieldsArray.indexOf(field); - var ks2; - var j; - if(field.map){ - if (!hasKs2){ - hasKs2 = true; - } - if (m[propName]&&(ks2 = Object.keys(m[propName]).length)){ - d[propName] = {}; - for (j = 0; j < ks2.length; ++j){ - valuePartial_toObject(field, index, propName, util.merge(util.copy(options), {m:m,d:d,ksi :ks2[j],o:o})); - } - } - }else if(field.repeated){ - if(m[propName]&&m[propName].length){ - d[propName] = []; - for (j = 0; j < m[propName].length; ++j){ - valuePartial_toObject(field, index, propName, util.merge(util.copy(options), {m:m,d:d,ksi:j,o:o})) - } - } - }else { - if(m[propName]!=null&& (m.hasOwnProperty(propName)/*|| field.partOf*/)){ - valuePartial_toObject(field, index, propName, util.merge(util.copy(options), {m:m,d:d,o:o})) - } - if(field.partOf) { - if (o.oneofs) - d[field.partOf.name] = propName; - } - } + } + } else if (field.repeated) { + if (m[propName] && m[propName].length) { + d[propName] = [] + for (j = 0; j < m[propName].length; ++j) { + valuePartial_toObject(field, index, propName, util.merge(util.copy(options), { + m, d, ksi: j, o + })) } - return d; + } + } else { + if (m[propName] != null && (m.hasOwnProperty(propName)/* || field.partOf */)) { + valuePartial_toObject(field, index, propName, util.merge(util.copy(options), {m, d, o})) + } + if (field.partOf) { + if (o.oneofs) d[field.partOf.name] = propName + } } + } + return d } - - -}; \ No newline at end of file + } +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/decoder.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/decoder.js index 7443b409..c26cedae 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/decoder.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/decoder.js @@ -2,117 +2,106 @@ * Created by zhangmiao on 2018/3/13. */ -var Enum, - types, - util; - +let Enum +let types +let util function missing(field) { - return "missing required '" + field.name + "'"; + return "missing required '" + field.name + "'" } -function decoder(mtype){ - return function (options){ - var Reader = options.Reader; - var _types = options.types; - var _util = options.util; - return function (r, l){ - if(!(r instanceof Reader)) - r = Reader.create(r); - var c = l === undefined ? r.len : r.pos + l, - m = new this.ctor; - var k; - while (r.pos < c){ - var t = r.uint32(); - if (mtype.group){ - if((t&7) === 4) - break; - } - var fieldId = t>>>3; - var i = 0; - var find = false; - for (; i < mtype.fieldsArray.length; ++i){ - var field = mtype._fieldsArray[i].resolve(), - name = field.name, - type = field.resolvedType instanceof Enum ? "int32" : field.type; - //ref = m[field.name]; - if (fieldId != field.id) continue; - find = true; - if (field.map){ - r.skip().pos++; - if(m[name] === _util.emptyObject) - m[name] = {}; - k = r[field.keyType](); - r.pos++; - if(types.long[field.keyType] != undefined){ - if(types.basic[type] == undefined){ - m[name][typeof k ==='object' ? _util.longToHash(k):k] = _types[i].decode(r, r.uint32()); - }else { - m[name][typeof k ==='object' ? _util.longToHash(k):k] = r[type](); - } - }else { - if(types.basic[type] == undefined){ - m[name] = _types[i].decode(r, r.uint32()); - }else { - m[name] = r[type](); - } - } - }else if(field.repeated){ - if(!(m[name] && m[name].length)){ - m[name] = []; - } - - if(types.packed[type] != undefined && (t&7) === 2){ - var c2 = r.uint32()+ r.pos; - while (r.pos < c2) - m[name].push(r[type]()) - }else { - if(types.basic[type] == undefined){ - field.resolvedType.group ? - m[name].push(_types[i].decode(r)) : - m[name].push(_types[i].decode(r, r.uint32())) - - }else { - m[name].push(r[type]()); - } - } - }else if (types.basic[type] == undefined){ - if(field.resolvedType.group){ - m[name] = _types[i].decode(r); - }else { - m[name] = _types[i].decode(r, r.uint32()); - } - }else { - //console.log("m",JSON.stringify(m),"type",type,"field",field); - m[name] = r[type](); - } - break; - } - - if(!find){ - console.log("t",t); - r.skipType(t&7) - } - +function decoder(mtype) { + return function (options) { + const Reader = options.Reader + const _types = options.types + const _util = options.util + return function (r, l) { + if (!(r instanceof Reader)) r = Reader.create(r) + const c = l === undefined ? r.len : r.pos + l + const m = new this.ctor() + let k + while (r.pos < c) { + const t = r.uint32() + if (mtype.group) { + if ((t & 7) === 4) break + } + const fieldId = t >>> 3 + var i = 0 + let find = false + for (; i < mtype.fieldsArray.length; ++i) { + const field = mtype._fieldsArray[i].resolve() + const name = field.name + const type = field.resolvedType instanceof Enum ? 'int32' : field.type + // ref = m[field.name]; + if (fieldId != field.id) continue + find = true + if (field.map) { + r.skip().pos++ + if (m[name] === _util.emptyObject) m[name] = {} + k = r[field.keyType]() + r.pos++ + if (types.long[field.keyType] != undefined) { + if (types.basic[type] == undefined) { + m[name][typeof k === 'object' ? _util.longToHash(k) : k] = _types[i].decode(r, r.uint32()) + } else { + m[name][typeof k === 'object' ? _util.longToHash(k) : k] = r[type]() + } + } else if (types.basic[type] == undefined) { + m[name] = _types[i].decode(r, r.uint32()) + } else { + m[name] = r[type]() + } + } else if (field.repeated) { + if (!(m[name] && m[name].length)) { + m[name] = [] } - for (i = 0; i < mtype._fieldsArray.length; ++ i){ - var rfield = mtype._fieldsArray[i]; - if(rfield.required){ - if(!m.hasOwnProperty(rfield.name)){ - throw util.ProtocolError(missing(rfield),{instance:m}) - } - } + if (types.packed[type] != undefined && (t & 7) === 2) { + const c2 = r.uint32() + r.pos + while (r.pos < c2) m[name].push(r[type]()) + } else if (types.basic[type] == undefined) { + field.resolvedType.group + ? m[name].push(_types[i].decode(r)) + : m[name].push(_types[i].decode(r, r.uint32())) + } else { + m[name].push(r[type]()) } - //mtype.fieldsArray.filter(function(field) { return field.map; }).length - return m; + } else if (types.basic[type] == undefined) { + if (field.resolvedType.group) { + m[name] = _types[i].decode(r) + } else { + m[name] = _types[i].decode(r, r.uint32()) + } + } else { + // console.log("m",JSON.stringify(m),"type",type,"field",field); + m[name] = r[type]() + } + break + } + + if (!find) { + console.log('t', t) + r.skipType(t & 7) } + } + + for (i = 0; i < mtype._fieldsArray.length; ++i) { + const rfield = mtype._fieldsArray[i] + if (rfield.required) { + if (!m.hasOwnProperty(rfield.name)) { + throw util.ProtocolError(missing(rfield), {instance: m}) + } + } + } + // mtype.fieldsArray.filter(function(field) { return field.map; }).length + return m } + } } -module.exports = decoder; -decoder._configure = function (){ - Enum = require("./enum"); - types = require("./types"); - util = require("./util"); -}; \ No newline at end of file +module.exports = decoder +decoder._configure = function () { + Enum = require('./enum') + types = require('./types') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/encoder.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/encoder.js index c238a45d..0c5c4a89 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/encoder.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/encoder.js @@ -2,90 +2,87 @@ * Created by zhangmiao on 2018/3/13. * 改写原来的googleProtocolBuffer的encode,请不要告我侵犯版权;/(ㄒoㄒ)/~~ */ -var Enum; -var types; +let Enum +let types +// 得到一个编码过程 +function encoder(mtype) { + return function (options) { + const Writer = options.Writer + const _types = options.types + const util = options.util + return function (message, writer) { + writer = writer || Writer.create() + const fields = mtype.fieldsArray.slice().sort(util.compareFieldsById) + for (let i = 0; i < fields.length; i++) { + const field = fields[i] + const index = mtype._fieldsArray.indexOf(field) -//得到一个编码过程 -function encoder(mtype){ - return function (options){ - var Writer = options.Writer; - var _types = options.types; - var util = options.util; - return function (message, writer) { - writer = writer || Writer.create(); - var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); - for (var i = 0; i < fields.length; i++) { - var field = fields[i]; - var index = mtype._fieldsArray.indexOf(field); - - var type = field.resolvedType instanceof Enum ? 'uint32' : field.type; - var wireType = types.basic[type]; - var ref = message[field.name]; - //此处增加枚举型替换,有可能外界传入的枚举是string,转换成number - if(field.resolvedType instanceof Enum && typeof ref === 'string'){ - ref = _types[index]['values'][ref]; - } + const type = field.resolvedType instanceof Enum ? 'uint32' : field.type + const wireType = types.basic[type] + let ref = message[field.name] + // 此处增加枚举型替换,有可能外界传入的枚举是string,转换成number + if (field.resolvedType instanceof Enum && typeof ref === 'string') { + ref = _types[index].values[ref] + } - //正式进行序列化 - if (field.map) {//有待验证 - if(ref != null && message.hasOwnProperty(field.name)){ - for (var ks =Object.keys(ref), l = 0; l < ks.length; ++l){ - writer.uint32((field.id << 3 | 2) >>> 0).fork().uint32(8 | types.mapKey[field.keyType])[field.keyType](ks[l]); - if(wireType === undefined ){ - _types[index].encode(ref[ks[l]], writer.uint32(18).fork()).ldelim().ldelim(); - }else { - writer.uint32(16 | wireType)[type](ref[ks[l]]).ldelim(); - } - } - } - } else if (field.repeated) { - if (ref && ref.length) { - if (field.packed && types.packed[type] !== undefined) {//如果数据可以被packed的话 - writer.uint32((field.id << 3 | 2) >>> 0).fork(); - for (var j = 0; j < ref.length; j++) { - writer[type](ref[j]) - } - writer.ldelim(); - } else {//数据不能packed的话 - for (var k = 0; k < ref.length; k++) { - if (wireType === undefined) {//如果是一个自定义的数据类型 - if(field.resolvedType.group){ - _types[index].encode(ref[k],writer.uint32((field.id << 3 | 3) >>> 0)).uint32((field.id << 3 | 4) >>> 0); - }else { - _types[index].encode(ref[k],writer.uint32((field.id << 3 | 2) >>> 0).fork()).ldelim(); - } - } else {//如果是string 或者 bytes - writer.uint32((field.id << 3 | wireType) >>> 0)[type](ref[k]); - } - } - } - } - } else { - if(!field.optional || (ref != null && (message.hasOwnProperty(field.name) /*|| field.partOf*/))){ - if(!field.optional && (ref == null || !message.hasOwnProperty(field.name))){ - console.warn('注意啦!!!很大概率会报错 类型:',message.$type ? message.$type.name : "不晓得",'没有设置对应的属性:',field.name,'检查是不是proto文件属性设置为了required'); - } - if(wireType === undefined){ - if(field.resolvedType.group){ - _types[index].encode(ref,writer.uint32((field.id << 3 | 3) >>> 0)).uint32((field.id << 3 | 4) >>> 0); - }else { - _types[index].encode(ref,writer.uint32((field.id << 3 | 2) >>> 0).fork()).ldelim(); - } - }else { - writer.uint32((field.id << 3 | wireType) >>> 0)[type](ref); - } - } + // 正式进行序列化 + if (field.map) { // 有待验证 + if (ref != null && message.hasOwnProperty(field.name)) { + for (let ks = Object.keys(ref), l = 0; l < ks.length; ++l) { + writer.uint32((field.id << 3 | 2) >>> 0).fork().uint32(8 | types.mapKey[field.keyType])[field.keyType](ks[l]) + if (wireType === undefined) { + _types[index].encode(ref[ks[l]], writer.uint32(18).fork()).ldelim().ldelim() + } else { + writer.uint32(16 | wireType)[type](ref[ks[l]]).ldelim() + } + } + } + } else if (field.repeated) { + if (ref && ref.length) { + if (field.packed && types.packed[type] !== undefined) { // 如果数据可以被packed的话 + writer.uint32((field.id << 3 | 2) >>> 0).fork() + for (let j = 0; j < ref.length; j++) { + writer[type](ref[j]) + } + writer.ldelim() + } else { // 数据不能packed的话 + for (let k = 0; k < ref.length; k++) { + if (wireType === undefined) { // 如果是一个自定义的数据类型 + if (field.resolvedType.group) { + _types[index].encode(ref[k], writer.uint32((field.id << 3 | 3) >>> 0)).uint32((field.id << 3 | 4) >>> 0) + } else { + _types[index].encode(ref[k], writer.uint32((field.id << 3 | 2) >>> 0).fork()).ldelim() + } + } else { // 如果是string 或者 bytes + writer.uint32((field.id << 3 | wireType) >>> 0)[type](ref[k]) } + } + } + } + } else if (!field.optional || (ref != null && (message.hasOwnProperty(field.name) /* || field.partOf */))) { + if (!field.optional && (ref == null || !message.hasOwnProperty(field.name))) { + console.warn('注意啦!!!很大概率会报错 类型:', message.$type ? message.$type.name : '不晓得', '没有设置对应的属性:', field.name, '检查是不是proto文件属性设置为了required') + } + if (wireType === undefined) { + if (field.resolvedType.group) { + _types[index].encode(ref, writer.uint32((field.id << 3 | 3) >>> 0)).uint32((field.id << 3 | 4) >>> 0) + } else { + _types[index].encode(ref, writer.uint32((field.id << 3 | 2) >>> 0).fork()).ldelim() } - return writer; + } else { + writer.uint32((field.id << 3 | wireType) >>> 0)[type](ref) + } } - }; + } + return writer + } + } } -module.exports = encoder; +module.exports = encoder -encoder._configure = function (){ - Enum = require("./enum"); - types = require("./types"); -}; \ No newline at end of file +encoder._configure = function () { + Enum = require('./enum') + types = require('./types') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/enum.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/enum.js index f9c4ceb8..52caddb0 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/enum.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/enum.js @@ -2,57 +2,58 @@ * Created by zhangmiao on 2018/3/12. */ -module.exports = Enum; +module.exports = Enum -var ReflectionObject = require("./object"); +const ReflectionObject = require('./object'); -((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; -var Namespace = require("./namespace"); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = 'Enum' +const Namespace = require('./namespace') function Enum(name, values, options, comment, comments) { - ReflectionObject.call(this, name, options); + ReflectionObject.call(this, name, options) - if (values && typeof values !== "object") - throw TypeError("values must be an object"); + if (values && typeof values !== 'object') throw TypeError('values must be an object') - /** + /** * Enum values by id. * @type {Object.} */ - this.valuesById = {}; + this.valuesById = {} - /** + /** * Enum values by name. * @type {Object.} */ - this.values = Object.create(this.valuesById); // toJSON, marker + this.values = Object.create(this.valuesById) // toJSON, marker - /** + /** * Enum comment text. * @type {string|null} */ - this.comment = comment; + this.comment = comment - /** + /** * Value comment texts, if any. * @type {Object.} */ - this.comments = comments || {}; + this.comments = comments || {} - /** + /** * Reserved ranges, if any. * @type {Array.} */ - this.reserved = undefined; // toJSON - - // Note that values inherit valuesById on their prototype which makes them a TypeScript- - // compatible enum. This is used by pbts to write actual enum definitions that work for - // static and reflection code alike instead of emitting generic object definitions. - - if (values) - for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) - if (typeof values[keys[i]] === "number") // use forward entries only - this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; + this.reserved = undefined // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) { + for (let keys = Object.keys(values), i = 0; i < keys.length; ++i) { + if (typeof values[keys[i]] === 'number') // use forward entries only + { this.valuesById[this.values[keys[i]] = values[keys[i]]] = keys[i] } + } + } } /** @@ -70,10 +71,10 @@ function Enum(name, values, options, comment, comments) { * @throws {TypeError} If arguments are invalid */ Enum.fromJSON = function fromJSON(name, json) { - var enm = new Enum(name, json.values, json.options, json.comment, json.comments); - enm.reserved = json.reserved; - return enm; -}; + const enm = new Enum(name, json.values, json.options, json.comment, json.comments) + enm.reserved = json.reserved + return enm +} /** * Converts this enum to an enum descriptor. @@ -81,15 +82,15 @@ Enum.fromJSON = function fromJSON(name, json) { * @returns {IEnum} Enum descriptor */ Enum.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options" , this.options, - "values" , this.values, - "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, - "comment" , keepComments ? this.comment : undefined, - "comments" , keepComments ? this.comments : undefined - ]); -}; + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'options', this.options, + 'values', this.values, + 'reserved', this.reserved && this.reserved.length ? this.reserved : undefined, + 'comment', keepComments ? this.comment : undefined, + 'comments', keepComments ? this.comments : undefined + ]) +} /** * Adds a value to this enum. @@ -101,33 +102,26 @@ Enum.prototype.toJSON = function toJSON(toJSONOptions) { * @throws {Error} If there is already a value with this name or id */ Enum.prototype.add = function add(name, id, comment) { - // utilized by the parser but not by .fromJSON + // utilized by the parser but not by .fromJSON - if (!util.isString(name)) - throw TypeError("name must be a string"); + if (!util.isString(name)) throw TypeError('name must be a string') - if (!util.isInteger(id)) - throw TypeError("id must be an integer"); + if (!util.isInteger(id)) throw TypeError('id must be an integer') - if (this.values[name] !== undefined) - throw Error("duplicate name '" + name + "' in " + this); + if (this.values[name] !== undefined) throw Error("duplicate name '" + name + "' in " + this) - if (this.isReservedId(id)) - throw Error("id " + id + " is reserved in " + this); + if (this.isReservedId(id)) throw Error('id ' + id + ' is reserved in ' + this) - if (this.isReservedName(name)) - throw Error("name '" + name + "' is reserved in " + this); + if (this.isReservedName(name)) throw Error("name '" + name + "' is reserved in " + this) - if (this.valuesById[id] !== undefined) { - if (!(this.options && this.options.allow_alias)) - throw Error("duplicate id " + id + " in " + this); - this.values[name] = id; - } else - this.valuesById[this.values[name] = id] = name; + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) throw Error('duplicate id ' + id + ' in ' + this) + this.values[name] = id + } else this.valuesById[this.values[name] = id] = name - this.comments[name] = comment || null; - return this; -}; + this.comments[name] = comment || null + return this +} /** * Removes a value from this enum @@ -137,20 +131,17 @@ Enum.prototype.add = function add(name, id, comment) { * @throws {Error} If `name` is not a name of this enum */ Enum.prototype.remove = function remove(name) { + if (!util.isString(name)) throw TypeError('name must be a string') - if (!util.isString(name)) - throw TypeError("name must be a string"); + const val = this.values[name] + if (val == null) throw Error("name '" + name + "' does not exist in " + this) - var val = this.values[name]; - if (val == null) - throw Error("name '" + name + "' does not exist in " + this); + delete this.valuesById[val] + delete this.values[name] + delete this.comments[name] - delete this.valuesById[val]; - delete this.values[name]; - delete this.comments[name]; - - return this; -}; + return this +} /** * Tests if the specified id is reserved. @@ -158,8 +149,8 @@ Enum.prototype.remove = function remove(name) { * @returns {boolean} `true` if reserved, otherwise `false` */ Enum.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; + return Namespace.isReservedId(this.reserved, id) +} /** * Tests if the specified name is reserved. @@ -167,5 +158,5 @@ Enum.prototype.isReservedId = function isReservedId(id) { * @returns {boolean} `true` if reserved, otherwise `false` */ Enum.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; \ No newline at end of file + return Namespace.isReservedName(this.reserved, name) +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/field.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/field.js index 8de03d6a..8662f6d5 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/field.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/field.js @@ -2,19 +2,20 @@ * Created by zhangmiao on 2018/3/12. */ -module.exports = Field; +module.exports = Field // extends ReflectionObject -var ReflectionObject = require("./object"); -((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; +const ReflectionObject = require('./object'); -var Enum, - types, - util; +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = 'Field' -var Type; // cyclic +let Enum +let types +let util -var ruleRe = /^required|optional|repeated$/; +let Type // cyclic + +const ruleRe = /^required|optional|repeated$/ /** * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. @@ -38,8 +39,8 @@ var ruleRe = /^required|optional|repeated$/; * @throws {TypeError} If arguments are invalid */ Field.fromJSON = function fromJSON(name, json) { - return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); -}; + return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment) +} /** * Not an actual constructor. Use {@link Field} instead. @@ -56,145 +57,140 @@ Field.fromJSON = function fromJSON(name, json) { * @param {string} [comment] Comment associated with this field */ function Field(name, id, type, rule, extend, options, comment) { + if (util.isObject(rule)) { + comment = extend + options = rule + rule = extend = undefined + } else if (util.isObject(extend)) { + comment = options + options = extend + extend = undefined + } - if (util.isObject(rule)) { - comment = extend; - options = rule; - rule = extend = undefined; - } else if (util.isObject(extend)) { - comment = options; - options = extend; - extend = undefined; - } - - ReflectionObject.call(this, name, options); + ReflectionObject.call(this, name, options) - if (!util.isInteger(id) || id < 0) - throw TypeError("id must be a non-negative integer"); + if (!util.isInteger(id) || id < 0) throw TypeError('id must be a non-negative integer') - if (!util.isString(type)) - throw TypeError("type must be a string"); + if (!util.isString(type)) throw TypeError('type must be a string') - if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) - throw TypeError("rule must be a string rule"); + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) throw TypeError('rule must be a string rule') - if (extend !== undefined && !util.isString(extend)) - throw TypeError("extend must be a string"); + if (extend !== undefined && !util.isString(extend)) throw TypeError('extend must be a string') - /** + /** * Field rule, if any. * @type {string|undefined} */ - this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + this.rule = rule && rule !== 'optional' ? rule : undefined // toJSON - /** + /** * Field type. * @type {string} */ - this.type = type; // toJSON + this.type = type // toJSON - /** + /** * Unique field id. * @type {number} */ - this.id = id; // toJSON, marker + this.id = id // toJSON, marker - /** + /** * Extended type if different from parent. * @type {string|undefined} */ - this.extend = extend || undefined; // toJSON + this.extend = extend || undefined // toJSON - /** + /** * Whether this field is required. * @type {boolean} */ - this.required = rule === "required"; + this.required = rule === 'required' - /** + /** * Whether this field is optional. * @type {boolean} */ - this.optional = !this.required; + this.optional = !this.required - /** + /** * Whether this field is repeated. * @type {boolean} */ - this.repeated = rule === "repeated"; + this.repeated = rule === 'repeated' - /** + /** * Whether this field is a map or not. * @type {boolean} */ - this.map = false; + this.map = false - /** + /** * Message this field belongs to. * @type {Type|null} */ - this.message = null; + this.message = null - /** + /** * OneOf this field belongs to, if any, * @type {OneOf|null} */ - this.partOf = null; + this.partOf = null - /** + /** * The field type's default value. * @type {*} */ - this.typeDefault = null; + this.typeDefault = null - /** + /** * The field's default value on prototypes. * @type {*} */ - this.defaultValue = null; + this.defaultValue = null - /** + /** * Whether this field's value should be treated as a long. * @type {boolean} */ - this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false - /** + /** * Whether this field's value is a buffer. * @type {boolean} */ - this.bytes = type === "bytes"; + this.bytes = type === 'bytes' - /** + /** * Resolved type if not a basic type. * @type {Type|Enum|null} */ - this.resolvedType = null; + this.resolvedType = null - /** + /** * Sister-field within the extended type if a declaring extension field. * @type {Field|null} */ - this.extensionField = null; + this.extensionField = null - /** + /** * Sister-field within the declaring namespace if an extended field. * @type {Field|null} */ - this.declaringField = null; + this.declaringField = null - /** + /** * Internally remembers whether this field is packed. * @type {boolean|null} * @private */ - this._packed = null; + this._packed = null - /** + /** * Comment for this field. * @type {string|null} */ - this.comment = comment; + this.comment = comment } /** @@ -203,23 +199,22 @@ function Field(name, id, type, rule, extend, options, comment) { * @type {boolean} * @readonly */ -Object.defineProperty(Field.prototype, "packed", { - get: function() { - // defaults to packed=true if not explicity set to false - if (this._packed === null) - this._packed = this.getOption("packed") !== false; - return this._packed; - } -}); +Object.defineProperty(Field.prototype, 'packed', { + get() { + // defaults to packed=true if not explicity set to false + if (this._packed === null) this._packed = this.getOption('packed') !== false + return this._packed + } +}) /** * @override */ Field.prototype.setOption = function setOption(name, value, ifNotSet) { - if (name === "packed") // clear cached before setting - this._packed = null; - return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); -}; + if (name === 'packed') // clear cached before setting + { this._packed = null } + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet) +} /** * Field descriptor. @@ -243,16 +238,16 @@ Field.prototype.setOption = function setOption(name, value, ifNotSet) { * @returns {IField} Field descriptor */ Field.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "rule" , this.rule !== "optional" && this.rule || undefined, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'rule', this.rule !== 'optional' && this.rule || undefined, + 'type', this.type, + 'id', this.id, + 'extend', this.extend, + 'options', this.options, + 'comment', keepComments ? this.comment : undefined + ]) +} /** * Resolves this field's type references. @@ -260,64 +255,53 @@ Field.prototype.toJSON = function toJSON(toJSONOptions) { * @throws {Error} If any reference cannot be resolved */ Field.prototype.resolve = function resolve() { - - if (this.resolved) - return this; - - if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it - this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); - if (this.resolvedType instanceof Type) - this.typeDefault = null; - else // instanceof Enum - this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined - } - - // use explicitly set default value if present - if (this.options && this.options["default"] != null) { - this.typeDefault = this.options["default"]; - if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") - this.typeDefault = this.resolvedType.values[this.typeDefault]; - } - - // remove unnecessary options - if (this.options) { - if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) - delete this.options.packed; - if (!Object.keys(this.options).length) - this.options = undefined; - } - - // convert to internal data type if necesssary - if (this.long) { - this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); - - /* istanbul ignore else */ - if (Object.freeze) - Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) - - } else if (this.bytes && typeof this.typeDefault === "string") { - var buf; - //if (util.base64.test(this.typeDefault)) - // util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); - //else - util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); - this.typeDefault = buf; - } - - // take special care of maps and repeated fields - if (this.map) - this.defaultValue = util.emptyObject; - else if (this.repeated) - this.defaultValue = util.emptyArray; - else - this.defaultValue = this.typeDefault; - - // ensure proper value on prototype - if (this.parent instanceof Type) { - this.parent.ctor.prototype[this.name] = this.defaultValue; - } - return ReflectionObject.prototype.resolve.call(this); -}; + if (this.resolved) return this + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type) + if (this.resolvedType instanceof Type) this.typeDefault = null + else // instanceof Enum + { this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]] } // first defined + } + + // use explicitly set default value if present + if (this.options && this.options.default != null) { + this.typeDefault = this.options.default + if (this.resolvedType instanceof Enum && typeof this.typeDefault === 'string') this.typeDefault = this.resolvedType.values[this.typeDefault] + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) delete this.options.packed + if (!Object.keys(this.options).length) this.options = undefined + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === 'u') + + /* istanbul ignore else */ + if (Object.freeze) Object.freeze(this.typeDefault) // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + } else if (this.bytes && typeof this.typeDefault === 'string') { + let buf + // if (util.base64.test(this.typeDefault)) + // util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + // else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0) + this.typeDefault = buf + } + + // take special care of maps and repeated fields + if (this.map) this.defaultValue = util.emptyObject + else if (this.repeated) this.defaultValue = util.emptyArray + else this.defaultValue = this.typeDefault + + // ensure proper value on prototype + if (this.parent instanceof Type) { + this.parent.ctor.prototype[this.name] = this.defaultValue + } + return ReflectionObject.prototype.resolve.call(this) +} /** * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). @@ -340,20 +324,17 @@ Field.prototype.resolve = function resolve() { * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] */ Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === 'function') fieldType = util.decorateType(fieldType).name - // submessage: decorate the submessage and use its name as the type - if (typeof fieldType === "function") - fieldType = util.decorateType(fieldType).name; - - // enum reference: create a reflected copy of the enum and keep reuseing it - else if (fieldType && typeof fieldType === "object") - fieldType = util.decorateEnum(fieldType).name; + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === 'object') fieldType = util.decorateEnum(fieldType).name - return function fieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); - }; -}; + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, {default: defaultValue})) + } +} /** * Field decorator (TypeScript). @@ -369,9 +350,9 @@ Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { // like Field.d but without a default value Field._configure = function configure() { - Type = require('./type'); + Type = require('./type') - Enum = require("./enum"); - types = require("./types"); - util = require("./util"); -}; + Enum = require('./enum') + types = require('./types') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/float.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/float.js index 3eabfe0e..a75d489c 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/float.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/float.js @@ -1,4 +1,4 @@ -module.exports = factory(factory); +module.exports = factory(factory) /** * Reads / writes floats / doubles from / to buffers. @@ -84,250 +84,244 @@ module.exports = factory(factory); // Factory function for the purpose of node-based testing in modified global environments function factory(exports) { - - // float: typed array - if (typeof Float32Array !== "undefined") (function() { - - var f32 = new Float32Array([ -0 ]), - f8b = new Uint8Array(f32.buffer), - le = f8b[3] === 128; - - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - /* istanbul ignore next */ - exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos ]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - - /* istanbul ignore next */ - exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - /* istanbul ignore next */ - exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - - // float: ieee754 - })(); else (function() { - - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 3.4028234663852886e+38) // +-Infinity - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 1.1754943508222875e-38) // denormal - writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), - mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } + // float: typed array + if (typeof Float32Array !== 'undefined') { + (function () { + const f32 = new Float32Array([-0]) + const f8b = new Uint8Array(f32.buffer) + const le = f8b[3] === 128 + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val + buf[pos] = f8b[0] + buf[pos + 1] = f8b[1] + buf[pos + 2] = f8b[2] + buf[pos + 3] = f8b[3] + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val + buf[pos] = f8b[3] + buf[pos + 1] = f8b[2] + buf[pos + 2] = f8b[1] + buf[pos + 3] = f8b[0] + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos] + f8b[1] = buf[pos + 1] + f8b[2] = buf[pos + 2] + f8b[3] = buf[pos + 3] + return f32[0] + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos] + f8b[2] = buf[pos + 1] + f8b[1] = buf[pos + 2] + f8b[0] = buf[pos + 3] + return f32[0] + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy + + // float: ieee754 + }()) + } else { + (function () { + function writeFloat_ieee754(writeUint, val, buf, pos) { + const sign = val < 0 ? 1 : 0 + if (sign) val = -val + if (val === 0) writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos) + else if (isNaN(val)) writeUint(2143289344, buf, pos) + else if (val > 3.4028234663852886e+38) // +-Infinity + { writeUint((sign << 31 | 2139095040) >>> 0, buf, pos) } else if (val < 1.1754943508222875e-38) // denormal + { writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos) } else { + const exponent = Math.floor(Math.log(val) / Math.LN2) + const mantissa = Math.round(val * 2 ** -exponent * 8388608) & 8388607 + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos) } - - exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), - sign = (uint >> 31) * 2 + 1, - exponent = uint >>> 23 & 255, - mantissa = uint & 8388607; - return exponent === 255 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 1.401298464324817e-45 * mantissa - : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE) + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE) + + function readFloat_ieee754(readUint, buf, pos) { + const uint = readUint(buf, pos) + const sign = (uint >> 31) * 2 + 1 + const exponent = uint >>> 23 & 255 + const mantissa = uint & 8388607 + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * 2 ** (exponent - 150) * (mantissa + 8388608) + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE) + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE) + }()) + } + + // double: typed array + if (typeof Float64Array !== 'undefined') { + (function () { + const f64 = new Float64Array([-0]) + const f8b = new Uint8Array(f64.buffer) + const le = f8b[7] === 128 + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val + buf[pos] = f8b[0] + buf[pos + 1] = f8b[1] + buf[pos + 2] = f8b[2] + buf[pos + 3] = f8b[3] + buf[pos + 4] = f8b[4] + buf[pos + 5] = f8b[5] + buf[pos + 6] = f8b[6] + buf[pos + 7] = f8b[7] + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val + buf[pos] = f8b[7] + buf[pos + 1] = f8b[6] + buf[pos + 2] = f8b[5] + buf[pos + 3] = f8b[4] + buf[pos + 4] = f8b[3] + buf[pos + 5] = f8b[2] + buf[pos + 6] = f8b[1] + buf[pos + 7] = f8b[0] + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos] + f8b[1] = buf[pos + 1] + f8b[2] = buf[pos + 2] + f8b[3] = buf[pos + 3] + f8b[4] = buf[pos + 4] + f8b[5] = buf[pos + 5] + f8b[6] = buf[pos + 6] + f8b[7] = buf[pos + 7] + return f64[0] + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos] + f8b[6] = buf[pos + 1] + f8b[5] = buf[pos + 2] + f8b[4] = buf[pos + 3] + f8b[3] = buf[pos + 4] + f8b[2] = buf[pos + 5] + f8b[1] = buf[pos + 6] + f8b[0] = buf[pos + 7] + return f64[0] + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy + + // double: ieee754 + }()) + } else { + (function () { + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + const sign = val < 0 ? 1 : 0 + if (sign) val = -val + if (val === 0) { + writeUint(0, buf, pos + off0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1) + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0) + writeUint(2146959360, buf, pos + off1) + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0) + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1) + } else { + let mantissa + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324 + writeUint(mantissa >>> 0, buf, pos + off0) + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1) + } else { + let exponent = Math.floor(Math.log(val) / Math.LN2) + if (exponent === 1024) exponent = 1023 + mantissa = val * 2 ** -exponent + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0) + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1) + } } - - exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - - })(); - - // double: typed array - if (typeof Float64Array !== "undefined") (function() { - - var f64 = new Float64Array([-0]), - f8b = new Uint8Array(f64.buffer), - le = f8b[7] === 128; - - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - /* istanbul ignore next */ - exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos ]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - - /* istanbul ignore next */ - exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - /* istanbul ignore next */ - exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - - // double: ieee754 - })(); else (function() { - - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 1.7976931348623157e+308) { // +-Infinity - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 2.2250738585072014e-308) { // denormal - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - - exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), - hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, - exponent = hi >>> 20 & 2047, - mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 5e-324 * mantissa - : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - - exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - - })(); - - return exports; + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4) + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0) + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + const lo = readUint(buf, pos + off0) + const hi = readUint(buf, pos + off1) + const sign = (hi >> 31) * 2 + 1 + const exponent = hi >>> 20 & 2047 + const mantissa = 4294967296 * (hi & 1048575) + lo + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * 2 ** (exponent - 1075) * (mantissa + 4503599627370496) + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4) + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0) + }()) + } + + return exports } // uint helpers function writeUintLE(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; + buf[pos] = val & 255 + buf[pos + 1] = val >>> 8 & 255 + buf[pos + 2] = val >>> 16 & 255 + buf[pos + 3] = val >>> 24 } function writeUintBE(val, buf, pos) { - buf[pos ] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; + buf[pos] = val >>> 24 + buf[pos + 1] = val >>> 16 & 255 + buf[pos + 2] = val >>> 8 & 255 + buf[pos + 3] = val & 255 } function readUintLE(buf, pos) { - return (buf[pos ] - | buf[pos + 1] << 8 - | buf[pos + 2] << 16 - | buf[pos + 3] << 24) >>> 0; + return (buf[pos] | + buf[pos + 1] << 8 | + buf[pos + 2] << 16 | + buf[pos + 3] << 24) >>> 0 } function readUintBE(buf, pos) { - return (buf[pos ] << 24 - | buf[pos + 1] << 16 - | buf[pos + 2] << 8 - | buf[pos + 3]) >>> 0; + return (buf[pos] << 24 | + buf[pos + 1] << 16 | + buf[pos + 2] << 8 | + buf[pos + 3]) >>> 0 } diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/inquire.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/inquire.js index 22425ec4..6da7fda5 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/inquire.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/inquire.js @@ -1,7 +1,7 @@ /** * Created by zhangmiao on 2018/3/14. */ -module.exports = inquire; +module.exports = inquire /** * Requires a module only if available. @@ -9,26 +9,24 @@ module.exports = inquire; * @param {string} moduleName Module to require * @returns {?Object} Required module if available and not empty, otherwise `null` */ -const app = getApp(); -app.globalData.pbModuleMap = app.globalData.pbModuleMap || {}; +const app = getApp() +app.globalData.pbModuleMap = app.globalData.pbModuleMap || {} function inquire(moduleName) { - var moduleMap = app.globalData.pbModuleMap; - var arr = moduleName.split('/'); - var name = arr[arr.length -1]; - if(typeof moduleMap[name] != 'undefined') - { - return moduleMap[name]; - } + const moduleMap = app.globalData.pbModuleMap + const arr = moduleName.split('/') + const name = arr[arr.length - 1] + if (typeof moduleMap[name] !== 'undefined') { + return moduleMap[name] + } - try { - var mod = require(moduleName); - if (mod) { - moduleMap[name] = mod; - return mod; - } - else { - console.log('没有加载到该模块') - } - } catch (e) {} // eslint-disable-line no-empty - return null; -} \ No newline at end of file + try { + const mod = require(moduleName) + if (mod) { + moduleMap[name] = mod + return mod + } else { + console.log('没有加载到该模块') + } + } catch (e) {} // eslint-disable-line no-empty + return null +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/long.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/long.js index 7a769e2f..a6be8da7 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/long.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/long.js @@ -1,16 +1,16 @@ -module.exports = Long; +module.exports = Long /** * wasm optimizations, to do native i64 multiplication and divide */ -var wasm = null; +let wasm = null try { - wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ - 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11 - ])), {}).exports; + wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([ + 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11 + ])), {}).exports } catch (e) { - // no wasm support :( + // no wasm support :( } /** @@ -24,24 +24,23 @@ try { * @constructor */ function Long(low, high, unsigned) { - - /** + /** * The low 32 bits as a signed value. * @type {number} */ - this.low = low | 0; + this.low = low | 0 - /** + /** * The high 32 bits as a signed value. * @type {number} */ - this.high = high | 0; + this.high = high | 0 - /** + /** * Whether unsigned or not. * @type {boolean} */ - this.unsigned = !!unsigned; + this.unsigned = !!unsigned } // The internal representation of a long is the two given signed, 32-bit values. @@ -67,9 +66,9 @@ function Long(low, high, unsigned) { * @const * @private */ -Long.prototype.__isLong__; +Long.prototype.__isLong__ -Object.defineProperty(Long.prototype, "__isLong__", { value: true }); +Object.defineProperty(Long.prototype, '__isLong__', {value: true}) /** * @function @@ -78,7 +77,7 @@ Object.defineProperty(Long.prototype, "__isLong__", { value: true }); * @inner */ function isLong(obj) { - return (obj && obj["__isLong__"]) === true; + return (obj && obj.__isLong__) === true } /** @@ -87,21 +86,21 @@ function isLong(obj) { * @param {*} obj Object * @returns {boolean} */ -Long.isLong = isLong; +Long.isLong = isLong /** * A cache of the Long representations of small integer values. * @type {!Object} * @inner */ -var INT_CACHE = {}; +const INT_CACHE = {} /** * A cache of the Long representations of small unsigned integer values. * @type {!Object} * @inner */ -var UINT_CACHE = {}; +const UINT_CACHE = {} /** * @param {number} value @@ -110,30 +109,27 @@ var UINT_CACHE = {}; * @inner */ function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if (cache = (0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true); - if (cache) - UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if (cache = (-128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) - return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) - INT_CACHE[value] = obj; - return obj; + let obj; let cachedObj; let + cache + if (unsigned) { + value >>>= 0 + if (cache = (value >= 0 && value < 256)) { + cachedObj = UINT_CACHE[value] + if (cachedObj) return cachedObj + } + obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true) + if (cache) UINT_CACHE[value] = obj + return obj + } else { + value |= 0 + if (cache = (value >= -128 && value < 128)) { + cachedObj = INT_CACHE[value] + if (cachedObj) return cachedObj } + obj = fromBits(value, value < 0 ? -1 : 0, false) + if (cache) INT_CACHE[value] = obj + return obj + } } /** @@ -143,7 +139,7 @@ function fromInt(value, unsigned) { * @param {boolean=} unsigned Whether unsigned or not, defaults to signed * @returns {!Long} The corresponding Long value */ -Long.fromInt = fromInt; +Long.fromInt = fromInt /** * @param {number} value @@ -152,22 +148,16 @@ Long.fromInt = fromInt; * @inner */ function fromNumber(value, unsigned) { - if (isNaN(value)) - return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) - return UZERO; - if (value >= TWO_PWR_64_DBL) - return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) - return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) - return MAX_VALUE; - } - if (value < 0) - return fromNumber(-value, unsigned).neg(); - return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned); + if (isNaN(value)) return unsigned ? UZERO : ZERO + if (unsigned) { + if (value < 0) return UZERO + if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE + } else { + if (value <= -TWO_PWR_63_DBL) return MIN_VALUE + if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE + } + if (value < 0) return fromNumber(-value, unsigned).neg() + return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned) } /** @@ -177,7 +167,7 @@ function fromNumber(value, unsigned) { * @param {boolean=} unsigned Whether unsigned or not, defaults to signed * @returns {!Long} The corresponding Long value */ -Long.fromNumber = fromNumber; +Long.fromNumber = fromNumber /** * @param {number} lowBits @@ -187,7 +177,7 @@ Long.fromNumber = fromNumber; * @inner */ function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); + return new Long(lowBits, highBits, unsigned) } /** @@ -199,7 +189,7 @@ function fromBits(lowBits, highBits, unsigned) { * @param {boolean=} unsigned Whether unsigned or not, defaults to signed * @returns {!Long} The corresponding Long value */ -Long.fromBits = fromBits; +Long.fromBits = fromBits /** * @function @@ -208,7 +198,7 @@ Long.fromBits = fromBits; * @returns {number} * @inner */ -var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) +const pow_dbl = Math.pow // Used 4 times (4*8 to 15+4) /** * @param {string} str @@ -218,46 +208,42 @@ var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) * @inner */ function fromString(str, unsigned, radix) { - if (str.length === 0) - throw Error('empty string'); - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") - return ZERO; - if (typeof unsigned === 'number') { - // For goog.math.long compatibility - radix = unsigned, - unsigned = false; + if (str.length === 0) throw Error('empty string') + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') return ZERO + if (typeof unsigned === 'number') { + // For goog.math.long compatibility + radix = unsigned, + unsigned = false + } else { + unsigned = !!unsigned + } + radix = radix || 10 + if (radix < 2 || radix > 36) throw RangeError('radix') + + let p + if ((p = str.indexOf('-')) > 0) throw Error('interior hyphen') + else if (p === 0) { + return fromString(str.substring(1), unsigned, radix).neg() + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = fromNumber(radix ** 8) + + let result = ZERO + for (let i = 0; i < str.length; i += 8) { + const size = Math.min(8, str.length - i) + const value = parseInt(str.substring(i, i + size), radix) + if (size < 8) { + const power = fromNumber(radix ** size) + result = result.mul(power).add(fromNumber(value)) } else { - unsigned = !! unsigned; - } - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - - var p; - if ((p = str.indexOf('-')) > 0) - throw Error('interior hyphen'); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); + result = result.mul(radixToPower) + result = result.add(fromNumber(value)) } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 8)); - - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; + } + result.unsigned = unsigned + return result } /** @@ -268,7 +254,7 @@ function fromString(str, unsigned, radix) { * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 * @returns {!Long} The corresponding Long value */ -Long.fromString = fromString; +Long.fromString = fromString /** * @function @@ -278,12 +264,10 @@ Long.fromString = fromString; * @inner */ function fromValue(val, unsigned) { - if (typeof val === 'number') - return fromNumber(val, unsigned); - if (typeof val === 'string') - return fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + if (typeof val === 'number') return fromNumber(val, unsigned) + if (typeof val === 'string') return fromString(val, unsigned) + // Throws for non-objects, converts non-instanceof Long: + return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned) } /** @@ -293,7 +277,7 @@ function fromValue(val, unsigned) { * @param {boolean=} unsigned Whether unsigned or not, defaults to signed * @returns {!Long} */ -Long.fromValue = fromValue; +Long.fromValue = fromValue // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be // no runtime penalty for these. @@ -303,162 +287,161 @@ Long.fromValue = fromValue; * @const * @inner */ -var TWO_PWR_16_DBL = 1 << 16; +const TWO_PWR_16_DBL = 1 << 16 /** * @type {number} * @const * @inner */ -var TWO_PWR_24_DBL = 1 << 24; +const TWO_PWR_24_DBL = 1 << 24 /** * @type {number} * @const * @inner */ -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL /** * @type {number} * @const * @inner */ -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL /** * @type {number} * @const * @inner */ -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2 /** * @type {!Long} * @const * @inner */ -var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); +const TWO_PWR_24 = fromInt(TWO_PWR_24_DBL) /** * @type {!Long} * @inner */ -var ZERO = fromInt(0); +var ZERO = fromInt(0) /** * Signed zero. * @type {!Long} */ -Long.ZERO = ZERO; +Long.ZERO = ZERO /** * @type {!Long} * @inner */ -var UZERO = fromInt(0, true); +var UZERO = fromInt(0, true) /** * Unsigned zero. * @type {!Long} */ -Long.UZERO = UZERO; +Long.UZERO = UZERO /** * @type {!Long} * @inner */ -var ONE = fromInt(1); +const ONE = fromInt(1) /** * Signed one. * @type {!Long} */ -Long.ONE = ONE; +Long.ONE = ONE /** * @type {!Long} * @inner */ -var UONE = fromInt(1, true); +const UONE = fromInt(1, true) /** * Unsigned one. * @type {!Long} */ -Long.UONE = UONE; +Long.UONE = UONE /** * @type {!Long} * @inner */ -var NEG_ONE = fromInt(-1); +const NEG_ONE = fromInt(-1) /** * Signed negative one. * @type {!Long} */ -Long.NEG_ONE = NEG_ONE; +Long.NEG_ONE = NEG_ONE /** * @type {!Long} * @inner */ -var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false); +var MAX_VALUE = fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0, false) /** * Maximum signed value. * @type {!Long} */ -Long.MAX_VALUE = MAX_VALUE; +Long.MAX_VALUE = MAX_VALUE /** * @type {!Long} * @inner */ -var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true); +var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF | 0, 0xFFFFFFFF | 0, true) /** * Maximum unsigned value. * @type {!Long} */ -Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; +Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE /** * @type {!Long} * @inner */ -var MIN_VALUE = fromBits(0, 0x80000000|0, false); +var MIN_VALUE = fromBits(0, 0x80000000 | 0, false) /** * Minimum signed value. * @type {!Long} */ -Long.MIN_VALUE = MIN_VALUE; +Long.MIN_VALUE = MIN_VALUE /** * @alias Long.prototype * @inner */ -var LongPrototype = Long.prototype; +const LongPrototype = Long.prototype /** * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * @returns {number} */ LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; -}; + return this.unsigned ? this.low >>> 0 : this.low +} /** * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * @returns {number} */ LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); -}; + if (this.unsigned) return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0) + return this.high * TWO_PWR_32_DBL + (this.low >>> 0) +} /** * Converts the Long to a string written in the specified radix. @@ -468,134 +451,127 @@ LongPrototype.toNumber = function toNumber() { * @throws {RangeError} If `radix` is out of range */ LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) - throw RangeError('radix'); - if (this.isZero()) - return '0'; - if (this.isNegative()) { // Unsigned Longs are never negative - if (this.eq(MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else - return '-' + this.neg().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), - rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower), - intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, - digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) - return digits + result; - else { - while (digits.length < 6) - digits = '0' + digits; - result = '' + digits + result; - } + radix = radix || 10 + if (radix < 2 || radix > 36) throw RangeError('radix') + if (this.isZero()) return '0' + if (this.isNegative()) { // Unsigned Longs are never negative + if (this.eq(MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + const radixLong = fromNumber(radix) + const div = this.div(radixLong) + const rem1 = div.mul(radixLong).sub(this) + return div.toString(radix) + rem1.toInt().toString(radix) + } else return '-' + this.neg().toString(radix) + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + const radixToPower = fromNumber(radix ** 6, this.unsigned) + let rem = this + let result = '' + while (true) { + const remDiv = rem.div(radixToPower) + const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0 + let digits = intval.toString(radix) + rem = remDiv + if (rem.isZero()) return digits + result + else { + while (digits.length < 6) digits = '0' + digits + result = '' + digits + result } -}; + } +} /** * Gets the high 32 bits as a signed integer. * @returns {number} Signed high bits */ LongPrototype.getHighBits = function getHighBits() { - return this.high; -}; + return this.high +} /** * Gets the high 32 bits as an unsigned integer. * @returns {number} Unsigned high bits */ LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; -}; + return this.high >>> 0 +} /** * Gets the low 32 bits as a signed integer. * @returns {number} Signed low bits */ LongPrototype.getLowBits = function getLowBits() { - return this.low; -}; + return this.low +} /** * Gets the low 32 bits as an unsigned integer. * @returns {number} Unsigned low bits */ LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; -}; + return this.low >>> 0 +} /** * Gets the number of bits needed to represent the absolute value of this Long. * @returns {number} */ LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) // Unsigned Longs are never negative - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) - if ((val & (1 << bit)) != 0) - break; - return this.high != 0 ? bit + 33 : bit + 1; -}; + if (this.isNegative()) // Unsigned Longs are never negative + { return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs() } + const val = this.high != 0 ? this.high : this.low + for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break + return this.high != 0 ? bit + 33 : bit + 1 +} /** * Tests if this Long's value equals zero. * @returns {boolean} */ LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; -}; + return this.high === 0 && this.low === 0 +} /** * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. * @returns {boolean} */ -LongPrototype.eqz = LongPrototype.isZero; +LongPrototype.eqz = LongPrototype.isZero /** * Tests if this Long's value is negative. * @returns {boolean} */ LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; -}; + return !this.unsigned && this.high < 0 +} /** * Tests if this Long's value is positive. * @returns {boolean} */ LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; -}; + return this.unsigned || this.high >= 0 +} /** * Tests if this Long's value is odd. * @returns {boolean} */ LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; -}; + return (this.low & 1) === 1 +} /** * Tests if this Long's value is even. * @returns {boolean} */ LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; -}; + return (this.low & 1) === 0 +} /** * Tests if this Long's value equals the specified's. @@ -603,12 +579,10 @@ LongPrototype.isEven = function isEven() { * @returns {boolean} */ LongPrototype.equals = function equals(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1) - return false; - return this.high === other.high && this.low === other.low; -}; + if (!isLong(other)) other = fromValue(other) + if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1) return false + return this.high === other.high && this.low === other.low +} /** * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. @@ -616,7 +590,7 @@ LongPrototype.equals = function equals(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.eq = LongPrototype.equals; +LongPrototype.eq = LongPrototype.equals /** * Tests if this Long's value differs from the specified's. @@ -624,8 +598,8 @@ LongPrototype.eq = LongPrototype.equals; * @returns {boolean} */ LongPrototype.notEquals = function notEquals(other) { - return !this.eq(/* validates */ other); -}; + return !this.eq(/* validates */ other) +} /** * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. @@ -633,7 +607,7 @@ LongPrototype.notEquals = function notEquals(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.neq = LongPrototype.notEquals; +LongPrototype.neq = LongPrototype.notEquals /** * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. @@ -641,7 +615,7 @@ LongPrototype.neq = LongPrototype.notEquals; * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.ne = LongPrototype.notEquals; +LongPrototype.ne = LongPrototype.notEquals /** * Tests if this Long's value is less than the specified's. @@ -649,8 +623,8 @@ LongPrototype.ne = LongPrototype.notEquals; * @returns {boolean} */ LongPrototype.lessThan = function lessThan(other) { - return this.comp(/* validates */ other) < 0; -}; + return this.comp(/* validates */ other) < 0 +} /** * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. @@ -658,7 +632,7 @@ LongPrototype.lessThan = function lessThan(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.lt = LongPrototype.lessThan; +LongPrototype.lt = LongPrototype.lessThan /** * Tests if this Long's value is less than or equal the specified's. @@ -666,8 +640,8 @@ LongPrototype.lt = LongPrototype.lessThan; * @returns {boolean} */ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(/* validates */ other) <= 0; -}; + return this.comp(/* validates */ other) <= 0 +} /** * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. @@ -675,7 +649,7 @@ LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.lte = LongPrototype.lessThanOrEqual; +LongPrototype.lte = LongPrototype.lessThanOrEqual /** * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. @@ -683,7 +657,7 @@ LongPrototype.lte = LongPrototype.lessThanOrEqual; * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.le = LongPrototype.lessThanOrEqual; +LongPrototype.le = LongPrototype.lessThanOrEqual /** * Tests if this Long's value is greater than the specified's. @@ -691,8 +665,8 @@ LongPrototype.le = LongPrototype.lessThanOrEqual; * @returns {boolean} */ LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(/* validates */ other) > 0; -}; + return this.comp(/* validates */ other) > 0 +} /** * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. @@ -700,7 +674,7 @@ LongPrototype.greaterThan = function greaterThan(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.gt = LongPrototype.greaterThan; +LongPrototype.gt = LongPrototype.greaterThan /** * Tests if this Long's value is greater than or equal the specified's. @@ -708,8 +682,8 @@ LongPrototype.gt = LongPrototype.greaterThan; * @returns {boolean} */ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(/* validates */ other) >= 0; -}; + return this.comp(/* validates */ other) >= 0 +} /** * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. @@ -717,7 +691,7 @@ LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.gte = LongPrototype.greaterThanOrEqual; +LongPrototype.gte = LongPrototype.greaterThanOrEqual /** * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. @@ -725,7 +699,7 @@ LongPrototype.gte = LongPrototype.greaterThanOrEqual; * @param {!Long|number|string} other Other value * @returns {boolean} */ -LongPrototype.ge = LongPrototype.greaterThanOrEqual; +LongPrototype.ge = LongPrototype.greaterThanOrEqual /** * Compares this Long's value with the specified's. @@ -734,22 +708,17 @@ LongPrototype.ge = LongPrototype.greaterThanOrEqual; * if the given one is greater */ LongPrototype.compare = function compare(other) { - if (!isLong(other)) - other = fromValue(other); - if (this.eq(other)) - return 0; - var thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) - return -1; - if (!thisNeg && otherNeg) - return 1; - // At this point the sign bits are the same - if (!this.unsigned) - return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1; -}; + if (!isLong(other)) other = fromValue(other) + if (this.eq(other)) return 0 + const thisNeg = this.isNegative() + const otherNeg = other.isNegative() + if (thisNeg && !otherNeg) return -1 + if (!thisNeg && otherNeg) return 1 + // At this point the sign bits are the same + if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1 + // Both are positive if at least one is unsigned + return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1 +} /** * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. @@ -758,24 +727,23 @@ LongPrototype.compare = function compare(other) { * @returns {number} 0 if they are the same, 1 if the this is greater and -1 * if the given one is greater */ -LongPrototype.comp = LongPrototype.compare; +LongPrototype.comp = LongPrototype.compare /** * Negates this Long's value. * @returns {!Long} Negated Long */ LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) - return MIN_VALUE; - return this.not().add(ONE); -}; + if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE + return this.not().add(ONE) +} /** * Negates this Long's value. This is an alias of {@link Long#negate}. * @function * @returns {!Long} Negated Long */ -LongPrototype.neg = LongPrototype.negate; +LongPrototype.neg = LongPrototype.negate /** * Returns the sum of this and the specified Long. @@ -783,35 +751,35 @@ LongPrototype.neg = LongPrototype.negate; * @returns {!Long} Sum */ LongPrototype.add = function add(addend) { - if (!isLong(addend)) - addend = fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xFFFF; - var a16 = this.low >>> 16; - var a00 = this.low & 0xFFFF; - - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xFFFF; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); -}; + if (!isLong(addend)) addend = fromValue(addend) + + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + const a48 = this.high >>> 16 + const a32 = this.high & 0xFFFF + const a16 = this.low >>> 16 + const a00 = this.low & 0xFFFF + + const b48 = addend.high >>> 16 + const b32 = addend.high & 0xFFFF + const b16 = addend.low >>> 16 + const b00 = addend.low & 0xFFFF + + let c48 = 0; let c32 = 0; let c16 = 0; let + c00 = 0 + c00 += a00 + b00 + c16 += c00 >>> 16 + c00 &= 0xFFFF + c16 += a16 + b16 + c32 += c16 >>> 16 + c16 &= 0xFFFF + c32 += a32 + b32 + c48 += c32 >>> 16 + c32 &= 0xFFFF + c48 += a48 + b48 + c48 &= 0xFFFF + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned) +} /** * Returns the difference of this and the specified Long. @@ -819,10 +787,9 @@ LongPrototype.add = function add(addend) { * @returns {!Long} Difference */ LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) - subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); -}; + if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend) + return this.add(subtrahend.neg()) +} /** * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. @@ -830,7 +797,7 @@ LongPrototype.subtract = function subtract(subtrahend) { * @param {!Long|number|string} subtrahend Subtrahend * @returns {!Long} Difference */ -LongPrototype.sub = LongPrototype.subtract; +LongPrototype.sub = LongPrototype.subtract /** * Returns the product of this and the specified Long. @@ -838,75 +805,69 @@ LongPrototype.sub = LongPrototype.subtract; * @returns {!Long} Product */ LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) - return ZERO; - if (!isLong(multiplier)) - multiplier = fromValue(multiplier); - - // use wasm support if present - if (wasm) { - var low = wasm.mul(this.low, - this.high, - multiplier.low, - multiplier.high); - return fromBits(low, wasm.get_high(), this.unsigned); - } - - if (multiplier.isZero()) - return ZERO; - if (this.eq(MIN_VALUE)) - return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) - return this.isOdd() ? MIN_VALUE : ZERO; - - if (this.isNegative()) { - if (multiplier.isNegative()) - return this.neg().mul(multiplier.neg()); - else - return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); - - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xFFFF; - var a16 = this.low >>> 16; - var a00 = this.low & 0xFFFF; - - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xFFFF; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); -}; + if (this.isZero()) return ZERO + if (!isLong(multiplier)) multiplier = fromValue(multiplier) + + // use wasm support if present + if (wasm) { + const low = wasm.mul( + this.low, + this.high, + multiplier.low, + multiplier.high + ) + return fromBits(low, wasm.get_high(), this.unsigned) + } + + if (multiplier.isZero()) return ZERO + if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO + if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO + + if (this.isNegative()) { + if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()) + else return this.neg().mul(multiplier).neg() + } else if (multiplier.isNegative()) return this.mul(multiplier.neg()).neg() + + // If both longs are small, use float multiplication + if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned) + + // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + const a48 = this.high >>> 16 + const a32 = this.high & 0xFFFF + const a16 = this.low >>> 16 + const a00 = this.low & 0xFFFF + + const b48 = multiplier.high >>> 16 + const b32 = multiplier.high & 0xFFFF + const b16 = multiplier.low >>> 16 + const b00 = multiplier.low & 0xFFFF + + let c48 = 0; let c32 = 0; let c16 = 0; let + c00 = 0 + c00 += a00 * b00 + c16 += c00 >>> 16 + c00 &= 0xFFFF + c16 += a16 * b00 + c32 += c16 >>> 16 + c16 &= 0xFFFF + c16 += a00 * b16 + c32 += c16 >>> 16 + c16 &= 0xFFFF + c32 += a32 * b00 + c48 += c32 >>> 16 + c32 &= 0xFFFF + c32 += a16 * b16 + c48 += c32 >>> 16 + c32 &= 0xFFFF + c32 += a00 * b32 + c48 += c32 >>> 16 + c32 &= 0xFFFF + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48 + c48 &= 0xFFFF + return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned) +} /** * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. @@ -914,7 +875,7 @@ LongPrototype.multiply = function multiply(multiplier) { * @param {!Long|number|string} multiplier Multiplier * @returns {!Long} Product */ -LongPrototype.mul = LongPrototype.multiply; +LongPrototype.mul = LongPrototype.multiply /** * Returns this Long divided by the specified. The result is signed if this Long is signed or @@ -923,111 +884,101 @@ LongPrototype.mul = LongPrototype.multiply; * @returns {!Long} Quotient */ LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - if (divisor.isZero()) - throw Error('division by zero'); - - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if (!this.unsigned && + if (!isLong(divisor)) divisor = fromValue(divisor) + if (divisor.isZero()) throw Error('division by zero') + + // use wasm support if present + if (wasm) { + // guard against signed division overflow: the largest + // negative number / -1 would be 1 larger than the largest + // positive number, due to two's complement. + if (!this.unsigned && this.high === -0x80000000 && divisor.low === -1 && divisor.high === -1) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm.div_u : wasm.div_s)( - this.low, - this.high, - divisor.low, - divisor.high - ); - return fromBits(low, wasm.get_high(), this.unsigned); + // be consistent with non-wasm code path + return this } - - if (this.isZero()) - return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(MIN_VALUE)) - return ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) - return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) - return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) - return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) - divisor = divisor.toUnsigned(); - if (divisor.gt(this)) - return UZERO; - if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true - return UONE; - res = UZERO; - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2), - delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48), - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - approxRes = fromNumber(approx), - approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); + const low = (this.unsigned ? wasm.div_u : wasm.div_s)( + this.low, + this.high, + divisor.low, + divisor.high + ) + return fromBits(low, wasm.get_high(), this.unsigned) + } + + if (this.isZero()) return this.unsigned ? UZERO : ZERO + let approx; let rem; let + res + if (!this.unsigned) { + // This section is only relevant for signed longs and is derived from the + // closure library as a whole. + if (this.eq(MIN_VALUE)) { + if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) return MIN_VALUE // recall that -MIN_VALUE == MIN_VALUE + else if (divisor.eq(MIN_VALUE)) return ONE + else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + const halfThis = this.shr(1) + approx = halfThis.div(divisor).shl(1) + if (approx.eq(ZERO)) { + return divisor.isNegative() ? ONE : NEG_ONE + } else { + rem = this.sub(divisor.mul(approx)) + res = approx.add(rem.div(divisor)) + return res } + } + } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO + if (this.isNegative()) { + if (divisor.isNegative()) return this.neg().div(divisor.neg()) + return this.neg().div(divisor).neg() + } else if (divisor.isNegative()) return this.div(divisor.neg()).neg() + res = ZERO + } else { + // The algorithm below has not been made for unsigned longs. It's therefore + // required to take special care of the MSB prior to running it. + if (!divisor.unsigned) divisor = divisor.toUnsigned() + if (divisor.gt(this)) return UZERO + if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true + { return UONE } + res = UZERO + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + rem = this + while (rem.gte(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())) + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + const log2 = Math.ceil(Math.log(approx) / Math.LN2) + const delta = (log2 <= 48) ? 1 : 2 ** (log2 - 48) + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + let approxRes = fromNumber(approx) + let approxRem = approxRes.mul(divisor) + while (approxRem.isNegative() || approxRem.gt(rem)) { + approx -= delta + approxRes = fromNumber(approx, this.unsigned) + approxRem = approxRes.mul(divisor) + } - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) - approxRes = ONE; + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) approxRes = ONE - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; -}; + res = res.add(approxRes) + rem = rem.sub(approxRem) + } + return res +} /** * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. @@ -1035,7 +986,7 @@ LongPrototype.divide = function divide(divisor) { * @param {!Long|number|string} divisor Divisor * @returns {!Long} Quotient */ -LongPrototype.div = LongPrototype.divide; +LongPrototype.div = LongPrototype.divide /** * Returns this Long modulo the specified. @@ -1043,22 +994,21 @@ LongPrototype.div = LongPrototype.divide; * @returns {!Long} Remainder */ LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) - divisor = fromValue(divisor); - - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( - this.low, - this.high, - divisor.low, - divisor.high - ); - return fromBits(low, wasm.get_high(), this.unsigned); - } - - return this.sub(this.div(divisor).mul(divisor)); -}; + if (!isLong(divisor)) divisor = fromValue(divisor) + + // use wasm support if present + if (wasm) { + const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)( + this.low, + this.high, + divisor.low, + divisor.high + ) + return fromBits(low, wasm.get_high(), this.unsigned) + } + + return this.sub(this.div(divisor).mul(divisor)) +} /** * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. @@ -1066,7 +1016,7 @@ LongPrototype.modulo = function modulo(divisor) { * @param {!Long|number|string} divisor Divisor * @returns {!Long} Remainder */ -LongPrototype.mod = LongPrototype.modulo; +LongPrototype.mod = LongPrototype.modulo /** * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. @@ -1074,15 +1024,15 @@ LongPrototype.mod = LongPrototype.modulo; * @param {!Long|number|string} divisor Divisor * @returns {!Long} Remainder */ -LongPrototype.rem = LongPrototype.modulo; +LongPrototype.rem = LongPrototype.modulo /** * Returns the bitwise NOT of this Long. * @returns {!Long} */ LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); -}; + return fromBits(~this.low, ~this.high, this.unsigned) +} /** * Returns the bitwise AND of this Long and the specified. @@ -1090,10 +1040,9 @@ LongPrototype.not = function not() { * @returns {!Long} */ LongPrototype.and = function and(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low & other.low, this.high & other.high, this.unsigned); -}; + if (!isLong(other)) other = fromValue(other) + return fromBits(this.low & other.low, this.high & other.high, this.unsigned) +} /** * Returns the bitwise OR of this Long and the specified. @@ -1101,10 +1050,9 @@ LongPrototype.and = function and(other) { * @returns {!Long} */ LongPrototype.or = function or(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low | other.low, this.high | other.high, this.unsigned); -}; + if (!isLong(other)) other = fromValue(other) + return fromBits(this.low | other.low, this.high | other.high, this.unsigned) +} /** * Returns the bitwise XOR of this Long and the given one. @@ -1112,10 +1060,9 @@ LongPrototype.or = function or(other) { * @returns {!Long} */ LongPrototype.xor = function xor(other) { - if (!isLong(other)) - other = fromValue(other); - return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); -}; + if (!isLong(other)) other = fromValue(other) + return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned) +} /** * Returns this Long with bits shifted to the left by the given amount. @@ -1123,15 +1070,11 @@ LongPrototype.xor = function xor(other) { * @returns {!Long} Shifted Long */ LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned); - else - return fromBits(0, this.low << (numBits - 32), this.unsigned); -}; + if (isLong(numBits)) numBits = numBits.toInt() + if ((numBits &= 63) === 0) return this + else if (numBits < 32) return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned) + else return fromBits(0, this.low << (numBits - 32), this.unsigned) +} /** * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. @@ -1139,7 +1082,7 @@ LongPrototype.shiftLeft = function shiftLeft(numBits) { * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -LongPrototype.shl = LongPrototype.shiftLeft; +LongPrototype.shl = LongPrototype.shiftLeft /** * Returns this Long with bits arithmetically shifted to the right by the given amount. @@ -1147,15 +1090,11 @@ LongPrototype.shl = LongPrototype.shiftLeft; * @returns {!Long} Shifted Long */ LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - if ((numBits &= 63) === 0) - return this; - else if (numBits < 32) - return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned); - else - return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned); -}; + if (isLong(numBits)) numBits = numBits.toInt() + if ((numBits &= 63) === 0) return this + else if (numBits < 32) return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned) + else return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned) +} /** * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. @@ -1163,7 +1102,7 @@ LongPrototype.shiftRight = function shiftRight(numBits) { * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -LongPrototype.shr = LongPrototype.shiftRight; +LongPrototype.shr = LongPrototype.shiftRight /** * Returns this Long with bits logically shifted to the right by the given amount. @@ -1171,22 +1110,18 @@ LongPrototype.shr = LongPrototype.shiftRight; * @returns {!Long} Shifted Long */ LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) - numBits = numBits.toInt(); - numBits &= 63; - if (numBits === 0) - return this; - else { - var high = this.high; - if (numBits < 32) { - var low = this.low; - return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned); - } else if (numBits === 32) - return fromBits(high, 0, this.unsigned); - else - return fromBits(high >>> (numBits - 32), 0, this.unsigned); - } -}; + if (isLong(numBits)) numBits = numBits.toInt() + numBits &= 63 + if (numBits === 0) return this + else { + const high = this.high + if (numBits < 32) { + const low = this.low + return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned) + } else if (numBits === 32) return fromBits(high, 0, this.unsigned) + else return fromBits(high >>> (numBits - 32), 0, this.unsigned) + } +} /** * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. @@ -1194,7 +1129,7 @@ LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -LongPrototype.shru = LongPrototype.shiftRightUnsigned; +LongPrototype.shru = LongPrototype.shiftRightUnsigned /** * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. @@ -1202,27 +1137,25 @@ LongPrototype.shru = LongPrototype.shiftRightUnsigned; * @param {number|!Long} numBits Number of bits * @returns {!Long} Shifted Long */ -LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; +LongPrototype.shr_u = LongPrototype.shiftRightUnsigned /** * Converts this Long to signed. * @returns {!Long} Signed long */ LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) - return this; - return fromBits(this.low, this.high, false); -}; + if (!this.unsigned) return this + return fromBits(this.low, this.high, false) +} /** * Converts this Long to unsigned. * @returns {!Long} Unsigned long */ LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) - return this; - return fromBits(this.low, this.high, true); -}; + if (this.unsigned) return this + return fromBits(this.low, this.high, true) +} /** * Converts this Long to its byte representation. @@ -1230,46 +1163,46 @@ LongPrototype.toUnsigned = function toUnsigned() { * @returns {!Array.} Byte representation */ LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); -}; + return le ? this.toBytesLE() : this.toBytesBE() +} /** * Converts this Long to its little endian byte representation. * @returns {!Array.} Little endian byte representation */ LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, - lo = this.low; - return [ - lo & 0xff, - lo >>> 8 & 0xff, - lo >>> 16 & 0xff, - lo >>> 24 , - hi & 0xff, - hi >>> 8 & 0xff, - hi >>> 16 & 0xff, - hi >>> 24 - ]; -}; + const hi = this.high + const lo = this.low + return [ + lo & 0xff, + lo >>> 8 & 0xff, + lo >>> 16 & 0xff, + lo >>> 24, + hi & 0xff, + hi >>> 8 & 0xff, + hi >>> 16 & 0xff, + hi >>> 24 + ] +} /** * Converts this Long to its big endian byte representation. * @returns {!Array.} Big endian byte representation */ LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, - lo = this.low; - return [ - hi >>> 24 , - hi >>> 16 & 0xff, - hi >>> 8 & 0xff, - hi & 0xff, - lo >>> 24 , - lo >>> 16 & 0xff, - lo >>> 8 & 0xff, - lo & 0xff - ]; -}; + const hi = this.high + const lo = this.low + return [ + hi >>> 24, + hi >>> 16 & 0xff, + hi >>> 8 & 0xff, + hi & 0xff, + lo >>> 24, + lo >>> 16 & 0xff, + lo >>> 8 & 0xff, + lo & 0xff + ] +} /** * Creates a Long from its byte representation. @@ -1279,8 +1212,8 @@ LongPrototype.toBytesBE = function toBytesBE() { * @returns {Long} The corresponding Long value */ Long.fromBytes = function fromBytes(bytes, unsigned, le) { - return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); -}; + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned) +} /** * Creates a Long from its little endian byte representation. @@ -1289,18 +1222,18 @@ Long.fromBytes = function fromBytes(bytes, unsigned, le) { * @returns {Long} The corresponding Long value */ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long( - bytes[0] | - bytes[1] << 8 | + return new Long( + bytes[0] | + bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24, - bytes[4] | - bytes[5] << 8 | + bytes[4] | + bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24, - unsigned - ); -}; + unsigned + ) +} /** * Creates a Long from its big endian byte representation. @@ -1309,15 +1242,15 @@ Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { * @returns {Long} The corresponding Long value */ Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long( - bytes[4] << 24 | + return new Long( + bytes[4] << 24 | bytes[5] << 16 | - bytes[6] << 8 | + bytes[6] << 8 | bytes[7], - bytes[0] << 24 | + bytes[0] << 24 | bytes[1] << 16 | - bytes[2] << 8 | + bytes[2] << 8 | bytes[3], - unsigned - ); -}; \ No newline at end of file + unsigned + ) +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/longBits.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/longBits.js index ae87a234..45f7d9ca 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/longBits.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/longBits.js @@ -1,122 +1,114 @@ -module.exports = LongBits; +module.exports = LongBits function LongBits(lo, hi) { - this.lo = lo >>> 0; - this.hi = hi >>> 0; + this.lo = lo >>> 0 + this.hi = hi >>> 0 } -var zero = LongBits.zero = new LongBits(0, 0); +const zero = LongBits.zero = new LongBits(0, 0) -zero.toNumber = function() { return 0; }; -zero.zzEncode = zero.zzDecode = function() { return this; }; -zero.length = function() { return 1; }; +zero.toNumber = function () { return 0 } +zero.zzEncode = zero.zzDecode = function () { return this } +zero.length = function () { return 1 } - -var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; +const zeroHash = LongBits.zeroHash = '\0\0\0\0\0\0\0\0' LongBits.fromNumber = function fromNumber(value) { - if (value === 0) - return zero; - var sign = value < 0;//如果sign为 1 ,表示为负数 - if (sign) - value = -value; - var lo = value >>> 0,//取出底32位 - hi = (value - lo) / 4294967296 >>> 0; //取出高32位 - if (sign) { //负数 - hi = ~hi >>> 0; //求取高32位的反码 - lo = ~lo >>> 0; //求取低32位的反码 - if (++lo > 4294967295) { //低32位大于Math.pow(2,31)-1 - lo = 0; - if (++hi > 4294967295) //高32位大于Math.pow(2,31)-1 - hi = 0; - } + if (value === 0) return zero + const sign = value < 0// 如果sign为 1 ,表示为负数 + if (sign) value = -value + let lo = value >>> 0; let // 取出底32位 + hi = (value - lo) / 4294967296 >>> 0 // 取出高32位 + if (sign) { // 负数 + hi = ~hi >>> 0 // 求取高32位的反码 + lo = ~lo >>> 0 // 求取低32位的反码 + if (++lo > 4294967295) { // 低32位大于Math.pow(2,31)-1 + lo = 0 + if (++hi > 4294967295) // 高32位大于Math.pow(2,31)-1 + { hi = 0 } } - return new LongBits(lo, hi); -}; - + } + return new LongBits(lo, hi) +} LongBits.from = function from(value) { - if (typeof value === "number") - return LongBits.fromNumber(value); - if (typeof value === "string" || value instanceof String) { - return LongBits.fromNumber(parseInt(value, 10)); - } - return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; -}; + if (typeof value === 'number') return LongBits.fromNumber(value) + if (typeof value === 'string' || value instanceof String) { + return LongBits.fromNumber(parseInt(value, 10)) + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero +} LongBits.prototype.toNumber = function toNumber(unsigned) { - if (!unsigned && this.hi >>> 31) { - var lo = ~this.lo + 1 >>> 0, - hi = ~this.hi >>> 0; - if (!lo) - hi = hi + 1 >>> 0; - return -(lo + hi * 4294967296); - } - return this.lo + this.hi * 4294967296; -}; + if (!unsigned && this.hi >>> 31) { + const lo = ~this.lo + 1 >>> 0 + let hi = ~this.hi >>> 0 + if (!lo) hi = hi + 1 >>> 0 + return -(lo + hi * 4294967296) + } + return this.lo + this.hi * 4294967296 +} LongBits.prototype.toLong = function toLong(unsigned) { - //return util.Long - // ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) - // /* istanbul ignore next */ - // : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; - return { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; -}; + // return util.Long + // ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + // /* istanbul ignore next */ + // : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; + return {low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned)} +} -var charCodeAt = String.prototype.charCodeAt; +const charCodeAt = String.prototype.charCodeAt LongBits.fromHash = function fromHash(hash) { - if (hash === zeroHash) - return zero; - return new LongBits( - ( charCodeAt.call(hash, 0) - | charCodeAt.call(hash, 1) << 8 - | charCodeAt.call(hash, 2) << 16 - | charCodeAt.call(hash, 3) << 24) >>> 0 - , - ( charCodeAt.call(hash, 4) - | charCodeAt.call(hash, 5) << 8 - | charCodeAt.call(hash, 6) << 16 - | charCodeAt.call(hash, 7) << 24) >>> 0 - ); -}; + if (hash === zeroHash) return zero + return new LongBits( + (charCodeAt.call(hash, 0) | + charCodeAt.call(hash, 1) << 8 | + charCodeAt.call(hash, 2) << 16 | + charCodeAt.call(hash, 3) << 24) >>> 0, + (charCodeAt.call(hash, 4) | + charCodeAt.call(hash, 5) << 8 | + charCodeAt.call(hash, 6) << 16 | + charCodeAt.call(hash, 7) << 24) >>> 0 + ) +} LongBits.prototype.toHash = function toHash() { - return String.fromCharCode( - this.lo & 255, - this.lo >>> 8 & 255, - this.lo >>> 16 & 255, - this.lo >>> 24 , - this.hi & 255, - this.hi >>> 8 & 255, - this.hi >>> 16 & 255, - this.hi >>> 24 - ); -}; + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24, + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ) +} LongBits.prototype.zzEncode = function zzEncode() { - var mask = this.hi >> 31; - this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; - this.lo = ( this.lo << 1 ^ mask) >>> 0; - return this; -}; + const mask = this.hi >> 31 + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0 + this.lo = (this.lo << 1 ^ mask) >>> 0 + return this +} LongBits.prototype.zzDecode = function zzDecode() { - var mask = -(this.lo & 1); - this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; - this.hi = ( this.hi >>> 1 ^ mask) >>> 0; - return this; -}; + const mask = -(this.lo & 1) + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0 + this.hi = (this.hi >>> 1 ^ mask) >>> 0 + return this +} LongBits.prototype.length = function length() { - var part0 = this.lo, - part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, - part2 = this.hi >>> 24; - return part2 === 0 - ? part1 === 0 - ? part0 < 16384 + const part0 = this.lo + const part1 = (this.lo >>> 28 | this.hi << 4) >>> 0 + const part2 = this.hi >>> 24 + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 ? part0 < 128 ? 1 : 2 : part0 < 2097152 ? 3 : 4 - : part1 < 16384 + : part1 < 16384 ? part1 < 128 ? 5 : 6 : part1 < 2097152 ? 7 : 8 - : part2 < 128 ? 9 : 10; -}; + : part2 < 128 ? 9 : 10 +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/mapField.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/mapField.js index 4ca5cbe1..085fcecb 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/mapField.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/mapField.js @@ -1,11 +1,12 @@ -module.exports = MapField; +module.exports = MapField // extends Field -var Field = require("./field"); -((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; +const Field = require('./field'); -var types, - util; +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = 'MapField' + +let types +let util /** * Constructs a new map field instance. @@ -20,26 +21,25 @@ var types, * @param {string} [comment] Comment associated with this field */ function MapField(name, id, keyType, type, options, comment) { - Field.call(this, name, id, type, undefined, undefined, options, comment); + Field.call(this, name, id, type, undefined, undefined, options, comment) - /* istanbul ignore if */ - if (!util.isString(keyType)) - throw TypeError("keyType must be a string"); + /* istanbul ignore if */ + if (!util.isString(keyType)) throw TypeError('keyType must be a string') - /** + /** * Key type. * @type {string} */ - this.keyType = keyType; // toJSON, marker + this.keyType = keyType // toJSON, marker - /** + /** * Resolved key type if not a basic type. * @type {ReflectionObject|null} */ - this.resolvedKeyType = null; + this.resolvedKeyType = null - // Overrides Field#map - this.map = true; + // Overrides Field#map + this.map = true } /** @@ -64,8 +64,8 @@ function MapField(name, id, keyType, type, options, comment) { * @throws {TypeError} If arguments are invalid */ MapField.fromJSON = function fromJSON(name, json) { - return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); -}; + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment) +} /** * Converts this map field to a map field descriptor. @@ -73,30 +73,28 @@ MapField.fromJSON = function fromJSON(name, json) { * @returns {IMapField} Map field descriptor */ MapField.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "keyType" , this.keyType, - "type" , this.type, - "id" , this.id, - "extend" , this.extend, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'keyType', this.keyType, + 'type', this.type, + 'id', this.id, + 'extend', this.extend, + 'options', this.options, + 'comment', keepComments ? this.comment : undefined + ]) +} /** * @override */ MapField.prototype.resolve = function resolve() { - if (this.resolved) - return this; + if (this.resolved) return this - // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" - if (types.mapKey[this.keyType] === undefined) - throw Error("invalid key type: " + this.keyType); + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) throw Error('invalid key type: ' + this.keyType) - return Field.prototype.resolve.call(this); -}; + return Field.prototype.resolve.call(this) +} /** * Map field decorator (TypeScript). @@ -109,22 +107,19 @@ MapField.prototype.resolve = function resolve() { * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } */ MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === 'function') fieldValueType = util.decorateType(fieldValueType).name - // submessage value: decorate the submessage and use its name as the type - if (typeof fieldValueType === "function") - fieldValueType = util.decorateType(fieldValueType).name; + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === 'object') fieldValueType = util.decorateEnum(fieldValueType).name - // enum reference value: create a reflected copy of the enum and keep reuseing it - else if (fieldValueType && typeof fieldValueType === "object") - fieldValueType = util.decorateEnum(fieldValueType).name; - - return function mapFieldDecorator(prototype, fieldName) { - util.decorateType(prototype.constructor) - .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); - }; -}; + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)) + } +} -MapField._configure = function(){ - types = require("./types"); - util = require("./util"); -}; \ No newline at end of file +MapField._configure = function () { + types = require('./types') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/message.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/message.js index 7bc9fceb..1c9b616f 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/message.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/message.js @@ -1,7 +1,6 @@ -"use strict"; -module.exports = Message; +module.exports = Message -var util; +let util /** * Constructs a new message instance. @@ -11,10 +10,8 @@ var util; * @template T extends object */ function Message(properties) { - // not used internally - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - this[keys[i]] = properties[keys[i]]; + // not used internally + if (properties) for (let keys = Object.keys(properties), i = 0; i < keys.length; ++i) this[keys[i]] = properties[keys[i]] } /** @@ -31,7 +28,7 @@ function Message(properties) { * @readonly */ -/*eslint-disable valid-jsdoc*/ +/* eslint-disable valid-jsdoc */ /** * Creates a new message of this type using the specified properties. @@ -41,8 +38,8 @@ function Message(properties) { * @this Constructor */ Message.create = function create(properties) { - return this.$type.create(properties); -}; + return this.$type.create(properties) +} /** * Encodes a message of this type. @@ -53,15 +50,15 @@ Message.create = function create(properties) { * @this Constructor */ Message.encode = function encode(message, writer) { - if(!arguments.length){ - return this.$type.encode(this); - }else if (arguments.length == 1){ - return this.$type.encode(arguments[0]); - }else{ - return this.$type.encode(arguments[0], arguments[1]); - } - //return this.$type.encode(message, writer); -}; + if (!arguments.length) { + return this.$type.encode(this) + } else if (arguments.length == 1) { + return this.$type.encode(arguments[0]) + } else { + return this.$type.encode(arguments[0], arguments[1]) + } + // return this.$type.encode(message, writer); +} /** * Encodes a message of this type preceeded by its length as a varint. @@ -72,8 +69,8 @@ Message.encode = function encode(message, writer) { * @this Constructor */ Message.encodeDelimited = function encodeDelimited(message, writer) { - return this.$type.encodeDelimited(message, writer); -}; + return this.$type.encodeDelimited(message, writer) +} /** * Decodes a message of this type. @@ -85,8 +82,8 @@ Message.encodeDelimited = function encodeDelimited(message, writer) { * @this Constructor */ Message.decode = function decode(reader) { - return this.$type.decode(reader); -}; + return this.$type.decode(reader) +} /** * Decodes a message of this type preceeded by its length as a varint. @@ -98,8 +95,8 @@ Message.decode = function decode(reader) { * @this Constructor */ Message.decodeDelimited = function decodeDelimited(reader) { - return this.$type.decodeDelimited(reader); -}; + return this.$type.decodeDelimited(reader) +} /** * Verifies a message of this type. @@ -109,8 +106,8 @@ Message.decodeDelimited = function decodeDelimited(reader) { * @returns {string|null} `null` if valid, otherwise the reason why it is not */ Message.verify = function verify(message) { - return this.$type.verify(message); -}; + return this.$type.verify(message) +} /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. @@ -120,8 +117,8 @@ Message.verify = function verify(message) { * @this Constructor */ Message.fromObject = function fromObject(object) { - return this.$type.fromObject(object); -}; + return this.$type.fromObject(object) +} /** * Creates a plain object from a message of this type. Also converts values to other types if specified. @@ -132,29 +129,27 @@ Message.fromObject = function fromObject(object) { * @this Constructor */ Message.toObject = function toObject(message, options) { - message = message || this; - return this.$type.toObject(message, options); -}; + message = message || this + return this.$type.toObject(message, options) +} /** * Converts this message to JSON. * @returns {Object.} JSON object */ Message.prototype.toJSON = function toJSON() { - return this.$type.toObject(this, util.toJSONOptions); -}; - - + return this.$type.toObject(this, util.toJSONOptions) +} -Message.set = function(key,value){ - Message[key] = value; -}; +Message.set = function (key, value) { + Message[key] = value +} -Message.get = function (key){ - return Message[key]; -}; -/*eslint-enable valid-jsdoc*/ +Message.get = function (key) { + return Message[key] +} +/* eslint-enable valid-jsdoc */ -Message._configure = function(){ - util = require("./util"); -} \ No newline at end of file +Message._configure = function () { + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/method.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/method.js index 3e82f5f2..9bae84c8 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/method.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/method.js @@ -1,11 +1,11 @@ -"use strict"; -module.exports = Method; +module.exports = Method // extends ReflectionObject -var ReflectionObject = require("./object"); -((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; +const ReflectionObject = require('./object'); -var util; +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = 'Method' + +let util /** * Constructs a new service method instance. @@ -22,77 +22,73 @@ var util; * @param {string} [comment] The comment for this method */ function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment) { + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream + requestStream = responseStream = undefined + } else if (util.isObject(responseStream)) { + options = responseStream + responseStream = undefined + } - /* istanbul ignore next */ - if (util.isObject(requestStream)) { - options = requestStream; - requestStream = responseStream = undefined; - } else if (util.isObject(responseStream)) { - options = responseStream; - responseStream = undefined; - } - - /* istanbul ignore if */ - if (!(type === undefined || util.isString(type))) - throw TypeError("type must be a string"); + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) throw TypeError('type must be a string') - /* istanbul ignore if */ - if (!util.isString(requestType)) - throw TypeError("requestType must be a string"); + /* istanbul ignore if */ + if (!util.isString(requestType)) throw TypeError('requestType must be a string') - /* istanbul ignore if */ - if (!util.isString(responseType)) - throw TypeError("responseType must be a string"); + /* istanbul ignore if */ + if (!util.isString(responseType)) throw TypeError('responseType must be a string') - ReflectionObject.call(this, name, options); + ReflectionObject.call(this, name, options) - /** + /** * Method type. * @type {string} */ - this.type = type || "rpc"; // toJSON + this.type = type || 'rpc' // toJSON - /** + /** * Request type. * @type {string} */ - this.requestType = requestType; // toJSON, marker + this.requestType = requestType // toJSON, marker - /** + /** * Whether requests are streamed or not. * @type {boolean|undefined} */ - this.requestStream = requestStream ? true : undefined; // toJSON + this.requestStream = requestStream ? true : undefined // toJSON - /** + /** * Response type. * @type {string} */ - this.responseType = responseType; // toJSON + this.responseType = responseType // toJSON - /** + /** * Whether responses are streamed or not. * @type {boolean|undefined} */ - this.responseStream = responseStream ? true : undefined; // toJSON + this.responseStream = responseStream ? true : undefined // toJSON - /** + /** * Resolved request type. * @type {Type|null} */ - this.resolvedRequestType = null; + this.resolvedRequestType = null - /** + /** * Resolved response type. * @type {Type|null} */ - this.resolvedResponseType = null; + this.resolvedResponseType = null - /** + /** * Comment for this method * @type {string|null} */ - this.comment = comment; + this.comment = comment } /** @@ -114,8 +110,8 @@ function Method(name, type, requestType, responseType, requestStream, responseSt * @throws {TypeError} If arguments are invalid */ Method.fromJSON = function fromJSON(name, json) { - return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment); -}; + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment) +} /** * Converts this method to a method descriptor. @@ -123,33 +119,31 @@ Method.fromJSON = function fromJSON(name, json) { * @returns {IMethod} Method descriptor */ Method.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, - "requestType" , this.requestType, - "requestStream" , this.requestStream, - "responseType" , this.responseType, - "responseStream" , this.responseStream, - "options" , this.options, - "comment" , keepComments ? this.comment : undefined - ]); -}; + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'type', this.type !== 'rpc' && /* istanbul ignore next */ this.type || undefined, + 'requestType', this.requestType, + 'requestStream', this.requestStream, + 'responseType', this.responseType, + 'responseStream', this.responseStream, + 'options', this.options, + 'comment', keepComments ? this.comment : undefined + ]) +} /** * @override */ Method.prototype.resolve = function resolve() { + /* istanbul ignore if */ + if (this.resolved) return this - /* istanbul ignore if */ - if (this.resolved) - return this; + this.resolvedRequestType = this.parent.lookupType(this.requestType) + this.resolvedResponseType = this.parent.lookupType(this.responseType) - this.resolvedRequestType = this.parent.lookupType(this.requestType); - this.resolvedResponseType = this.parent.lookupType(this.responseType); - - return ReflectionObject.prototype.resolve.call(this); -}; + return ReflectionObject.prototype.resolve.call(this) +} -Method._configure = function (){ - util = require("./util"); -} \ No newline at end of file +Method._configure = function () { + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/namespace.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/namespace.js index dddcf0e1..91a1999f 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/namespace.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/namespace.js @@ -1,16 +1,16 @@ - -module.exports = Namespace; +module.exports = Namespace // extends ReflectionObject -var ReflectionObject = require("./object"); -((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; +const ReflectionObject = require('./object'); + +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = 'Namespace' -var Enum, - Field, - util; +let Enum +let Field +let util -var Type; // cyclic -var Service; +let Type // cyclic +let Service /** * Constructs a new namespace instance. @@ -32,8 +32,8 @@ var Service; * @throws {TypeError} If arguments are invalid */ Namespace.fromJSON = function fromJSON(name, json) { - return new Namespace(name, json.options).addJSON(json.nested); -}; + return new Namespace(name, json.options).addJSON(json.nested) +} /** * Converts an array of reflection objects to JSON. @@ -43,15 +43,13 @@ Namespace.fromJSON = function fromJSON(name, json) { * @returns {Object.|undefined} JSON object or `undefined` when array is empty */ function arrayToJSON(array, toJSONOptions) { - if (!(array && array.length)) - return undefined; - var obj = {}; - for (var i = 0; i < array.length; ++i) - obj[array[i].name] = array[i].toJSON(toJSONOptions); - return obj; + if (!(array && array.length)) return undefined + const obj = {} + for (let i = 0; i < array.length; ++i) obj[array[i].name] = array[i].toJSON(toJSONOptions) + return obj } -Namespace.arrayToJSON = arrayToJSON; +Namespace.arrayToJSON = arrayToJSON /** * Tests if the specified id is reserved. @@ -60,12 +58,9 @@ Namespace.arrayToJSON = arrayToJSON; * @returns {boolean} `true` if reserved, otherwise `false` */ Namespace.isReservedId = function isReservedId(reserved, id) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id) - return true; - return false; -}; + if (reserved) for (let i = 0; i < reserved.length; ++i) if (typeof reserved[i] !== 'string' && reserved[i][0] <= id && reserved[i][1] >= id) return true + return false +} /** * Tests if the specified name is reserved. @@ -74,12 +69,9 @@ Namespace.isReservedId = function isReservedId(reserved, id) { * @returns {boolean} `true` if reserved, otherwise `false` */ Namespace.isReservedName = function isReservedName(reserved, name) { - if (reserved) - for (var i = 0; i < reserved.length; ++i) - if (reserved[i] === name) - return true; - return false; -}; + if (reserved) for (let i = 0; i < reserved.length; ++i) if (reserved[i] === name) return true + return false +} /** * Not an actual constructor. Use {@link Namespace} instead. @@ -93,25 +85,25 @@ Namespace.isReservedName = function isReservedName(reserved, name) { * @see {@link Namespace} */ function Namespace(name, options) { - ReflectionObject.call(this, name, options); + ReflectionObject.call(this, name, options) - /** + /** * Nested objects by name. * @type {Object.|undefined} */ - this.nested = undefined; // toJSON + this.nested = undefined // toJSON - /** + /** * Cached nested objects as an array. * @type {ReflectionObject[]|null} * @private */ - this._nestedArray = null; + this._nestedArray = null } function clearCache(namespace) { - namespace._nestedArray = null; - return namespace; + namespace._nestedArray = null + return namespace } /** @@ -120,11 +112,11 @@ function clearCache(namespace) { * @type {ReflectionObject[]} * @readonly */ -Object.defineProperty(Namespace.prototype, "nestedArray", { - get: function() { - return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); - } -}); +Object.defineProperty(Namespace.prototype, 'nestedArray', { + get() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)) + } +}) /** * Namespace descriptor. @@ -152,11 +144,11 @@ Object.defineProperty(Namespace.prototype, "nestedArray", { * @returns {INamespace} Namespace descriptor */ Namespace.prototype.toJSON = function toJSON(toJSONOptions) { - return util.toObject([ - "options" , this.options, - "nested" , arrayToJSON(this.nestedArray, toJSONOptions) - ]); -}; + return util.toObject([ + 'options', this.options, + 'nested', arrayToJSON(this.nestedArray, toJSONOptions) + ]) +} /** * Adds nested objects to this namespace from nested object descriptors. @@ -164,26 +156,26 @@ Namespace.prototype.toJSON = function toJSON(toJSONOptions) { * @returns {Namespace} `this` */ Namespace.prototype.addJSON = function addJSON(nestedJson) { - var ns = this; - /* istanbul ignore else */ - if (nestedJson) { - for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { - nested = nestedJson[names[i]]; - ns.add( // most to least likely - ( nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : nested.id !== undefined - ? Field.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); - } + const ns = this + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]] + ns.add( // most to least likely + (nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON)(names[i], nested) + ) } - return this; -}; + } + return this +} /** * Gets the nested object of the specified name. @@ -191,9 +183,9 @@ Namespace.prototype.addJSON = function addJSON(nestedJson) { * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist */ Namespace.prototype.get = function get(name) { - return this.nested && this.nested[name] - || null; -}; + return this.nested && this.nested[name] || + null +} /** * Gets the values of the nested {@link Enum|enum} of the specified name. @@ -203,10 +195,9 @@ Namespace.prototype.get = function get(name) { * @throws {Error} If there is no such enum */ Namespace.prototype.getEnum = function getEnum(name) { - if (this.nested && this.nested[name] instanceof Enum) - return this.nested[name].values; - throw Error("no such enum: " + name); -}; + if (this.nested && this.nested[name] instanceof Enum) return this.nested[name].values + throw Error('no such enum: ' + name) +} /** * Adds a nested object to this namespace. @@ -216,33 +207,26 @@ Namespace.prototype.getEnum = function getEnum(name) { * @throws {Error} If there is already a nested object with this name */ Namespace.prototype.add = function add(object) { - - if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace)) - throw TypeError("object must be a valid nested object"); - - if (!this.nested) - this.nested = {}; - else { - var prev = this.get(object.name); - if (prev) { - if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { - // replace plain namespace but keep existing nested elements and options - var nested = prev.nestedArray; - for (var i = 0; i < nested.length; ++i) - object.add(nested[i]); - this.remove(prev); - if (!this.nested) - this.nested = {}; - object.setOptions(prev.options, true); - - } else - throw Error("duplicate name '" + object.name + "' in " + this); - } + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace)) throw TypeError('object must be a valid nested object') + + if (!this.nested) this.nested = {} + else { + const prev = this.get(object.name) + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + const nested = prev.nestedArray + for (let i = 0; i < nested.length; ++i) object.add(nested[i]) + this.remove(prev) + if (!this.nested) this.nested = {} + object.setOptions(prev.options, true) + } else throw Error("duplicate name '" + object.name + "' in " + this) } - this.nested[object.name] = object; - object.onAdd(this); - return clearCache(this); -}; + } + this.nested[object.name] = object + object.onAdd(this) + return clearCache(this) +} /** * Removes a nested object from this namespace. @@ -252,19 +236,15 @@ Namespace.prototype.add = function add(object) { * @throws {Error} If `object` is not a member of this namespace */ Namespace.prototype.remove = function remove(object) { + if (!(object instanceof ReflectionObject)) throw TypeError('object must be a ReflectionObject') + if (object.parent !== this) throw Error(object + ' is not a member of ' + this) - if (!(object instanceof ReflectionObject)) - throw TypeError("object must be a ReflectionObject"); - if (object.parent !== this) - throw Error(object + " is not a member of " + this); - - delete this.nested[object.name]; - if (!Object.keys(this.nested).length) - this.nested = undefined; + delete this.nested[object.name] + if (!Object.keys(this.nested).length) this.nested = undefined - object.onRemove(this); - return clearCache(this); -}; + object.onRemove(this) + return clearCache(this) +} /** * Defines additial namespaces within this one if not yet existing. @@ -273,42 +253,35 @@ Namespace.prototype.remove = function remove(object) { * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty */ Namespace.prototype.define = function define(path, json) { - - if (util.isString(path)) - path = path.split("."); - else if (!Array.isArray(path)) - throw TypeError("illegal path"); - if (path && path.length && path[0] === "") - throw Error("path must be relative"); - - var ptr = this; - while (path.length > 0) { - var part = path.shift(); - if (ptr.nested && ptr.nested[part]) { - ptr = ptr.nested[part]; - if (!(ptr instanceof Namespace)) - throw Error("path conflicts with non-namespace objects"); - } else - ptr.add(ptr = new Namespace(part)); - } - if (json) - ptr.addJSON(json); - return ptr; -}; + if (util.isString(path)) path = path.split('.') + else if (!Array.isArray(path)) throw TypeError('illegal path') + if (path && path.length && path[0] === '') throw Error('path must be relative') + + let ptr = this + while (path.length > 0) { + const part = path.shift() + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part] + if (!(ptr instanceof Namespace)) throw Error('path conflicts with non-namespace objects') + } else ptr.add(ptr = new Namespace(part)) + } + if (json) ptr.addJSON(json) + return ptr +} /** * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. * @returns {Namespace} `this` */ Namespace.prototype.resolveAll = function resolveAll() { - var nested = this.nestedArray, i = 0; - while (i < nested.length) - if (nested[i] instanceof Namespace) - nested[i++].resolveAll(); - else - nested[i++].resolve(); - return this.resolve(); -}; + const nested = this.nestedArray; let + i = 0 + while (i < nested.length) { + if (nested[i] instanceof Namespace) nested[i++].resolveAll() + else nested[i++].resolve() + } + return this.resolve() +} /** * Recursively looks up the reflection object matching the specified path in the scope of this namespace. @@ -318,45 +291,34 @@ Namespace.prototype.resolveAll = function resolveAll() { * @returns {ReflectionObject|null} Looked up object or `null` if none could be found */ Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { - - /* istanbul ignore next */ - if (typeof filterTypes === "boolean") { - parentAlreadyChecked = filterTypes; - filterTypes = undefined; - } else if (filterTypes && !Array.isArray(filterTypes)) - filterTypes = [ filterTypes ]; - - if (util.isString(path) && path.length) { - if (path === ".") - return this.root; - path = path.split("."); - } else if (!path.length) - return this; - - // Start at root if path is absolute - if (path[0] === "") - return this.root.lookup(path.slice(1), filterTypes); - - // Test if the first part matches any nested object, and if so, traverse if path contains more - var found = this.get(path[0]); - if (found) { - if (path.length === 1) { - if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) - return found; - } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) - return found; - - // Otherwise try each nested namespace - } else - for (var i = 0; i < this.nestedArray.length; ++i) - if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) - return found; - - // If there hasn't been a match, try again at the parent - if (this.parent === null || parentAlreadyChecked) - return null; - return this.parent.lookup(path, filterTypes); -}; + /* istanbul ignore next */ + if (typeof filterTypes === 'boolean') { + parentAlreadyChecked = filterTypes + filterTypes = undefined + } else if (filterTypes && !Array.isArray(filterTypes)) filterTypes = [filterTypes] + + if (util.isString(path) && path.length) { + if (path === '.') return this.root + path = path.split('.') + } else if (!path.length) return this + + // Start at root if path is absolute + if (path[0] === '') return this.root.lookup(path.slice(1), filterTypes) + + // Test if the first part matches any nested object, and if so, traverse if path contains more + let found = this.get(path[0]) + if (found) { + if (path.length === 1) { + if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) return found + } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) return found + + // Otherwise try each nested namespace + } else for (let i = 0; i < this.nestedArray.length; ++i) if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) return found + + // If there hasn't been a match, try again at the parent + if (this.parent === null || parentAlreadyChecked) return null + return this.parent.lookup(path, filterTypes) +} /** * Looks up the reflection object at the specified path, relative to this namespace. @@ -377,11 +339,10 @@ Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChe * @throws {Error} If `path` does not point to a type */ Namespace.prototype.lookupType = function lookupType(path) { - var found = this.lookup(path, [ Type ]); - if (!found) - throw Error("no such type: " + path); - return found; -}; + const found = this.lookup(path, [Type]) + if (!found) throw Error('no such type: ' + path) + return found +} /** * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. @@ -391,11 +352,10 @@ Namespace.prototype.lookupType = function lookupType(path) { * @throws {Error} If `path` does not point to an enum */ Namespace.prototype.lookupEnum = function lookupEnum(path) { - var found = this.lookup(path, [ Enum ]); - if (!found) - throw Error("no such Enum '" + path + "' in " + this); - return found; -}; + const found = this.lookup(path, [Enum]) + if (!found) throw Error("no such Enum '" + path + "' in " + this) + return found +} /** * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. @@ -405,11 +365,10 @@ Namespace.prototype.lookupEnum = function lookupEnum(path) { * @throws {Error} If `path` does not point to a type or enum */ Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { - var found = this.lookup(path, [ Type, Enum ]); - if (!found) - throw Error("no such Type or Enum '" + path + "' in " + this); - return found; -}; + const found = this.lookup(path, [Type, Enum]) + if (!found) throw Error("no such Type or Enum '" + path + "' in " + this) + return found +} /** * Looks up the {@link Service|service} at the specified path, relative to this namespace. @@ -419,17 +378,16 @@ Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { * @throws {Error} If `path` does not point to a service */ Namespace.prototype.lookupService = function lookupService(path) { - var found = this.lookup(path, [ Service ]); - if (!found) - throw Error("no such Service '" + path + "' in " + this); - return found; -}; - -Namespace._configure = function() { - Enum = require("./enum"); - Field = require("./field"); - util = require("./util"); - - Type = require("./type"); // cyclic - Service = require("./service"); -}; \ No newline at end of file + const found = this.lookup(path, [Service]) + if (!found) throw Error("no such Service '" + path + "' in " + this) + return found +} + +Namespace._configure = function () { + Enum = require('./enum') + Field = require('./field') + util = require('./util') + + Type = require('./type') // cyclic + Service = require('./service') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/object.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/object.js index 0b7dfc49..0499916f 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/object.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/object.js @@ -1,10 +1,9 @@ -"use strict"; -module.exports = ReflectionObject; +module.exports = ReflectionObject -ReflectionObject.className = "ReflectionObject"; -var util; +ReflectionObject.className = 'ReflectionObject' +let util -var Root; // cyclic +let Root // cyclic /** * Constructs a new reflection object instance. @@ -15,85 +14,81 @@ var Root; // cyclic * @abstract */ function ReflectionObject(name, options) { + if (!util.isString(name)) throw TypeError('name must be a string') - if (!util.isString(name)) - throw TypeError("name must be a string"); + if (options && !util.isObject(options)) throw TypeError('options must be an object') - if (options && !util.isObject(options)) - throw TypeError("options must be an object"); - - /** + /** * Options. * @type {Object.|undefined} */ - this.options = options; // toJSON + this.options = options // toJSON - /** + /** * Unique name within its namespace. * @type {string} */ - this.name = name; + this.name = name - /** + /** * Parent namespace. * @type {Namespace|null} */ - this.parent = null; + this.parent = null - /** + /** * Whether already resolved or not. * @type {boolean} */ - this.resolved = false; + this.resolved = false - /** + /** * Comment text, if any. * @type {string|null} */ - this.comment = null; + this.comment = null - /** + /** * Defining file name. * @type {string|null} */ - this.filename = null; + this.filename = null } Object.defineProperties(ReflectionObject.prototype, { - /** + /** * Reference to the root namespace. * @name ReflectionObject#root * @type {Root} * @readonly */ - root: { - get: function() { - var ptr = this; - while (ptr.parent !== null) - ptr = ptr.parent; - return ptr; - } - }, - - /** + root: { + get() { + let ptr = this + while (ptr.parent !== null) ptr = ptr.parent + return ptr + } + }, + + /** * Full name including leading dot. * @name ReflectionObject#fullName * @type {string} * @readonly */ - fullName: { - get: function() { - var path = [ this.name ], - ptr = this.parent; - while (ptr) { - path.unshift(ptr.name); - ptr = ptr.parent; - } - return path.join("."); - } + fullName: { + get() { + const path = [this.name] + let ptr = this.parent + while (ptr) { + path.unshift(ptr.name) + ptr = ptr.parent + } + return path.join('.') } -}); + } +}) /** * Converts this reflection object to its descriptor representation. @@ -101,8 +96,8 @@ Object.defineProperties(ReflectionObject.prototype, { * @abstract */ ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { - throw Error(); // not implemented, shouldn't happen -}; + throw Error() // not implemented, shouldn't happen +} /** * Called when this object is added to a parent. @@ -110,14 +105,12 @@ ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() * @returns {undefined} */ ReflectionObject.prototype.onAdd = function onAdd(parent) { - if (this.parent && this.parent !== parent) - this.parent.remove(this); - this.parent = parent; - this.resolved = false; - var root = parent.root; - if (root instanceof Root) - root._handleAdd(this); -}; + if (this.parent && this.parent !== parent) this.parent.remove(this) + this.parent = parent + this.resolved = false + const root = parent.root + if (root instanceof Root) root._handleAdd(this) +} /** * Called when this object is removed from a parent. @@ -125,24 +118,21 @@ ReflectionObject.prototype.onAdd = function onAdd(parent) { * @returns {undefined} */ ReflectionObject.prototype.onRemove = function onRemove(parent) { - var root = parent.root; - if (root instanceof Root) - root._handleRemove(this); - this.parent = null; - this.resolved = false; -}; + const root = parent.root + if (root instanceof Root) root._handleRemove(this) + this.parent = null + this.resolved = false +} /** * Resolves this objects type references. * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.resolve = function resolve() { - if (this.resolved) - return this; - if (this.root instanceof Root) - this.resolved = true; // only if part of a root - return this; -}; + if (this.resolved) return this + if (this.root instanceof Root) this.resolved = true // only if part of a root + return this +} /** * Gets an option value. @@ -150,10 +140,9 @@ ReflectionObject.prototype.resolve = function resolve() { * @returns {*} Option value or `undefined` if not set */ ReflectionObject.prototype.getOption = function getOption(name) { - if (this.options) - return this.options[name]; - return undefined; -}; + if (this.options) return this.options[name] + return undefined +} /** * Sets an option. @@ -163,10 +152,9 @@ ReflectionObject.prototype.getOption = function getOption(name) { * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { - if (!ifNotSet || !this.options || this.options[name] === undefined) - (this.options || (this.options = {}))[name] = value; - return this; -}; + if (!ifNotSet || !this.options || this.options[name] === undefined) (this.options || (this.options = {}))[name] = value + return this +} /** * Sets multiple options. @@ -175,25 +163,22 @@ ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) * @returns {ReflectionObject} `this` */ ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { - if (options) - for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) - this.setOption(keys[i], options[keys[i]], ifNotSet); - return this; -}; + if (options) for (let keys = Object.keys(options), i = 0; i < keys.length; ++i) this.setOption(keys[i], options[keys[i]], ifNotSet) + return this +} /** * Converts this instance to its string representation. * @returns {string} Class name[, space, full name] */ ReflectionObject.prototype.toString = function toString() { - var className = this.constructor.className, - fullName = this.fullName; - if (fullName.length) - return className + " " + fullName; - return className; -}; - -ReflectionObject._configure = function(Root_) { - Root = require('./root'); - util = require('./util'); -}; + const className = this.constructor.className + const fullName = this.fullName + if (fullName.length) return className + ' ' + fullName + return className +} + +ReflectionObject._configure = function (Root_) { + Root = require('./root') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/oneof.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/oneof.js index c5605c31..f1c7c69e 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/oneof.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/oneof.js @@ -1,11 +1,12 @@ -module.exports = OneOf; +module.exports = OneOf // extends ReflectionObject -var ReflectionObject = require("./object"); -((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; +const ReflectionObject = require('./object'); -var Field; -var util; +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = 'OneOf' + +let Field +let util /** * Constructs a new oneof instance. @@ -18,34 +19,33 @@ var util; * @param {string} [comment] Comment associated with this field */ function OneOf(name, fieldNames, options, comment) { - if (!Array.isArray(fieldNames)) { - options = fieldNames; - fieldNames = undefined; - } - ReflectionObject.call(this, name, options); + if (!Array.isArray(fieldNames)) { + options = fieldNames + fieldNames = undefined + } + ReflectionObject.call(this, name, options) - /* istanbul ignore if */ - if (!(fieldNames === undefined || Array.isArray(fieldNames))) - throw TypeError("fieldNames must be an Array"); + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) throw TypeError('fieldNames must be an Array') - /** + /** * Field names that belong to this oneof. * @type {string[]} */ - this.oneof = fieldNames || []; // toJSON, marker + this.oneof = fieldNames || [] // toJSON, marker - /** + /** * Fields that belong to this oneof as an array for iteration. * @type {Field[]} * @readonly */ - this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + this.fieldsArray = [] // declared readonly for conformance, possibly not yet added to parent - /** + /** * Comment for this field. * @type {string|null} */ - this.comment = comment; + this.comment = comment } /** @@ -63,8 +63,8 @@ function OneOf(name, fieldNames, options, comment) { * @throws {TypeError} If arguments are invalid */ OneOf.fromJSON = function fromJSON(name, json) { - return new OneOf(name, json.oneof, json.options, json.comment); -}; + return new OneOf(name, json.oneof, json.options, json.comment) +} /** * Converts this oneof to a oneof descriptor. @@ -72,13 +72,13 @@ OneOf.fromJSON = function fromJSON(name, json) { * @returns {IOneOf} Oneof descriptor */ OneOf.prototype.toJSON = function toJSON(toJSONOptions) { - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options" , this.options, - "oneof" , this.oneof, - "comment" , keepComments ? this.comment : undefined - ]); -}; + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'options', this.options, + 'oneof', this.oneof, + 'comment', keepComments ? this.comment : undefined + ]) +} /** * Adds the fields of the specified oneof to the parent if not already done so. @@ -88,10 +88,7 @@ OneOf.prototype.toJSON = function toJSON(toJSONOptions) { * @ignore */ function addFieldsToParent(oneof) { - if (oneof.parent) - for (var i = 0; i < oneof.fieldsArray.length; ++i) - if (!oneof.fieldsArray[i].parent) - oneof.parent.add(oneof.fieldsArray[i]); + if (oneof.parent) for (let i = 0; i < oneof.fieldsArray.length; ++i) if (!oneof.fieldsArray[i].parent) oneof.parent.add(oneof.fieldsArray[i]) } /** @@ -100,19 +97,16 @@ function addFieldsToParent(oneof) { * @returns {OneOf} `this` */ OneOf.prototype.add = function add(field) { - - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); - - if (field.parent && field.parent !== this.parent) - field.parent.remove(field); - this.oneof.push(field.name); - this.fieldsArray.push(field); - field.partOf = this; // field.parent remains null - addFieldsToParent(this); - return this; -}; + /* istanbul ignore if */ + if (!(field instanceof Field)) throw TypeError('field must be a Field') + + if (field.parent && field.parent !== this.parent) field.parent.remove(field) + this.oneof.push(field.name) + this.fieldsArray.push(field) + field.partOf = this // field.parent remains null + addFieldsToParent(this) + return this +} /** * Removes a field from this oneof and puts it back to the oneof's parent. @@ -120,55 +114,50 @@ OneOf.prototype.add = function add(field) { * @returns {OneOf} `this` */ OneOf.prototype.remove = function remove(field) { + /* istanbul ignore if */ + if (!(field instanceof Field)) throw TypeError('field must be a Field') - /* istanbul ignore if */ - if (!(field instanceof Field)) - throw TypeError("field must be a Field"); + let index = this.fieldsArray.indexOf(field) - var index = this.fieldsArray.indexOf(field); + /* istanbul ignore if */ + if (index < 0) throw Error(field + ' is not a member of ' + this) - /* istanbul ignore if */ - if (index < 0) - throw Error(field + " is not a member of " + this); + this.fieldsArray.splice(index, 1) + index = this.oneof.indexOf(field.name) - this.fieldsArray.splice(index, 1); - index = this.oneof.indexOf(field.name); + /* istanbul ignore else */ + if (index > -1) // theoretical + { this.oneof.splice(index, 1) } - /* istanbul ignore else */ - if (index > -1) // theoretical - this.oneof.splice(index, 1); - - field.partOf = null; - return this; -}; + field.partOf = null + return this +} /** * @override */ OneOf.prototype.onAdd = function onAdd(parent) { - ReflectionObject.prototype.onAdd.call(this, parent); - var self = this; - // Collect present fields - for (var i = 0; i < this.oneof.length; ++i) { - var field = parent.get(this.oneof[i]); - if (field && !field.partOf) { - field.partOf = self; - self.fieldsArray.push(field); - } + ReflectionObject.prototype.onAdd.call(this, parent) + const self = this + // Collect present fields + for (let i = 0; i < this.oneof.length; ++i) { + const field = parent.get(this.oneof[i]) + if (field && !field.partOf) { + field.partOf = self + self.fieldsArray.push(field) } - // Add not yet present fields - addFieldsToParent(this); -}; + } + // Add not yet present fields + addFieldsToParent(this) +} /** * @override */ OneOf.prototype.onRemove = function onRemove(parent) { - for (var i = 0, field; i < this.fieldsArray.length; ++i) - if ((field = this.fieldsArray[i]).parent) - field.parent.remove(field); - ReflectionObject.prototype.onRemove.call(this, parent); -}; + for (var i = 0, field; i < this.fieldsArray.length; ++i) if ((field = this.fieldsArray[i]).parent) field.parent.remove(field) + ReflectionObject.prototype.onRemove.call(this, parent) +} /** * Decorator function as returned by {@link OneOf.d} (TypeScript). @@ -187,21 +176,20 @@ OneOf.prototype.onRemove = function onRemove(parent) { * @template T extends string */ OneOf.d = function decorateOneOf() { - var fieldNames = new Array(arguments.length), - index = 0; - while (index < arguments.length) - fieldNames[index] = arguments[index++]; - return function oneOfDecorator(prototype, oneofName) { - util.decorateType(prototype.constructor) - .add(new OneOf(oneofName, fieldNames)); - Object.defineProperty(prototype, oneofName, { - get: util.oneOfGetter(fieldNames), - set: util.oneOfSetter(fieldNames) - }); - }; -}; - -OneOf._configure = function (){ - Field = require('./field'); - util = require('./util'); -}; \ No newline at end of file + const fieldNames = new Array(arguments.length) + let index = 0 + while (index < arguments.length) fieldNames[index] = arguments[index++] + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)) + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }) + } +} + +OneOf._configure = function () { + Field = require('./field') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/parse.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/parse.js index d7f43894..8e138423 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/parse.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/parse.js @@ -1,31 +1,30 @@ -"use strict"; -module.exports = parse; - -parse.filename = null; -parse.defaults = { keepCase: false }; - -var tokenize, - Root, - Type, - Field, - MapField, - OneOf, - Enum, - Service, - Method, - types, - util; - -var base10Re = /^[1-9][0-9]*$/, - base10NegRe = /^-?[1-9][0-9]*$/, - base16Re = /^0[x][0-9a-fA-F]+$/, - base16NegRe = /^-?0[x][0-9a-fA-F]+$/, - base8Re = /^0[0-7]+$/, - base8NegRe = /^-?0[0-7]+$/, - numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, - nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, - typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/, - fqTypeRefRe = /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/; +module.exports = parse + +parse.filename = null +parse.defaults = {keepCase: false} + +let tokenize +let Root +let Type +let Field +let MapField +let OneOf +let Enum +let Service +let Method +let types +let util + +const base10Re = /^[1-9][0-9]*$/ +const base10NegRe = /^-?[1-9][0-9]*$/ +const base16Re = /^0[x][0-9a-fA-F]+$/ +const base16NegRe = /^-?0[x][0-9a-fA-F]+$/ +const base8Re = /^0[0-7]+$/ +const base8NegRe = /^-?0[0-7]+$/ +const numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/ +const nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/ +const typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/ +const fqTypeRefRe = /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/ /** * Result object returned from {@link parse}. @@ -60,688 +59,609 @@ var base10Re = /^[1-9][0-9]*$/, * @property {IParseOptions} defaults Default {@link IParseOptions} */ function parse(source, root, options) { - /* eslint-disable callback-return */ - if (!(root instanceof Root)) { - options = root; - root = new Root(); + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root + root = new Root() + } + if (!options) options = parse.defaults + + const tn = tokenize(source, options.alternateCommentMode || false) + const next = tn.next + const push = tn.push + const peek = tn.peek + const skip = tn.skip + const cmnt = tn.cmnt + + let head = true + let pkg + let imports + let weakImports + let syntax + let isProto3 = false + + let ptr = root + + const applyCase = options.keepCase ? function (name) { return name } : util.camelCase + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + const filename = parse.filename + if (!insideTryCatch) parse.filename = null + return Error('illegal ' + (name || 'token') + " '" + token + "' (" + (filename ? filename + ', ' : '') + 'line ' + tn.line + ')') + } + + function readString() { + const values = [] + let token + do { + /* istanbul ignore if */ + if ((token = next()) !== '"' && token !== "'") throw illegal(token) + + values.push(next()) + skip(token) + token = peek() + } while (token === '"' || token === "'") + return values.join('') + } + + function readValue(acceptTypeRef) { + const token = next() + switch (token) { + case "'": + case '"': + push(token) + return readString() + case 'true': case 'TRUE': + return true + case 'false': case 'FALSE': + return false } - if (!options) - options = parse.defaults; - - var tn = tokenize(source, options.alternateCommentMode || false), - next = tn.next, - push = tn.push, - peek = tn.peek, - skip = tn.skip, - cmnt = tn.cmnt; - - var head = true, - pkg, - imports, - weakImports, - syntax, - isProto3 = false; - - var ptr = root; - - var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; - - /* istanbul ignore next */ - function illegal(token, name, insideTryCatch) { - var filename = parse.filename; - if (!insideTryCatch) - parse.filename = null; - return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + try { + return parseNumber(token, /* insideTryCatch */ true) + } catch (e) { + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) return token + + /* istanbul ignore next */ + throw illegal(token, 'value') } - - function readString() { - var values = [], - token; - do { - /* istanbul ignore if */ - if ((token = next()) !== "\"" && token !== "'") - throw illegal(token); - - values.push(next()); - skip(token); - token = peek(); - } while (token === "\"" || token === "'"); - return values.join(""); + } + + function readRanges(target, acceptStrings) { + let token; let + start + do { + if (acceptStrings && ((token = peek()) === '"' || token === "'")) target.push(readString()) + else target.push([start = parseId(next()), skip('to', true) ? parseId(next()) : start]) + } while (skip(',', true)) + skip(';') + } + + function parseNumber(token, insideTryCatch) { + let sign = 1 + if (token.charAt(0) === '-') { + sign = -1 + token = token.substring(1) } - - function readValue(acceptTypeRef) { - var token = next(); - switch (token) { - case "'": - case "\"": - push(token); - return readString(); - case "true": case "TRUE": - return true; - case "false": case "FALSE": - return false; - } - try { - return parseNumber(token, /* insideTryCatch */ true); - } catch (e) { - - /* istanbul ignore else */ - if (acceptTypeRef && typeRefRe.test(token)) - return token; - - /* istanbul ignore next */ - throw illegal(token, "value"); - } + switch (token) { + case 'inf': case 'INF': case 'Inf': + return sign * Infinity + case 'nan': case 'NAN': case 'Nan': case 'NaN': + return NaN + case '0': + return 0 } + if (base10Re.test(token)) return sign * parseInt(token, 10) + if (base16Re.test(token)) return sign * parseInt(token, 16) + if (base8Re.test(token)) return sign * parseInt(token, 8) - function readRanges(target, acceptStrings) { - var token, start; - do { - if (acceptStrings && ((token = peek()) === "\"" || token === "'")) - target.push(readString()); - else - target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); - } while (skip(",", true)); - skip(";"); - } - - function parseNumber(token, insideTryCatch) { - var sign = 1; - if (token.charAt(0) === "-") { - sign = -1; - token = token.substring(1); - } - switch (token) { - case "inf": case "INF": case "Inf": - return sign * Infinity; - case "nan": case "NAN": case "Nan": case "NaN": - return NaN; - case "0": - return 0; - } - if (base10Re.test(token)) - return sign * parseInt(token, 10); - if (base16Re.test(token)) - return sign * parseInt(token, 16); - if (base8Re.test(token)) - return sign * parseInt(token, 8); - - /* istanbul ignore else */ - if (numberRe.test(token)) - return sign * parseFloat(token); + /* istanbul ignore else */ + if (numberRe.test(token)) return sign * parseFloat(token) - /* istanbul ignore next */ - throw illegal(token, "number", insideTryCatch); + /* istanbul ignore next */ + throw illegal(token, 'number', insideTryCatch) + } + + function parseId(token, acceptNegative) { + switch (token) { + case 'max': case 'MAX': case 'Max': + return 536870911 + case '0': + return 0 } - function parseId(token, acceptNegative) { - switch (token) { - case "max": case "MAX": case "Max": - return 536870911; - case "0": - return 0; - } + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === '-') throw illegal(token, 'id') - /* istanbul ignore if */ - if (!acceptNegative && token.charAt(0) === "-") - throw illegal(token, "id"); + if (base10NegRe.test(token)) return parseInt(token, 10) + if (base16NegRe.test(token)) return parseInt(token, 16) - if (base10NegRe.test(token)) - return parseInt(token, 10); - if (base16NegRe.test(token)) - return parseInt(token, 16); + /* istanbul ignore else */ + if (base8NegRe.test(token)) return parseInt(token, 8) - /* istanbul ignore else */ - if (base8NegRe.test(token)) - return parseInt(token, 8); - - /* istanbul ignore next */ - throw illegal(token, "id"); + /* istanbul ignore next */ + throw illegal(token, 'id') + } + + function parsePackage() { + /* istanbul ignore if */ + if (pkg !== undefined) throw illegal('package') + + pkg = next() + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) throw illegal(pkg, 'name') + + ptr = ptr.define(pkg) + skip(';') + } + + function parseImport() { + let token = peek() + let whichImports + switch (token) { + case 'weak': + whichImports = weakImports || (weakImports = []) + next() + break + case 'public': + next() + // eslint-disable-line no-fallthrough + default: + whichImports = imports || (imports = []) + break } - - function parsePackage() { - - /* istanbul ignore if */ - if (pkg !== undefined) - throw illegal("package"); - - pkg = next(); - - /* istanbul ignore if */ - if (!typeRefRe.test(pkg)) - throw illegal(pkg, "name"); - - ptr = ptr.define(pkg); - skip(";"); + token = readString() + skip(';') + whichImports.push(token) + } + + function parseSyntax() { + skip('=') + syntax = readString() + isProto3 = syntax === 'proto3' + + /* istanbul ignore if */ + if (!isProto3 && syntax !== 'proto2') throw illegal(syntax, 'syntax') + + skip(';') + } + + function parseCommon(parent, token) { + switch (token) { + case 'option': + parseOption(parent, token) + skip(';') + return true + + case 'message': + parseType(parent, token) + return true + + case 'enum': + parseEnum(parent, token) + return true + + case 'service': + parseService(parent, token) + return true + + case 'extend': + parseExtension(parent, token) + return true } - - function parseImport() { - var token = peek(); - var whichImports; - switch (token) { - case "weak": - whichImports = weakImports || (weakImports = []); - next(); - break; - case "public": - next(); - // eslint-disable-line no-fallthrough - default: - whichImports = imports || (imports = []); - break; - } - token = readString(); - skip(";"); - whichImports.push(token); + return false + } + + function ifBlock(obj, fnIf, fnElse) { + const trailingLine = tn.line + if (obj) { + obj.comment = cmnt() // try block-type comment + obj.filename = parse.filename } - - function parseSyntax() { - skip("="); - syntax = readString(); - isProto3 = syntax === "proto3"; - - /* istanbul ignore if */ - if (!isProto3 && syntax !== "proto2") - throw illegal(syntax, "syntax"); - - skip(";"); + if (skip('{', true)) { + let token + while ((token = next()) !== '}') fnIf(token) + skip(';', true) + } else { + if (fnElse) fnElse() + skip(';') + if (obj && typeof obj.comment !== 'string') obj.comment = cmnt(trailingLine) // try line-type comment if no block } - - function parseCommon(parent, token) { - switch (token) { - - case "option": - parseOption(parent, token); - skip(";"); - return true; - - case "message": - parseType(parent, token); - return true; - - case "enum": - parseEnum(parent, token); - return true; - - case "service": - parseService(parent, token); - return true; - - case "extend": - parseExtension(parent, token); - return true; - } - return false; + } + + function parseType(parent, token) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) throw illegal(token, 'type name') + + const type = new Type(token) + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) return + + switch (token) { + case 'map': + parseMapField(type, token) + break + + case 'required': + case 'optional': + case 'repeated': + parseField(type, token) + break + + case 'oneof': + parseOneOf(type, token) + break + + case 'extensions': + readRanges(type.extensions || (type.extensions = [])) + break + + case 'reserved': + readRanges(type.reserved || (type.reserved = []), true) + break + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) throw illegal(token) + + push(token) + parseField(type, 'optional') + break + } + }) + parent.add(type) + } + + function parseField(parent, rule, extend) { + const type = next() + if (type === 'group') { + parseGroup(parent, rule) + return } - function ifBlock(obj, fnIf, fnElse) { - var trailingLine = tn.line; - if (obj) { - obj.comment = cmnt(); // try block-type comment - obj.filename = parse.filename; - } - if (skip("{", true)) { - var token; - while ((token = next()) !== "}") - fnIf(token); - skip(";", true); - } else { - if (fnElse) - fnElse(); - skip(";"); - if (obj && typeof obj.comment !== "string") - obj.comment = cmnt(trailingLine); // try line-type comment if no block - } + /* istanbul ignore if */ + if (!typeRefRe.test(type)) throw illegal(type, 'type') + + let name = next() + + /* istanbul ignore if */ + if (!nameRe.test(name)) throw illegal(name, 'name') + + name = applyCase(name) + skip('=') + + const field = new Field(name, parseId(next()), type, rule, extend) + ifBlock(field, function parseField_block(token) { + /* istanbul ignore else */ + if (token === 'option') { + parseOption(field, token) + skip(';') + } else throw illegal(token) + }, function parseField_line() { + parseInlineOptions(field) + }) + parent.add(field) + + // JSON defaults to packed=true if not set so we have to set packed=false explicity when + // parsing proto2 descriptors without the option, where applicable. This must be done for + // all known packable types and anything that could be an enum (= is not a basic type). + if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined)) field.setOption('packed', false, /* ifNotSet */ true) + } + + function parseGroup(parent, rule) { + let name = next() + + /* istanbul ignore if */ + if (!nameRe.test(name)) throw illegal(name, 'name') + + const fieldName = util.lcFirst(name) + if (name === fieldName) name = util.ucFirst(name) + skip('=') + const id = parseId(next()) + const type = new Type(name) + type.group = true + const field = new Field(fieldName, id, name, rule) + field.filename = parse.filename + ifBlock(type, function parseGroup_block(token) { + switch (token) { + case 'option': + parseOption(type, token) + skip(';') + break + + case 'required': + case 'optional': + case 'repeated': + parseField(type, token) + break + + /* istanbul ignore next */ + default: + throw illegal(token) // there are no groups with proto3 semantics + } + }) + parent.add(type) + .add(field) + } + + function parseMapField(parent) { + skip('<') + const keyType = next() + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) throw illegal(keyType, 'type') + + skip(',') + const valueType = next() + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) throw illegal(valueType, 'type') + + skip('>') + const name = next() + + /* istanbul ignore if */ + if (!nameRe.test(name)) throw illegal(name, 'name') + + skip('=') + const field = new MapField(applyCase(name), parseId(next()), keyType, valueType) + ifBlock(field, function parseMapField_block(token) { + /* istanbul ignore else */ + if (token === 'option') { + parseOption(field, token) + skip(';') + } else throw illegal(token) + }, function parseMapField_line() { + parseInlineOptions(field) + }) + parent.add(field) + } + + function parseOneOf(parent, token) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) throw illegal(token, 'name') + + const oneof = new OneOf(applyCase(token)) + ifBlock(oneof, function parseOneOf_block(token) { + if (token === 'option') { + parseOption(oneof, token) + skip(';') + } else { + push(token) + parseField(oneof, 'optional') + } + }) + parent.add(oneof) + } + + function parseEnum(parent, token) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) throw illegal(token, 'name') + + const enm = new Enum(token) + ifBlock(enm, function parseEnum_block(token) { + switch (token) { + case 'option': + parseOption(enm, token) + skip(';') + break + + case 'reserved': + readRanges(enm.reserved || (enm.reserved = []), true) + break + + default: + parseEnumValue(enm, token) + } + }) + parent.add(enm) + } + + function parseEnumValue(parent, token) { + /* istanbul ignore if */ + if (!nameRe.test(token)) throw illegal(token, 'name') + + skip('=') + const value = parseId(next(), true) + const dummy = {} + ifBlock(dummy, function parseEnumValue_block(token) { + /* istanbul ignore else */ + if (token === 'option') { + parseOption(dummy, token) // skip + skip(';') + } else throw illegal(token) + }, function parseEnumValue_line() { + parseInlineOptions(dummy) // skip + }) + parent.add(token, value, dummy.comment) + } + + function parseOption(parent, token) { + const isCustom = skip('(', true) + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) throw illegal(token, 'name') + + let name = token + if (isCustom) { + skip(')') + name = '(' + name + ')' + token = peek() + if (fqTypeRefRe.test(token)) { + name += token + next() + } } + skip('=') + parseOptionValue(parent, name) + } - function parseType(parent, token) { - + function parseOptionValue(parent, name) { + if (skip('{', true)) { // { a: "foo" b { c: "bar" } } + do { /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "type name"); - - var type = new Type(token); - ifBlock(type, function parseType_block(token) { - if (parseCommon(type, token)) - return; - - switch (token) { - - case "map": - parseMapField(type, token); - break; - - case "required": - case "optional": - case "repeated": - parseField(type, token); - break; - - case "oneof": - parseOneOf(type, token); - break; - - case "extensions": - readRanges(type.extensions || (type.extensions = [])); - break; - - case "reserved": - readRanges(type.reserved || (type.reserved = []), true); - break; - - default: - /* istanbul ignore if */ - if (!isProto3 || !typeRefRe.test(token)) - throw illegal(token); - - push(token); - parseField(type, "optional"); - break; - } - }); - parent.add(type); - } + if (!nameRe.test(token = next())) throw illegal(token, 'name') - function parseField(parent, rule, extend) { - var type = next(); - if (type === "group") { - parseGroup(parent, rule); - return; + if (peek() === '{') parseOptionValue(parent, name + '.' + token) + else { + skip(':') + if (peek() === '{') parseOptionValue(parent, name + '.' + token) + else setOption(parent, name + '.' + token, readValue(true)) } - - /* istanbul ignore if */ - if (!typeRefRe.test(type)) - throw illegal(type, "type"); - - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - name = applyCase(name); - skip("="); - - var field = new Field(name, parseId(next()), type, rule, extend); - ifBlock(field, function parseField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseField_line() { - parseInlineOptions(field); - }); - parent.add(field); - - // JSON defaults to packed=true if not set so we have to set packed=false explicity when - // parsing proto2 descriptors without the option, where applicable. This must be done for - // all known packable types and anything that could be an enum (= is not a basic type). - if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined)) - field.setOption("packed", false, /* ifNotSet */ true); - } - - function parseGroup(parent, rule) { - var name = next(); - - /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - var fieldName = util.lcFirst(name); - if (name === fieldName) - name = util.ucFirst(name); - skip("="); - var id = parseId(next()); - var type = new Type(name); - type.group = true; - var field = new Field(fieldName, id, name, rule); - field.filename = parse.filename; - ifBlock(type, function parseGroup_block(token) { - switch (token) { - - case "option": - parseOption(type, token); - skip(";"); - break; - - case "required": - case "optional": - case "repeated": - parseField(type, token); - break; - - /* istanbul ignore next */ - default: - throw illegal(token); // there are no groups with proto3 semantics - } - }); - parent.add(type) - .add(field); + } while (!skip('}', true)) + } else setOption(parent, name, readValue(true)) + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (parent.setOption) parent.setOption(name, value) + } + + function parseInlineOptions(parent) { + if (skip('[', true)) { + do { + parseOption(parent, 'option') + } while (skip(',', true)) + skip(']') } - - function parseMapField(parent) { - skip("<"); - var keyType = next(); + return parent + } + + function parseService(parent, token) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) throw illegal(token, 'service name') + + const service = new Service(token) + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) return + + /* istanbul ignore else */ + if (token === 'rpc') parseMethod(service, token) + else throw illegal(token) + }) + parent.add(service) + } + + function parseMethod(parent, token) { + const type = token + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) throw illegal(token, 'name') + + const name = token + let requestType; let requestStream + let responseType; let + responseStream + + skip('(') + if (skip('stream', true)) requestStream = true + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) throw illegal(token) + + requestType = token + skip(')'); skip('returns'); skip('(') + if (skip('stream', true)) responseStream = true + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) throw illegal(token) + + responseType = token + skip(')') + + const method = new Method(name, type, requestType, responseType, requestStream, responseStream) + ifBlock(method, function parseMethod_block(token) { + /* istanbul ignore else */ + if (token === 'option') { + parseOption(method, token) + skip(';') + } else throw illegal(token) + }) + parent.add(method) + } + + function parseExtension(parent, token) { + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) throw illegal(token, 'reference') + + const reference = token + ifBlock(null, function parseExtension_block(token) { + switch (token) { + case 'required': + case 'repeated': + case 'optional': + parseField(parent, token, reference) + break + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) throw illegal(token) + push(token) + parseField(parent, 'optional', reference) + break + } + }) + } + + let token + while ((token = next()) !== null) { + switch (token) { + case 'package': /* istanbul ignore if */ - if (types.mapKey[keyType] === undefined) - throw illegal(keyType, "type"); - - skip(","); - var valueType = next(); + if (!head) throw illegal(token) - /* istanbul ignore if */ - if (!typeRefRe.test(valueType)) - throw illegal(valueType, "type"); + parsePackage() + break - skip(">"); - var name = next(); + case 'import': /* istanbul ignore if */ - if (!nameRe.test(name)) - throw illegal(name, "name"); - - skip("="); - var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); - ifBlock(field, function parseMapField_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(field, token); - skip(";"); - } else - throw illegal(token); - - }, function parseMapField_line() { - parseInlineOptions(field); - }); - parent.add(field); - } + if (!head) throw illegal(token) - function parseOneOf(parent, token) { + parseImport() + break - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var oneof = new OneOf(applyCase(token)); - ifBlock(oneof, function parseOneOf_block(token) { - if (token === "option") { - parseOption(oneof, token); - skip(";"); - } else { - push(token); - parseField(oneof, "optional"); - } - }); - parent.add(oneof); - } - - function parseEnum(parent, token) { + case 'syntax': /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var enm = new Enum(token); - ifBlock(enm, function parseEnum_block(token) { - switch(token) { - case "option": - parseOption(enm, token); - skip(";"); - break; - - case "reserved": - readRanges(enm.reserved || (enm.reserved = []), true); - break; - - default: - parseEnumValue(enm, token); - } - }); - parent.add(enm); - } + if (!head) throw illegal(token) - function parseEnumValue(parent, token) { + parseSyntax() + break - /* istanbul ignore if */ - if (!nameRe.test(token)) - throw illegal(token, "name"); - - skip("="); - var value = parseId(next(), true), - dummy = {}; - ifBlock(dummy, function parseEnumValue_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(dummy, token); // skip - skip(";"); - } else - throw illegal(token); - - }, function parseEnumValue_line() { - parseInlineOptions(dummy); // skip - }); - parent.add(token, value, dummy.comment); - } - - function parseOption(parent, token) { - var isCustom = skip("(", true); + case 'option': /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token, "name"); - - var name = token; - if (isCustom) { - skip(")"); - name = "(" + name + ")"; - token = peek(); - if (fqTypeRefRe.test(token)) { - name += token; - next(); - } - } - skip("="); - parseOptionValue(parent, name); - } + if (!head) throw illegal(token) - function parseOptionValue(parent, name) { - if (skip("{", true)) { // { a: "foo" b { c: "bar" } } - do { - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - if (peek() === "{") - parseOptionValue(parent, name + "." + token); - else { - skip(":"); - if (peek() === "{") - parseOptionValue(parent, name + "." + token); - else - setOption(parent, name + "." + token, readValue(true)); - } - } while (!skip("}", true)); - } else - setOption(parent, name, readValue(true)); - // Does not enforce a delimiter to be universal - } + parseOption(ptr, token) + skip(';') + break - function setOption(parent, name, value) { - if (parent.setOption) - parent.setOption(name, value); - } + default: - function parseInlineOptions(parent) { - if (skip("[", true)) { - do { - parseOption(parent, "option"); - } while (skip(",", true)); - skip("]"); + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false + continue } - return parent; - } - - function parseService(parent, token) { - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "service name"); - - var service = new Service(token); - ifBlock(service, function parseService_block(token) { - if (parseCommon(service, token)) - return; - - /* istanbul ignore else */ - if (token === "rpc") - parseMethod(service, token); - else - throw illegal(token); - }); - parent.add(service); - } - function parseMethod(parent, token) { - var type = token; - - /* istanbul ignore if */ - if (!nameRe.test(token = next())) - throw illegal(token, "name"); - - var name = token, - requestType, requestStream, - responseType, responseStream; - - skip("("); - if (skip("stream", true)) - requestStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - requestType = token; - skip(")"); skip("returns"); skip("("); - if (skip("stream", true)) - responseStream = true; - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token); - - responseType = token; - skip(")"); - - var method = new Method(name, type, requestType, responseType, requestStream, responseStream); - ifBlock(method, function parseMethod_block(token) { - - /* istanbul ignore else */ - if (token === "option") { - parseOption(method, token); - skip(";"); - } else - throw illegal(token); - - }); - parent.add(method); - } - - function parseExtension(parent, token) { - - /* istanbul ignore if */ - if (!typeRefRe.test(token = next())) - throw illegal(token, "reference"); - - var reference = token; - ifBlock(null, function parseExtension_block(token) { - switch (token) { - - case "required": - case "repeated": - case "optional": - parseField(parent, token, reference); - break; - - default: - /* istanbul ignore if */ - if (!isProto3 || !typeRefRe.test(token)) - throw illegal(token); - push(token); - parseField(parent, "optional", reference); - break; - } - }); - } - - var token; - while ((token = next()) !== null) { - switch (token) { - - case "package": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parsePackage(); - break; - - case "import": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseImport(); - break; - - case "syntax": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseSyntax(); - break; - - case "option": - - /* istanbul ignore if */ - if (!head) - throw illegal(token); - - parseOption(ptr, token); - skip(";"); - break; - - default: - - /* istanbul ignore else */ - if (parseCommon(ptr, token)) { - head = false; - continue; - } - - /* istanbul ignore next */ - throw illegal(token); - } + /* istanbul ignore next */ + throw illegal(token) } - - parse.filename = null; - return { - "package" : pkg, - "imports" : imports, - weakImports : weakImports, - syntax : syntax, - root : root - }; + } + + parse.filename = null + return { + package: pkg, + imports, + weakImports, + syntax, + root + } } /** @@ -755,16 +675,16 @@ function parse(source, root, options) { * @property {IParseOptions} defaults Default {@link IParseOptions} * @variation 2 */ -parse._configure = function (){ - tokenize = require("./tokenize"), - Root = require("./root"), - Type = require("./type"), - Field = require("./field"), - MapField = require("./mapField"), - OneOf = require("./oneof"), - Enum = require("./enum"), - Service = require("./service"), - Method = require("./method"), - types = require("./types"), - util = require("./util"); -} \ No newline at end of file +parse._configure = function () { + tokenize = require('./tokenize'), + Root = require('./root'), + Type = require('./type'), + Field = require('./field'), + MapField = require('./mapField'), + OneOf = require('./oneof'), + Enum = require('./enum'), + Service = require('./service'), + Method = require('./method'), + types = require('./types'), + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/path.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/path.js index 9864a0ea..fe48f0dd 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/path.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/path.js @@ -1,44 +1,38 @@ -var path = module.exports; +const path = module.exports -var isAbsolute = +const isAbsolute = /** * Tests if the specified path is absolute. * @param {string} path Path to test * @returns {boolean} `true` if path is absolute */ path.isAbsolute = function isAbsolute(path) { - return /^(?:\/|\w+:)/.test(path); - }; + return /^(?:\/|\w+:)/.test(path) + } -var normalize = +const normalize = /** * Normalizes the specified path. * @param {string} path Path to normalize * @returns {string} Normalized path */ path.normalize = function normalize(path) { - path = path.replace(/\\/g, "/") - .replace(/\/{2,}/g, "/"); - var parts = path.split("/"), - absolute = isAbsolute(path), - prefix = ""; - if (absolute) - prefix = parts.shift() + "/"; - for (var i = 0; i < parts.length;) { - if (parts[i] === "..") { - if (i > 0 && parts[i - 1] !== "..") - parts.splice(--i, 2); - else if (absolute) - parts.splice(i, 1); - else - ++i; - } else if (parts[i] === ".") - parts.splice(i, 1); - else - ++i; - } - return prefix + parts.join("/"); - }; + path = path.replace(/\\/g, '/') + .replace(/\/{2,}/g, '/') + const parts = path.split('/') + const absolute = isAbsolute(path) + let prefix = '' + if (absolute) prefix = parts.shift() + '/' + for (let i = 0; i < parts.length;) { + if (parts[i] === '..') { + if (i > 0 && parts[i - 1] !== '..') parts.splice(--i, 2) + else if (absolute) parts.splice(i, 1) + else ++i + } else if (parts[i] === '.') parts.splice(i, 1) + else ++i + } + return prefix + parts.join('/') + } /** * Resolves the specified include path against the specified origin path. @@ -48,11 +42,8 @@ var normalize = * @returns {string} Path to the include file */ path.resolve = function resolve(originPath, includePath, alreadyNormalized) { - if (!alreadyNormalized) - includePath = normalize(includePath); - if (isAbsolute(includePath)) - return includePath; - if (!alreadyNormalized) - originPath = normalize(originPath); - return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; -}; + if (!alreadyNormalized) includePath = normalize(includePath) + if (isAbsolute(includePath)) return includePath + if (!alreadyNormalized) originPath = normalize(originPath) + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, '')).length ? normalize(originPath + '/' + includePath) : includePath +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/pool.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/pool.js index f9168270..9f10d6be 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/pool.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/pool.js @@ -1,4 +1,4 @@ -module.exports = pool; +module.exports = pool /** * An allocator as used by {@link util.pool}. @@ -28,20 +28,19 @@ module.exports = pool; * @returns {PoolAllocator} Pooled allocator */ function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size) { - if (size < 1 || size > MAX) - return alloc(size); - if (offset + size > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size); - if (offset & 7) // align to 32 bit - offset = (offset | 7) + 1; - return buf; - }; -} \ No newline at end of file + const SIZE = size || 8192 + const MAX = SIZE >>> 1 + let slab = null + let offset = SIZE + return function pool_alloc(size) { + if (size < 1 || size > MAX) return alloc(size) + if (offset + size > SIZE) { + slab = alloc(SIZE) + offset = 0 + } + const buf = slice.call(slab, offset, offset += size) + if (offset & 7) // align to 32 bit + { offset = (offset | 7) + 1 } + return buf + } +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/reader.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/reader.js index 6dd93b86..21eda96d 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/reader.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/reader.js @@ -2,313 +2,281 @@ * Created by zhangmiao on 2018/3/13. */ -module.exports = Reader; +module.exports = Reader -var util = require('./util'); +const util = require('./util') -var LongBits; -var utf8; +let LongBits +let utf8 -var BufferReader; +let BufferReader function indexOutOfRange(reader, writeLength) { - return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); + return RangeError('index out of range: ' + reader.pos + ' + ' + (writeLength || 1) + ' > ' + reader.len) } - function Reader(buffer) { - - /** + /** * Read buffer. * @type {Uint8Array} */ - this.buf = buffer; + this.buf = buffer - /** + /** * Read buffer position. * @type {number} */ - this.pos = 0; + this.pos = 0 - /** + /** * Read buffer length. * @type {number} */ - this.len = buffer.length; + this.len = buffer.length } -var create_array = typeof Uint8Array !== "undefined" - ? function create_typed_array(buffer) { - if (buffer instanceof Uint8Array || Array.isArray(buffer)) - return new Reader(buffer); - if (typeof ArrayBuffer !== "undefined" && buffer instanceof ArrayBuffer) //增加ArrayBuffer构建 - return new Reader(new Uint8Array(buffer)); - throw Error("illegal buffer"); -} - /* istanbul ignore next */ - : function create_array(buffer) { - if (Array.isArray(buffer)) - return new Reader(buffer); - throw Error("illegal buffer"); -}; +const create_array = typeof Uint8Array !== 'undefined' + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) return new Reader(buffer) + if (typeof ArrayBuffer !== 'undefined' && buffer instanceof ArrayBuffer) // 增加ArrayBuffer构建 + { return new Reader(new Uint8Array(buffer)) } + throw Error('illegal buffer') + } +/* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) return new Reader(buffer) + throw Error('illegal buffer') + } Reader.create = util.Buffer - ? function create_buffer_setup(buffer) { + ? function create_buffer_setup(buffer) { return (Reader.create = function create_buffer(buffer) { - return util.Buffer.isBuffer(buffer) - ? new BufferReader(buffer) - /* istanbul ignore next */ - : create_array(buffer); - })(buffer); -} - /* istanbul ignore next */ - : create_array; - -Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer) + })(buffer) + } +/* istanbul ignore next */ + : create_array +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice Reader.prototype.uint32 = (function read_uint32_setup() { - var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) - return function read_uint32() { - value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; - value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; - - /* istanbul ignore if */ - if ((this.pos += 5) > this.len) { - this.pos = this.len; - throw indexOutOfRange(this, 10); - } - return value; - }; -})(); + let value = 4294967295 // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = (this.buf[this.pos] & 127) >>> 0; if (this.buf[this.pos++] < 128) return value + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len + throw indexOutOfRange(this, 10) + } + return value + } +}()) Reader.prototype.int32 = function read_int32() { - return this.uint32() | 0; -}; + return this.uint32() | 0 +} Reader.prototype.sint32 = function read_sint32() { - var value = this.uint32(); - return value >>> 1 ^ -(value & 1) | 0; -}; + const value = this.uint32() + return value >>> 1 ^ -(value & 1) | 0 +} function readLongVarint() { - // tends to deopt with local vars for octet etc. - var bits = new LongBits(0, 0); - var i = 0; - if (this.len - this.pos > 4) { // fast route (lo) - for (; i < 4; ++i) { - // 1st..4th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 5th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; - bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - i = 0; - } else { - for (; i < 3; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 1st..3th - bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - // 4th - bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; - return bits; + // tends to deopt with local vars for octet etc. + const bits = new LongBits(0, 0) + let i = 0 + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0 + if (this.buf[this.pos++] < 128) return bits + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0 + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0 + if (this.buf[this.pos++] < 128) return bits + i = 0 + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) throw indexOutOfRange(this) + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0 + if (this.buf[this.pos++] < 128) return bits } - if (this.len - this.pos > 4) { // fast route (hi) - for (; i < 5; ++i) { - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } - } else { - for (; i < 5; ++i) { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - // 6th..10th - bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; - if (this.buf[this.pos++] < 128) - return bits; - } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0 + return bits + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0 + if (this.buf[this.pos++] < 128) return bits } - /* istanbul ignore next */ - throw Error("invalid varint encoding"); + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) throw indexOutOfRange(this) + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0 + if (this.buf[this.pos++] < 128) return bits + } + } + /* istanbul ignore next */ + throw Error('invalid varint encoding') } Reader.prototype.bool = function read_bool() { - return this.uint32() !== 0; -}; - + return this.uint32() !== 0 +} function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` - return (buf[end - 4] - | buf[end - 3] << 8 - | buf[end - 2] << 16 - | buf[end - 1] << 24) >>> 0; + return (buf[end - 4] | + buf[end - 3] << 8 | + buf[end - 2] << 16 | + buf[end - 1] << 24) >>> 0 } Reader.prototype.fixed32 = function read_fixed32() { + /* istanbul ignore if */ + if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4) - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4); -}; + return readFixed32_end(this.buf, this.pos += 4) +} Reader.prototype.sfixed32 = function read_sfixed32() { + /* istanbul ignore if */ + if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4) - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - return readFixed32_end(this.buf, this.pos += 4) | 0; -}; + return readFixed32_end(this.buf, this.pos += 4) | 0 +} /* eslint-disable no-invalid-this */ function readFixed64(/* this: Reader */) { + /* istanbul ignore if */ + if (this.pos + 8 > this.len) throw indexOutOfRange(this, 8) - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 8); - - return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)) } - Reader.prototype.float = function read_float() { + /* istanbul ignore if */ + if (this.pos + 4 > this.len) throw indexOutOfRange(this, 4) - /* istanbul ignore if */ - if (this.pos + 4 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readFloatLE(this.buf, this.pos); - this.pos += 4; - return value; -}; + const value = util.float.readFloatLE(this.buf, this.pos) + this.pos += 4 + return value +} Reader.prototype.double = function read_double() { + /* istanbul ignore if */ + if (this.pos + 8 > this.len) throw indexOutOfRange(this, 4) - /* istanbul ignore if */ - if (this.pos + 8 > this.len) - throw indexOutOfRange(this, 4); - - var value = util.float.readDoubleLE(this.buf, this.pos); - this.pos += 8; - return value; -}; + const value = util.float.readDoubleLE(this.buf, this.pos) + this.pos += 8 + return value +} Reader.prototype.bytes = function read_bytes() { - var length = this.uint32(), - start = this.pos, - end = this.pos + length; - - /* istanbul ignore if */ - if (end > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - if (Array.isArray(this.buf)) // plain array - return this.buf.slice(start, end); - return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1 - ? new this.buf.constructor(0) - : this._slice.call(this.buf, start, end); -}; + const length = this.uint32() + const start = this.pos + const end = this.pos + length + + /* istanbul ignore if */ + if (end > this.len) throw indexOutOfRange(this, length) + this.pos += length + if (Array.isArray(this.buf)) // plain array + { return this.buf.slice(start, end) } + return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1 + ? new this.buf.constructor(0) + : this._slice.call(this.buf, start, end) +} Reader.prototype.string = function read_string() { - var bytes = this.bytes(); - return utf8.read(bytes, 0, bytes.length); -}; + const bytes = this.bytes() + return utf8.read(bytes, 0, bytes.length) +} Reader.prototype.skip = function skip(length) { - if (typeof length === "number") { - /* istanbul ignore if */ - if (this.pos + length > this.len) - throw indexOutOfRange(this, length); - this.pos += length; - } else { - do { - /* istanbul ignore if */ - if (this.pos >= this.len) - throw indexOutOfRange(this); - } while (this.buf[this.pos++] & 128); - } - return this; -}; - -Reader.prototype.skipType = function(wireType) { - switch (wireType) { - case 0: - this.skip(); - break; - case 1: - this.skip(8); - break; - case 2: - this.skip(this.uint32()); - break; - case 3: - do { // eslint-disable-line no-constant-condition - if ((wireType = this.uint32() & 7) === 4) - break; - this.skipType(wireType); - } while (true); - break; - case 5: - this.skip(4); - break; - - /* istanbul ignore next */ - default: - throw Error("invalid wire type " + wireType + " at offset " + this.pos); - } - return this; -}; - - - -//这部分可能用不到 -Reader._configure = function() { + if (typeof length === 'number') { + /* istanbul ignore if */ + if (this.pos + length > this.len) throw indexOutOfRange(this, length) + this.pos += length + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) throw indexOutOfRange(this) + } while (this.buf[this.pos++] & 128) + } + return this +} - //util = require('./util'); - LongBits = require("./longBits"); - utf8 = require("./utf8"); +Reader.prototype.skipType = function (wireType) { + switch (wireType) { + case 0: + this.skip() + break + case 1: + this.skip(8) + break + case 2: + this.skip(this.uint32()) + break + case 3: + do { // eslint-disable-line no-constant-condition + if ((wireType = this.uint32() & 7) === 4) break + this.skipType(wireType) + } while (true) + break + case 5: + this.skip(4) + break + + /* istanbul ignore next */ + default: + throw Error('invalid wire type ' + wireType + ' at offset ' + this.pos) + } + return this +} - var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; - util.merge(Reader.prototype, { +// 这部分可能用不到 +Reader._configure = function () { + // util = require('./util'); + LongBits = require('./longBits') + utf8 = require('./utf8') - int64: function read_int64() { - return readLongVarint.call(this)[fn](false); - }, + const fn = util.Long ? 'toLong' : /* istanbul ignore next */ 'toNumber' + util.merge(Reader.prototype, { - uint64: function read_uint64() { - return readLongVarint.call(this)[fn](true); - }, + int64: function read_int64() { + return readLongVarint.call(this)[fn](false) + }, - sint64: function read_sint64() { - return readLongVarint.call(this).zzDecode()[fn](false); - }, + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true) + }, - fixed64: function read_fixed64() { - return readFixed64.call(this)[fn](true); - }, + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false) + }, - sfixed64: function read_sfixed64() { - return readFixed64.call(this)[fn](false); - } + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true) + }, - }); -}; + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false) + } + }) +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/root.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/root.js index ecf69d4a..98016d3b 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/root.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/root.js @@ -1,17 +1,18 @@ -module.exports = Root; +module.exports = Root // extends Namespace -var Namespace = require("./namespace"); -((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; +const Namespace = require('./namespace'); -var Field = require("./field"), - Enum = require("./enum"), - OneOf = require("./oneof"), - util = require("./util"); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = 'Root' -var Type, // cyclic - parse, // might be excluded - common; // " +let Field = require('./field') +let Enum = require('./enum') +let OneOf = require('./oneof') +let util = require('./util') + +let Type // cyclic +let parse // might be excluded +let common // " /** * Constructs a new root namespace instance. @@ -21,25 +22,25 @@ var Type, // cyclic * @param {Object.} [options] Top level options */ function Root(options) { - Namespace.call(this, "", options); + Namespace.call(this, '', options) - /** + /** * Deferred extension fields. * @type {Field[]} */ - this.deferred = []; + this.deferred = [] - /** + /** * Resolved file names of loaded files. * @type {string[]} */ - this.files = []; + this.files = [] - /** + /** * Resolved name of parsered pbString. * @type {string[]} */ - this.names = []; + this.names = [] } /** @@ -49,13 +50,11 @@ function Root(options) { * @returns {Root} Root namespace */ Root.fromJSON = function fromJSON(json, root) { - json = typeof json === 'string' ? JSON.parse(json) : json; - if (!root) - root = new Root(); - if (json.options) - root.setOptions(json.options); - return root.addJSON(json.nested); -}; + json = typeof json === 'string' ? JSON.parse(json) : json + if (!root) root = new Root() + if (json.options) root.setOptions(json.options) + return root.addJSON(json.nested) +} /** * Resolves the path of an imported file, relative to the importing origin. @@ -65,89 +64,83 @@ Root.fromJSON = function fromJSON(json, root) { * @param {string} target The file name being imported * @returns {string|null} Resolved path to `target` or `null` to skip the file */ -Root.prototype.resolvePath = util.path.resolve; +Root.prototype.resolvePath = util.path.resolve // A symbol-like function to safely signal synchronous loading /* istanbul ignore next */ function SYNC() {} // eslint-disable-line no-empty-function -function parseFromPbString(pbString, options, callback){ - - if (typeof options === "function") { - callback = options; - options = undefined; - } - var self = this; - if (!callback){ - return util.asPromise(parseFromPbString, self, pbString, options); - } - - var pbObj = null; - if(typeof pbString === 'string'){ - pbObj = JSON.parse(pbString); - }else if(typeof pbString === 'object'){ - pbObj = pbString; - }else { - //throw Error("pb格式转化失败"); - console.log("pb格式转化失败"); - return undefined; - } - - var name = pbObj['name']; - var pbJsonStr = pbObj['pbJsonStr']; - - function finish(err, root){ - if(!callback) - return; - var cb = callback; - callback = null; - cb(err, root); - } - - function process(name, source){ - try { - if (util.isString(source) && source.charAt(0) === "{") - source = JSON.parse(source); - if (!util.isString(source)) - self.setOptions(source.options).addJSON(source.nested); - else { - parse.filename = name; - var parsed = parse(source, self, options), - resolved; - var i = 0; - if(parsed.imports){ - for (; i < parsed.imports.length; ++i){ - resolved = parsed.imports[i]; - fetch(resolved); - } - } - if (parsed.weakImports){ - for (i = 0; i < parsed.weakImports.length; ++i) - resolved = parsed.weakImports[i]; - fetch(resolved, true); - } - } - } catch (err) { - finish(err); +function parseFromPbString(pbString, options, callback) { + if (typeof options === 'function') { + callback = options + options = undefined + } + const self = this + if (!callback) { + return util.asPromise(parseFromPbString, self, pbString, options) + } + + let pbObj = null + if (typeof pbString === 'string') { + pbObj = JSON.parse(pbString) + } else if (typeof pbString === 'object') { + pbObj = pbString + } else { + // throw Error("pb格式转化失败"); + console.log('pb格式转化失败') + return undefined + } + + const name = pbObj.name + const pbJsonStr = pbObj.pbJsonStr + + function finish(err, root) { + if (!callback) return + const cb = callback + callback = null + cb(err, root) + } + + function process(name, source) { + try { + if (util.isString(source) && source.charAt(0) === '{') source = JSON.parse(source) + if (!util.isString(source)) self.setOptions(source.options).addJSON(source.nested) + else { + parse.filename = name + const parsed = parse(source, self, options) + let resolved + let i = 0 + if (parsed.imports) { + for (; i < parsed.imports.length; ++i) { + resolved = parsed.imports[i] + fetch(resolved) + } } - - finish(null, self); // only once anyway + if (parsed.weakImports) { + for (i = 0; i < parsed.weakImports.length; ++i) resolved = parsed.weakImports[i] + fetch(resolved, true) + } + } + } catch (err) { + finish(err) } - function fetch(name){ - if(self.names.indexOf(name)>-1) - return; - self.names.push(name); - if (name in common){ - process(name, common[name]); - } + finish(null, self) // only once anyway + } + + function fetch(name) { + if (self.names.indexOf(name) > -1) return + self.names.push(name) + if (name in common) { + process(name, common[name]) } + } - process(name, pbJsonStr); - return undefined; + process(name, pbJsonStr) + return undefined } -Root.prototype.parseFromPbString = parseFromPbString; +Root.prototype.parseFromPbString = parseFromPbString /** * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. @@ -157,132 +150,108 @@ Root.prototype.parseFromPbString = parseFromPbString; * @returns {undefined} */ Root.prototype.load = function load(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = undefined; + if (typeof options === 'function') { + callback = options + options = undefined + } + const self = this + if (!callback) return util.asPromise(load, self, filename, options) + + const sync = callback === SYNC // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) return + const cb = callback + callback = null + if (sync) throw err + cb(err, root) + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === '{') source = JSON.parse(source) + if (!util.isString(source)) self.setOptions(source.options).addJSON(source.nested) + else { + parse.filename = filename + const parsed = parse(source, self, options) + let resolved + let i = 0 + if (parsed.imports) for (; i < parsed.imports.length; ++i) if (resolved = self.resolvePath(filename, parsed.imports[i])) fetch(resolved) + if (parsed.weakImports) for (i = 0; i < parsed.weakImports.length; ++i) if (resolved = self.resolvePath(filename, parsed.weakImports[i])) fetch(resolved, true) + } + } catch (err) { + finish(err) } - var self = this; - if (!callback) - return util.asPromise(load, self, filename, options); - - var sync = callback === SYNC; // undocumented - - // Finishes loading by calling the callback (exactly once) - function finish(err, root) { - /* istanbul ignore if */ - if (!callback) - return; - var cb = callback; - callback = null; - if (sync) - throw err; - cb(err, root); + if (!sync && !queued) finish(null, self) // only once anyway + } + + // Fetches a single file + function fetch(filename, weak) { + // Strip path if this file references a bundled definition + const idx = filename.lastIndexOf('google/protobuf/') + if (idx > -1) { + const altname = filename.substring(idx) + if (altname in common) filename = altname } - // Processes a single file - function process(filename, source) { - try { - if (util.isString(source) && source.charAt(0) === "{") - source = JSON.parse(source); - if (!util.isString(source)) - self.setOptions(source.options).addJSON(source.nested); - else { - parse.filename = filename; - var parsed = parse(source, self, options), - resolved, - i = 0; - if (parsed.imports) - for (; i < parsed.imports.length; ++i) - if (resolved = self.resolvePath(filename, parsed.imports[i])) - fetch(resolved); - if (parsed.weakImports) - for (i = 0; i < parsed.weakImports.length; ++i) - if (resolved = self.resolvePath(filename, parsed.weakImports[i])) - fetch(resolved, true); - } - } catch (err) { - finish(err); - } - if (!sync && !queued) - finish(null, self); // only once anyway + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) return + self.files.push(filename) + + // Shortcut bundled definitions + if (filename in common) { + if (sync) process(filename, common[filename]) + else { + ++queued + setTimeout(function () { + --queued + process(filename, common[filename]) + }) + } + return } - // Fetches a single file - function fetch(filename, weak) { - - // Strip path if this file references a bundled definition - var idx = filename.lastIndexOf("google/protobuf/"); - if (idx > -1) { - var altname = filename.substring(idx); - if (altname in common) - filename = altname; + // Otherwise fetch from disk or network + if (sync) { + let source + try { + source = util.fs.readFileSync(filename).toString('utf8') + } catch (err) { + if (!weak) finish(err) + return + } + process(filename, source) + } else { + ++queued + util.fetch(filename, function (err, source) { + --queued + /* istanbul ignore if */ + if (!callback) return // terminated meanwhile + if (err) { + /* istanbul ignore else */ + if (!weak) finish(err) + else if (!queued) // can't be covered reliably + { finish(null, self) } + return } + process(filename, source) + }) + } + } + var queued = 0 - // Skip if already loaded / attempted - if (self.files.indexOf(filename) > -1) - return; - self.files.push(filename); - - // Shortcut bundled definitions - if (filename in common) { - if (sync) - process(filename, common[filename]); - else { - ++queued; - setTimeout(function() { - --queued; - process(filename, common[filename]); - }); - } - return; - } + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) filename = [filename] + for (var i = 0, resolved; i < filename.length; ++i) if (resolved = self.resolvePath('', filename[i])) fetch(resolved) - // Otherwise fetch from disk or network - if (sync) { - var source; - try { - source = util.fs.readFileSync(filename).toString("utf8"); - } catch (err) { - if (!weak) - finish(err); - return; - } - process(filename, source); - } else { - ++queued; - util.fetch(filename, function(err, source) { - --queued; - /* istanbul ignore if */ - if (!callback) - return; // terminated meanwhile - if (err) { - /* istanbul ignore else */ - if (!weak) - finish(err); - else if (!queued) // can't be covered reliably - finish(null, self); - return; - } - process(filename, source); - }); - } - } - var queued = 0; - - // Assembling the root namespace doesn't require working type - // references anymore, so we can load everything in parallel - if (util.isString(filename)) - filename = [ filename ]; - for (var i = 0, resolved; i < filename.length; ++i) - if (resolved = self.resolvePath("", filename[i])) - fetch(resolved); - - if (sync) - return self; - if (!queued) - finish(null, self); - return undefined; -}; + if (sync) return self + if (!queued) finish(null, self) + return undefined +} // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined /** @@ -314,24 +283,24 @@ Root.prototype.load = function load(filename, options, callback) { * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid */ Root.prototype.loadSync = function loadSync(filename, options) { - if (!util.isNode) - throw Error("not supported"); - return this.load(filename, options, SYNC); -}; + if (!util.isNode) throw Error('not supported') + return this.load(filename, options, SYNC) +} /** * @override */ Root.prototype.resolveAll = function resolveAll() { - if (this.deferred.length) - throw Error("unresolvable extensions: " + this.deferred.map(function(field) { - return "'extend " + field.extend + "' in " + field.parent.fullName; - }).join(", ")); - return Namespace.prototype.resolveAll.call(this); -}; + if (this.deferred.length) { + throw Error('unresolvable extensions: ' + this.deferred.map(function (field) { + return "'extend " + field.extend + "' in " + field.parent.fullName + }).join(', ')) + } + return Namespace.prototype.resolveAll.call(this) +} // only uppercased (and thus conflict-free) children are exposed, see below -var exposeRe = /^[A-Z]/; +const exposeRe = /^[A-Z]/ /** * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. @@ -342,15 +311,15 @@ var exposeRe = /^[A-Z]/; * @ignore */ function tryHandleExtension(root, field) { - var extendedType = field.parent.lookup(field.extend); - if (extendedType) { - var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); - sisterField.declaringField = field; - field.extensionField = sisterField; - extendedType.add(sisterField); - return true; - } - return false; + const extendedType = field.parent.lookup(field.extend) + if (extendedType) { + const sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options) + sisterField.declaringField = field + field.extensionField = sisterField + extendedType.add(sisterField) + return true + } + return false } /** @@ -360,35 +329,27 @@ function tryHandleExtension(root, field) { * @private */ Root.prototype._handleAdd = function _handleAdd(object) { - if (object instanceof Field) { - - if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) - if (!tryHandleExtension(this, object)) - this.deferred.push(object); - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - object.parent[object.name] = object.values; // expose enum values as property of its parent - - } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { - - if (object instanceof Type) // Try to handle any deferred extensions - for (var i = 0; i < this.deferred.length;) - if (tryHandleExtension(this, this.deferred[i])) - this.deferred.splice(i, 1); - else - ++i; - for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace - this._handleAdd(object._nestedArray[j]); - if (exposeRe.test(object.name)) - object.parent[object.name] = object; // expose namespace as property of its parent + if (object instanceof Field) { + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) if (!tryHandleExtension(this, object)) this.deferred.push(object) + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) object.parent[object.name] = object.values // expose enum values as property of its parent + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + if (object instanceof Type) // Try to handle any deferred extensions + { + for (let i = 0; i < this.deferred.length;) { + if (tryHandleExtension(this, this.deferred[i])) this.deferred.splice(i, 1) + else ++i + } } - - // The above also adds uppercased (and thus conflict-free) nested types, services and enums as - // properties of namespaces just like static code does. This allows using a .d.ts generated for - // a static module with reflection-based solutions where the condition is met. -}; + for (let j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + { this._handleAdd(object._nestedArray[j]) } + if (exposeRe.test(object.name)) object.parent[object.name] = object // expose namespace as property of its parent + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +} /** * Called when any object is removed from this root or its sub-namespaces. @@ -397,43 +358,34 @@ Root.prototype._handleAdd = function _handleAdd(object) { * @private */ Root.prototype._handleRemove = function _handleRemove(object) { - if (object instanceof Field) { - - if (/* an extension field */ object.extend !== undefined) { - if (/* already handled */ object.extensionField) { // remove its sister field - object.extensionField.parent.remove(object.extensionField); - object.extensionField = null; - } else { // cancel the extension - var index = this.deferred.indexOf(object); - /* istanbul ignore else */ - if (index > -1) - this.deferred.splice(index, 1); - } - } - - } else if (object instanceof Enum) { - - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose enum values - - } else if (object instanceof Namespace) { - - for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace - this._handleRemove(object._nestedArray[i]); + if (object instanceof Field) { + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField) + object.extensionField = null + } else { // cancel the extension + const index = this.deferred.indexOf(object) + /* istanbul ignore else */ + if (index > -1) this.deferred.splice(index, 1) + } + } + } else if (object instanceof Enum) { + if (exposeRe.test(object.name)) delete object.parent[object.name] // unexpose enum values + } else if (object instanceof Namespace) { + for (let i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + { this._handleRemove(object._nestedArray[i]) } + + if (exposeRe.test(object.name)) delete object.parent[object.name] // unexpose namespaces + } +} - if (exposeRe.test(object.name)) - delete object.parent[object.name]; // unexpose namespaces +Root._configure = function () { + Type = require('./type') + parse = require('./parse') + common = require('./common') - } -}; - -Root._configure = function() { - Type = require('./type'); - parse = require('./parse'); - common = require('./common'); - - Field = require("./field"); - Enum = require("./enum"); - OneOf = require("./oneof"); - util = require("./util"); -}; + Field = require('./field') + Enum = require('./enum') + OneOf = require('./oneof') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/roots.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/roots.js index 70ad6602..c0558779 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/roots.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/roots.js @@ -2,5 +2,4 @@ * Created by zhangmiao on 2018/3/13. */ - -module.exports = {}; \ No newline at end of file +module.exports = {} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/rpc/service.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/rpc/service.js index b0c8243e..32cf96e3 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/rpc/service.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/rpc/service.js @@ -1,9 +1,8 @@ -"use strict"; -module.exports = Service; -var util = require("../util"); +module.exports = Service +const util = require('../util'); // Extends EventEmitter -(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service /** * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. @@ -39,29 +38,27 @@ var util = require("../util"); * @param {boolean} [responseDelimited=false] Whether responses are length-delimited */ function Service(rpcImpl, requestDelimited, responseDelimited) { + if (typeof rpcImpl !== 'function') throw TypeError('rpcImpl must be a function') - if (typeof rpcImpl !== "function") - throw TypeError("rpcImpl must be a function"); + util.EventEmitter.call(this) - util.EventEmitter.call(this); - - /** + /** * RPC implementation. Becomes `null` once the service is ended. * @type {RPCImpl|null} */ - this.rpcImpl = rpcImpl; + this.rpcImpl = rpcImpl - /** + /** * Whether requests are length-delimited. * @type {boolean} */ - this.requestDelimited = Boolean(requestDelimited); + this.requestDelimited = Boolean(requestDelimited) - /** + /** * Whether responses are length-delimited. * @type {boolean} */ - this.responseDelimited = Boolean(responseDelimited); + this.responseDelimited = Boolean(responseDelimited) } /** @@ -76,54 +73,50 @@ function Service(rpcImpl, requestDelimited, responseDelimited) { * @template TRes extends Message */ Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { - - if (!request) - throw TypeError("request must be specified"); - - var self = this; - if (!callback) - return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); - - if (!self.rpcImpl) { - setTimeout(function() { callback(Error("already ended")); }, 0); - return undefined; - } - - try { - return self.rpcImpl( - method, - requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), - function rpcCallback(err, response) { - - if (err) { - self.emit("error", err, method); - return callback(err); - } - - if (response === null) { - self.end(/* endedByRPC */ true); - return undefined; - } - - if (!(response instanceof responseCtor)) { - try { - response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); - } catch (err) { - self.emit("error", err, method); - return callback(err); - } - } - - self.emit("data", response, method); - return callback(null, response); - } - ); - } catch (err) { - self.emit("error", err, method); - setTimeout(function() { callback(err); }, 0); - return undefined; - } -}; + if (!request) throw TypeError('request must be specified') + + const self = this + if (!callback) return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request) + + if (!self.rpcImpl) { + setTimeout(function () { callback(Error('already ended')) }, 0) + return undefined + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? 'encodeDelimited' : 'encode'](request).finish(), + function rpcCallback(err, response) { + if (err) { + self.emit('error', err, method) + return callback(err) + } + + if (response === null) { + self.end(/* endedByRPC */ true) + return undefined + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? 'decodeDelimited' : 'decode'](response) + } catch (err) { + self.emit('error', err, method) + return callback(err) + } + } + + self.emit('data', response, method) + return callback(null, response) + } + ) + } catch (err) { + self.emit('error', err, method) + setTimeout(function () { callback(err) }, 0) + return undefined + } +} /** * Ends this service and emits the `end` event. @@ -131,11 +124,11 @@ Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, * @returns {rpc.Service} `this` */ Service.prototype.end = function end(endedByRPC) { - if (this.rpcImpl) { - if (!endedByRPC) // signal end to rpcImpl - this.rpcImpl(null, null, null); - this.rpcImpl = null; - this.emit("end").off(); - } - return this; -}; + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + { this.rpcImpl(null, null, null) } + this.rpcImpl = null + this.emit('end').off() + } + return this +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/service.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/service.js index e7c30e5d..3d11d3ec 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/service.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/service.js @@ -1,13 +1,13 @@ -"use strict"; -module.exports = Service; +module.exports = Service // extends Namespace -var Namespace = require("./namespace"); -((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; +const Namespace = require('./namespace'); -var Method, - util, - rpc; +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = 'Service' + +let Method +let util +let rpc /** * Constructs a new service instance. @@ -19,20 +19,20 @@ var Method, * @throws {TypeError} If arguments are invalid */ function Service(name, options) { - Namespace.call(this, name, options); + Namespace.call(this, name, options) - /** + /** * Service methods. * @type {Object.} */ - this.methods = {}; // toJSON, marker + this.methods = {} // toJSON, marker - /** + /** * Cached methods as an array. * @type {Method[]|null} * @private */ - this._methodsArray = null; + this._methodsArray = null } /** @@ -50,16 +50,13 @@ function Service(name, options) { * @throws {TypeError} If arguments are invalid */ Service.fromJSON = function fromJSON(name, json) { - var service = new Service(name, json.options); - /* istanbul ignore else */ - if (json.methods) - for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) - service.add(Method.fromJSON(names[i], json.methods[names[i]])); - if (json.nested) - service.addJSON(json.nested); - service.comment = json.comment; - return service; -}; + const service = new Service(name, json.options) + /* istanbul ignore else */ + if (json.methods) for (let names = Object.keys(json.methods), i = 0; i < names.length; ++i) service.add(Method.fromJSON(names[i], json.methods[names[i]])) + if (json.nested) service.addJSON(json.nested) + service.comment = json.comment + return service +} /** * Converts this service to a service descriptor. @@ -67,15 +64,15 @@ Service.fromJSON = function fromJSON(name, json) { * @returns {IService} Service descriptor */ Service.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - return util.toObject([ - "options" , inherited && inherited.options || undefined, - "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, - "nested" , inherited && inherited.nested || undefined, - "comment" , keepComments ? this.comment : undefined - ]); -}; + const inherited = Namespace.prototype.toJSON.call(this, toJSONOptions) + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + return util.toObject([ + 'options', inherited && inherited.options || undefined, + 'methods', Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + 'nested', inherited && inherited.nested || undefined, + 'comment', keepComments ? this.comment : undefined + ]) +} /** * Methods of this service as an array for iteration. @@ -83,68 +80,63 @@ Service.prototype.toJSON = function toJSON(toJSONOptions) { * @type {Method[]} * @readonly */ -Object.defineProperty(Service.prototype, "methodsArray", { - get: function() { - return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); - } -}); +Object.defineProperty(Service.prototype, 'methodsArray', { + get() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)) + } +}) function clearCache(service) { - service._methodsArray = null; - return service; + service._methodsArray = null + return service } /** * @override */ Service.prototype.get = function get(name) { - return this.methods[name] - || Namespace.prototype.get.call(this, name); -}; + return this.methods[name] || + Namespace.prototype.get.call(this, name) +} /** * @override */ Service.prototype.resolveAll = function resolveAll() { - var methods = this.methodsArray; - for (var i = 0; i < methods.length; ++i) - methods[i].resolve(); - return Namespace.prototype.resolve.call(this); -}; + const methods = this.methodsArray + for (let i = 0; i < methods.length; ++i) methods[i].resolve() + return Namespace.prototype.resolve.call(this) +} /** * @override */ Service.prototype.add = function add(object) { - - /* istanbul ignore if */ - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Method) { - this.methods[object.name] = object; - object.parent = this; - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; + /* istanbul ignore if */ + if (this.get(object.name)) throw Error("duplicate name '" + object.name + "' in " + this) + + if (object instanceof Method) { + this.methods[object.name] = object + object.parent = this + return clearCache(this) + } + return Namespace.prototype.add.call(this, object) +} /** * @override */ Service.prototype.remove = function remove(object) { - if (object instanceof Method) { - - /* istanbul ignore if */ - if (this.methods[object.name] !== object) - throw Error(object + " is not a member of " + this); + if (object instanceof Method) { + /* istanbul ignore if */ + if (this.methods[object.name] !== object) throw Error(object + ' is not a member of ' + this) - delete this.methods[object.name]; - object.parent = null; - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); -}; + delete this.methods[object.name] + object.parent = null + return clearCache(this) + } + return Namespace.prototype.remove.call(this, object) +} /** * Creates a runtime service using the specified rpc implementation. @@ -154,20 +146,20 @@ Service.prototype.remove = function remove(object) { * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. */ Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { - var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); - for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { - var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); - rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ - m: method, - q: method.resolvedRequestType.ctor, - s: method.resolvedResponseType.ctor - }); - } - return rpcService; -}; - -Service._configure = function (){ - Method = require("./method"); - util = require("./util"); - rpc = require("./rpc/service"); -}; \ No newline at end of file + const rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited) + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + const methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, '') + rpcService[methodName] = util.codegen(['r', 'c'], util.isReserved(methodName) ? methodName + '_' : methodName)('return this.rpcCall(m,q,s,r,c)')({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }) + } + return rpcService +} + +Service._configure = function () { + Method = require('./method') + util = require('./util') + rpc = require('./rpc/service') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/tokenize.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/tokenize.js index ce2ca698..676bea5b 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/tokenize.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/tokenize.js @@ -1,21 +1,21 @@ -module.exports = tokenize; - -var delimRe = /[\s{}=;:[\],'"()<>]/g, - stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, - stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; - -var setCommentRe = /^ *[*/]+ */, - setCommentAltRe = /^\s*\*?\/*/, - setCommentSplitRe = /\n/g, - whitespaceRe = /\s/, - unescapeRe = /\\(.?)/g; - -var unescapeMap = { - "0": "\0", - "r": "\r", - "n": "\n", - "t": "\t" -}; +module.exports = tokenize + +const delimRe = /[\s{}=;:[\],'"()<>]/g +const stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g +const stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g + +const setCommentRe = /^ *[*/]+ */ +const setCommentAltRe = /^\s*\*?\/*/ +const setCommentSplitRe = /\n/g +const whitespaceRe = /\s/ +const unescapeRe = /\\(.?)/g + +const unescapeMap = { + 0: '\0', + r: '\r', + n: '\n', + t: '\t' +} /** * Unescapes a string. @@ -25,18 +25,18 @@ var unescapeMap = { * @memberof tokenize */ function unescape(str) { - return str.replace(unescapeRe, function($0, $1) { - switch ($1) { - case "\\": - case "": - return $1; - default: - return unescapeMap[$1] || ""; - } - }); + return str.replace(unescapeRe, function ($0, $1) { + switch ($1) { + case '\\': + case '': + return $1 + default: + return unescapeMap[$1] || '' + } + }) } -tokenize.unescape = unescape; +tokenize.unescape = unescape /** * Gets the next token and advances. @@ -96,250 +96,241 @@ tokenize.unescape = unescape; * @returns {ITokenizerHandle} Tokenizer handle */ function tokenize(source, alternateCommentMode) { - /* eslint-disable callback-return */ - source = source.toString(); + /* eslint-disable callback-return */ + source = source.toString() - var offset = 0, - length = source.length, - line = 1, - commentType = null, - commentText = null, - commentLine = 0, - commentLineEmpty = false; + let offset = 0 + const length = source.length + let line = 1 + let commentType = null + let commentText = null + let commentLine = 0 + let commentLineEmpty = false - var stack = []; + const stack = [] - var stringDelim = null; + let stringDelim = null - /* istanbul ignore next */ - /** + /* istanbul ignore next */ + /** * Creates an error for illegal syntax. * @param {string} subject Subject * @returns {Error} Error created * @inner */ - function illegal(subject) { - return Error("illegal " + subject + " (line " + line + ")"); - } + function illegal(subject) { + return Error('illegal ' + subject + ' (line ' + line + ')') + } - /** + /** * Reads a string till its end. * @returns {string} String read * @inner */ - function readString() { - var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; - re.lastIndex = offset - 1; - var match = re.exec(source); - if (!match) - throw illegal("string"); - offset = re.lastIndex; - push(stringDelim); - stringDelim = null; - return unescape(match[1]); - } - - /** + function readString() { + const re = stringDelim === "'" ? stringSingleRe : stringDoubleRe + re.lastIndex = offset - 1 + const match = re.exec(source) + if (!match) throw illegal('string') + offset = re.lastIndex + push(stringDelim) + stringDelim = null + return unescape(match[1]) + } + + /** * Gets the character at `pos` within the source. * @param {number} pos Position * @returns {string} Character * @inner */ - function charAt(pos) { - return source.charAt(pos); - } + function charAt(pos) { + return source.charAt(pos) + } - /** + /** * Sets the current comment text. * @param {number} start Start offset * @param {number} end End offset * @returns {undefined} * @inner */ - function setComment(start, end) { - commentType = source.charAt(start++); - commentLine = line; - commentLineEmpty = false; - var lookback; - if (alternateCommentMode) { - lookback = 2; // alternate comment parsing: "//" or "/*" - } else { - lookback = 3; // "///" or "/**" - } - var commentOffset = start - lookback, - c; - do { - if (--commentOffset < 0 || - (c = source.charAt(commentOffset)) === "\n") { - commentLineEmpty = true; - break; - } - } while (c === " " || c === "\t"); - var lines = source - .substring(start, end) - .split(setCommentSplitRe); - for (var i = 0; i < lines.length; ++i) - lines[i] = lines[i] - .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") - .trim(); - commentText = lines - .join("\n") - .trim(); + function setComment(start, end) { + commentType = source.charAt(start++) + commentLine = line + commentLineEmpty = false + let lookback + if (alternateCommentMode) { + lookback = 2 // alternate comment parsing: "//" or "/*" + } else { + lookback = 3 // "///" or "/**" } - - function isDoubleSlashCommentLine(startOffset) { - var endOffset = findEndOfLine(startOffset); - - // see if remaining line matches comment pattern - var lineText = source.substring(startOffset, endOffset); - // look for 1 or 2 slashes since startOffset would already point past - // the first slash that started the comment. - var isComment = /^\s*\/{1,2}/.test(lineText); - return isComment; + let commentOffset = start - lookback + let c + do { + if (--commentOffset < 0 || + (c = source.charAt(commentOffset)) === '\n') { + commentLineEmpty = true + break + } + } while (c === ' ' || c === '\t') + const lines = source + .substring(start, end) + .split(setCommentSplitRe) + for (let i = 0; i < lines.length; ++i) { + lines[i] = lines[i] + .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, '') + .trim() } - - function findEndOfLine(cursor) { - // find end of cursor's line - var endOffset = cursor; - while (endOffset < length && charAt(endOffset) !== "\n") { - endOffset++; - } - return endOffset; + commentText = lines + .join('\n') + .trim() + } + + function isDoubleSlashCommentLine(startOffset) { + const endOffset = findEndOfLine(startOffset) + + // see if remaining line matches comment pattern + const lineText = source.substring(startOffset, endOffset) + // look for 1 or 2 slashes since startOffset would already point past + // the first slash that started the comment. + const isComment = /^\s*\/{1,2}/.test(lineText) + return isComment + } + + function findEndOfLine(cursor) { + // find end of cursor's line + let endOffset = cursor + while (endOffset < length && charAt(endOffset) !== '\n') { + endOffset++ } + return endOffset + } - /** + /** * Obtains the next token. * @returns {string|null} Next token or `null` on eof * @inner */ - function next() { - if (stack.length > 0) - return stack.shift(); - if (stringDelim) - return readString(); - var repeat, - prev, - curr, - start, - isDoc; - do { - if (offset === length) - return null; - repeat = false; - while (whitespaceRe.test(curr = charAt(offset))) { - if (curr === "\n") - ++line; - if (++offset === length) - return null; + function next() { + if (stack.length > 0) return stack.shift() + if (stringDelim) return readString() + let repeat + let prev + let curr + let start + let isDoc + do { + if (offset === length) return null + repeat = false + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === '\n') ++line + if (++offset === length) return null + } + + if (charAt(offset) === '/') { + if (++offset === length) { + throw illegal('comment') + } + if (charAt(offset) === '/') { // Line + if (!alternateCommentMode) { + // check for triple-slash comment + isDoc = charAt(start = offset + 1) === '/' + + while (charAt(++offset) !== '\n') { + if (offset === length) { + return null + } } - - if (charAt(offset) === "/") { - if (++offset === length) { - throw illegal("comment"); - } - if (charAt(offset) === "/") { // Line - if (!alternateCommentMode) { - // check for triple-slash comment - isDoc = charAt(start = offset + 1) === "/"; - - while (charAt(++offset) !== "\n") { - if (offset === length) { - return null; - } - } - ++offset; - if (isDoc) { - setComment(start, offset - 1); - } - ++line; - repeat = true; - } else { - // check for double-slash comments, consolidating consecutive lines - start = offset; - isDoc = false; - if (isDoubleSlashCommentLine(offset)) { - isDoc = true; - do { - offset = findEndOfLine(offset); - if (offset === length) { - break; - } - offset++; - } while (isDoubleSlashCommentLine(offset)); - } else { - offset = Math.min(length, findEndOfLine(offset) + 1); - } - if (isDoc) { - setComment(start, offset); - } - line++; - repeat = true; - } - } else if ((curr = charAt(offset)) === "*") { /* Block */ - // check for /** (regular comment mode) or /* (alternate comment mode) - start = offset + 1; - isDoc = alternateCommentMode || charAt(start) === "*"; - do { - if (curr === "\n") { - ++line; - } - if (++offset === length) { - throw illegal("comment"); - } - prev = curr; - curr = charAt(offset); - } while (prev !== "*" || curr !== "/"); - ++offset; - if (isDoc) { - setComment(start, offset - 2); - } - repeat = true; - } else { - return "/"; + ++offset + if (isDoc) { + setComment(start, offset - 1) + } + ++line + repeat = true + } else { + // check for double-slash comments, consolidating consecutive lines + start = offset + isDoc = false + if (isDoubleSlashCommentLine(offset)) { + isDoc = true + do { + offset = findEndOfLine(offset) + if (offset === length) { + break } + offset++ + } while (isDoubleSlashCommentLine(offset)) + } else { + offset = Math.min(length, findEndOfLine(offset) + 1) } - } while (repeat); - - // offset !== length if we got here - - var end = offset; - delimRe.lastIndex = 0; - var delim = delimRe.test(charAt(end++)); - if (!delim) - while (end < length && !delimRe.test(charAt(end))) - ++end; - var token = source.substring(offset, offset = end); - if (token === "\"" || token === "'") - stringDelim = token; - return token; - } + if (isDoc) { + setComment(start, offset) + } + line++ + repeat = true + } + } else if ((curr = charAt(offset)) === '*') { /* Block */ + // check for /** (regular comment mode) or /* (alternate comment mode) + start = offset + 1 + isDoc = alternateCommentMode || charAt(start) === '*' + do { + if (curr === '\n') { + ++line + } + if (++offset === length) { + throw illegal('comment') + } + prev = curr + curr = charAt(offset) + } while (prev !== '*' || curr !== '/') + ++offset + if (isDoc) { + setComment(start, offset - 2) + } + repeat = true + } else { + return '/' + } + } + } while (repeat) + + // offset !== length if we got here + + let end = offset + delimRe.lastIndex = 0 + const delim = delimRe.test(charAt(end++)) + if (!delim) while (end < length && !delimRe.test(charAt(end))) ++end + const token = source.substring(offset, offset = end) + if (token === '"' || token === "'") stringDelim = token + return token + } - /** + /** * Pushes a token back to the stack. * @param {string} token Token * @returns {undefined} * @inner */ - function push(token) { - stack.push(token); - } + function push(token) { + stack.push(token) + } - /** + /** * Peeks for the next token. * @returns {string|null} Token or `null` on eof * @inner */ - function peek() { - if (!stack.length) { - var token = next(); - if (token === null) - return null; - push(token); - } - return stack[0]; + function peek() { + if (!stack.length) { + const token = next() + if (token === null) return null + push(token) } + return stack[0] + } - /** + /** * Skips a token. * @param {string} expected Expected token * @param {boolean} [optional=false] Whether the token is optional @@ -347,50 +338,49 @@ function tokenize(source, alternateCommentMode) { * @throws {Error} When a required token is not present * @inner */ - function skip(expected, optional) { - var actual = peek(), - equals = actual === expected; - if (equals) { - next(); - return true; - } - if (!optional) - throw illegal("token '" + actual + "', '" + expected + "' expected"); - return false; + function skip(expected, optional) { + const actual = peek() + const equals = actual === expected + if (equals) { + next() + return true } + if (!optional) throw illegal("token '" + actual + "', '" + expected + "' expected") + return false + } - /** + /** * Gets a comment. * @param {number} [trailingLine] Line number if looking for a trailing comment * @returns {string|null} Comment text * @inner */ - function cmnt(trailingLine) { - var ret = null; - if (trailingLine === undefined) { - if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) { - ret = commentText; - } - } else { - /* istanbul ignore else */ - if (commentLine < trailingLine) { - peek(); - } - if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) { - ret = commentText; - } - } - return ret; + function cmnt(trailingLine) { + let ret = null + if (trailingLine === undefined) { + if (commentLine === line - 1 && (alternateCommentMode || commentType === '*' || commentLineEmpty)) { + ret = commentText + } + } else { + /* istanbul ignore else */ + if (commentLine < trailingLine) { + peek() + } + if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === '/')) { + ret = commentText + } } - - return Object.defineProperty({ - next: next, - peek: peek, - push: push, - skip: skip, - cmnt: cmnt - }, "line", { - get: function() { return line; } - }); - /* eslint-enable callback-return */ + return ret + } + + return Object.defineProperty({ + next, + peek, + push, + skip, + cmnt + }, 'line', { + get() { return line } + }) + /* eslint-enable callback-return */ } diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/type.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/type.js index 844da0a7..981003b1 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/type.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/type.js @@ -2,469 +2,432 @@ * Created by zhangmiao on 2018/3/13. */ - -module.exports = Type; - -var Namespace = require("./namespace"); -((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; - - -var Enum, - Field, - Message, - OneOf, - Writer, - Reader, - util, - verifier, - encoder, - decoder, - Service, - wrappers, - converter, - MapField; - - +module.exports = Type + +const Namespace = require('./namespace'); + +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = 'Type' + +let Enum +let Field +let Message +let OneOf +let Writer +let Reader +let util +let verifier +let encoder +let decoder +let Service +let wrappers +let converter +let MapField function Type(name, options) { - Namespace.call(this, name, options); + Namespace.call(this, name, options) - /** + /** * Message fields. * @type {Object.} */ - this.fields = {}; // toJSON, marker + this.fields = {} // toJSON, marker - /** + /** * Oneofs declared within this namespace, if any. * @type {Object.} */ - this.oneofs = undefined; // toJSON + this.oneofs = undefined // toJSON - /** + /** * Extension ranges, if any. * @type {number[][]} */ - this.extensions = undefined; // toJSON + this.extensions = undefined // toJSON - /** + /** * Reserved ranges, if any. * @type {Array.} */ - this.reserved = undefined; // toJSON + this.reserved = undefined // toJSON - /*? + /* ? * Whether this type is a legacy group. * @type {boolean|undefined} */ - this.group = undefined; // toJSON 这个可能不需要,因为不支持 + this.group = undefined // toJSON 这个可能不需要,因为不支持 - /** + /** * Cached fields by id. * @type {Object.|null} * @private */ - this._fieldsById = null; + this._fieldsById = null - /** + /** * Cached fields as an array. * @type {Field[]|null} * @private */ - this._fieldsArray = null; + this._fieldsArray = null - /** + /** * Cached oneofs as an array. * @type {OneOf[]|null} * @private */ - this._oneofsArray = null; + this._oneofsArray = null - /** + /** * Cached constructor. * @type {Constructor<{}>} * @private */ - this._ctor = null; + this._ctor = null } - Object.defineProperties(Type.prototype, { - /** + /** * Message fields by id. * @name Type#fieldsById * @type {Object.} * @readonly */ - fieldsById: { - get: function() { - - /* istanbul ignore if */ - if (this._fieldsById) - return this._fieldsById; + fieldsById: { + get() { + /* istanbul ignore if */ + if (this._fieldsById) return this._fieldsById - this._fieldsById = {}; - for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { - var field = this.fields[names[i]], - id = field.id; + this._fieldsById = {} + for (let names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + const field = this.fields[names[i]] + const id = field.id - /* istanbul ignore if */ - if (this._fieldsById[id]) - throw Error("duplicate id " + id + " in " + this); + /* istanbul ignore if */ + if (this._fieldsById[id]) throw Error('duplicate id ' + id + ' in ' + this) - this._fieldsById[id] = field; - } - return this._fieldsById; - } - }, + this._fieldsById[id] = field + } + return this._fieldsById + } + }, - /** + /** * Fields of this message as an array for iteration. * @name Type#fieldsArray * @type {Field[]} * @readonly */ - fieldsArray: { - get: function() { - return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); - } - }, + fieldsArray: { + get() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)) + } + }, - /** + /** * Oneofs of this message as an array for iteration. * @name Type#oneofsArray * @type {OneOf[]} * @readonly */ - oneofsArray: { - get: function() { - return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); - } - }, + oneofsArray: { + get() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)) + } + }, - /** + /** * The registered constructor, if any registered, otherwise a generic constructor. * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. * @name Type#ctor * @type {Constructor<{}>} */ - ctor: { - get: function() { - return this._ctor || (this.ctor = Type.generateConstructor(this)); - }, - set: function(ctor) { - - // Ensure proper prototype - var prototype = ctor.prototype; - if (!(prototype instanceof Message)) { - (ctor.prototype = new Message()).constructor = ctor; - util.merge(ctor.prototype, prototype); + ctor: { + get() { + return this._ctor || (this.ctor = Type.generateConstructor(this)) + }, + set(ctor) { + // Ensure proper prototype + const prototype = ctor.prototype + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor + util.merge(ctor.prototype, prototype) + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this + + // Mix in static methods + util.merge(ctor, Message, true) + util.merge(ctor.prototype, Message, true) + + this._ctor = ctor + + // Messages have non-enumerable default values on their prototype + let i = 0 + for (; i < /* initializes */ this.fieldsArray.length; ++i) this._fieldsArray[i].resolve() // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + const ctorProperties = {} + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) { + const oneofName = this._oneofsArray[i].resolve().name + + const oneOfGetAndSet = (function (fieldNames) { + const fieldMap = {} + for (let i = 0; i < fieldNames.length; ++i) fieldMap[fieldNames[i]] = 0 + + return { + setter(name) { + if (fieldNames.indexOf(name) < 0) return + fieldMap[name] = 1 + for (let i = 0; i < fieldNames.length; ++i) if (fieldNames[i] !== name) delete this[/* "_"+*/fieldNames[i]] + }, + + getter() { + for (let keys = Object.keys(this), i = keys.length - 1; i > -1; --i) if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) return keys[i] } - // Classes and messages reference their reflected type - ctor.$type = ctor.prototype.$type = this; - - // Mix in static methods - util.merge(ctor, Message, true); - util.merge(ctor.prototype, Message, true); - - - this._ctor = ctor; - - // Messages have non-enumerable default values on their prototype - var i = 0; - for (; i < /* initializes */ this.fieldsArray.length; ++i) - this._fieldsArray[i].resolve(); // ensures a proper value - - // Messages have non-enumerable getters and setters for each virtual oneof field - var ctorProperties = {}; - for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) { - var oneofName = this._oneofsArray[i].resolve().name; - - var oneOfGetAndSet = (function(fieldNames){ - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 0; - - return { - setter : function (name){ - if(fieldNames.indexOf(name) < 0) return; - fieldMap[name] = 1; - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[/*"_"+*/fieldNames[i]]; - }, - - getter : function (){ - for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) - if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) - return keys[i]; - } - - } - })(this._oneofsArray[i].oneof); - - ctorProperties[oneofName] = { - get: oneOfGetAndSet.getter, - set: oneOfGetAndSet.setter - }; - //var fieldNames = this._oneofsArray[i].oneof; - //for (var j = 0 ; j < fieldNames.length; j++){ - // var fieldName = fieldNames[j]; - // ctorProperties[fieldName] = { - // set : (function(oneofName, fieldName){ - // return function (value){ - // this[oneofName] = fieldName; - // this["_"+fieldName] = value; - // } - // })(oneofName , fieldName), - // get : (function(fieldName){ - // return function (){ - // return this["_"+fieldName]; - // } - // })(fieldName) - // } - //} - } + } + }(this._oneofsArray[i].oneof)) - if (i) { - //util.merge(ctor.prototype, ctorProperties, true); - Object.defineProperties(ctor.prototype, ctorProperties); - } + ctorProperties[oneofName] = { + get: oneOfGetAndSet.getter, + set: oneOfGetAndSet.setter } - } -}); + // var fieldNames = this._oneofsArray[i].oneof; + // for (var j = 0 ; j < fieldNames.length; j++){ + // var fieldName = fieldNames[j]; + // ctorProperties[fieldName] = { + // set : (function(oneofName, fieldName){ + // return function (value){ + // this[oneofName] = fieldName; + // this["_"+fieldName] = value; + // } + // })(oneofName , fieldName), + // get : (function(fieldName){ + // return function (){ + // return this["_"+fieldName]; + // } + // })(fieldName) + // } + // } + } + if (i) { + // util.merge(ctor.prototype, ctorProperties, true); + Object.defineProperties(ctor.prototype, ctorProperties) + } + } + } +}) -//生成一个构造函数 +// 生成一个构造函数 Type.generateConstructor = function generateConstructor(mtype) { - return function (p){ - for (var i = 0, field; i < mtype.fieldsArray.length; i++){ - if((field = mtype._fieldsArray[i]).map){ - this[field.name] = {}; - }else if(field.repeated){ - this[field.name] = []; - } - } + return function (p) { + for (var i = 0, field; i < mtype.fieldsArray.length; i++) { + if ((field = mtype._fieldsArray[i]).map) { + this[field.name] = {} + } else if (field.repeated) { + this[field.name] = [] + } + } - if(p){ - for (var ks = Object.keys(p), j = 0; j < ks.length; ++j) { - if (p[ks[j]] != null) { - this[ks[j]] = p[ks[j]] - } - } + if (p) { + for (let ks = Object.keys(p), j = 0; j < ks.length; ++j) { + if (p[ks[j]] != null) { + this[ks[j]] = p[ks[j]] } - }; -}; - + } + } + } +} function clearCache(type) { - type._fieldsById = type._fieldsArray = type._oneofsArray = null; - delete type.encode; - delete type.decode; - delete type.verify; - return type; + type._fieldsById = type._fieldsArray = type._oneofsArray = null + delete type.encode + delete type.decode + delete type.verify + return type } - - Type.fromJSON = function fromJSON(name, json) { - var type = new Type(name, json.options); - type.extensions = json.extensions; - type.reserved = json.reserved; - var names = Object.keys(json.fields), - i = 0; - for (; i < names.length; ++i) - type.add( - ( typeof json.fields[names[i]].keyType !== "undefined" - ? MapField.fromJSON - : Field.fromJSON )(names[i], json.fields[names[i]]) - ); - if (json.oneofs) - for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) - type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); - if (json.nested) - for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { - var nested = json.nested[names[i]]; - type.add( // most to least likely - ( nested.id !== undefined - ? Field.fromJSON - : nested.fields !== undefined - ? Type.fromJSON - : nested.values !== undefined - ? Enum.fromJSON - : nested.methods !== undefined - ? Service.fromJSON - : Namespace.fromJSON )(names[i], nested) - ); - } - if (json.extensions && json.extensions.length) - type.extensions = json.extensions; - if (json.reserved && json.reserved.length) - type.reserved = json.reserved; - if (json.group) - type.group = true; - if (json.comment) - type.comment = json.comment; - return type; -}; + const type = new Type(name, json.options) + type.extensions = json.extensions + type.reserved = json.reserved + let names = Object.keys(json.fields) + let i = 0 + for (; i < names.length; ++i) { + type.add( + (typeof json.fields[names[i]].keyType !== 'undefined' + ? MapField.fromJSON + : Field.fromJSON)(names[i], json.fields[names[i]]) + ) + } + if (json.oneofs) for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])) + if (json.nested) { + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + const nested = json.nested[names[i]] + type.add( // most to least likely + (nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON)(names[i], nested) + ) + } + } + if (json.extensions && json.extensions.length) type.extensions = json.extensions + if (json.reserved && json.reserved.length) type.reserved = json.reserved + if (json.group) type.group = true + if (json.comment) type.comment = json.comment + return type +} Type.prototype.toJSON = function toJSON(toJSONOptions) { - var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); - var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; - - return { - "options" : inherited && inherited.options || undefined, - "oneofs" : Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), - "fields" : Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, - "extensions" : this.extensions && this.extensions.length ? this.extensions : undefined, - "reserved" : this.reserved && this.reserved.length ? this.reserved : undefined, - "group" : this.group || undefined, - "nested" : inherited && inherited.nested || undefined, - "comment" : keepComments ? this.comment : undefined - }; -}; + const inherited = Namespace.prototype.toJSON.call(this, toJSONOptions) + const keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false + + return { + options: inherited && inherited.options || undefined, + oneofs: Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + fields: Namespace.arrayToJSON(this.fieldsArray.filter(function (obj) { return !obj.declaringField }), toJSONOptions) || {}, + extensions: this.extensions && this.extensions.length ? this.extensions : undefined, + reserved: this.reserved && this.reserved.length ? this.reserved : undefined, + group: this.group || undefined, + nested: inherited && inherited.nested || undefined, + comment: keepComments ? this.comment : undefined + } +} Type.prototype.resolveAll = function resolveAll() { - var fields = this.fieldsArray, i = 0; - while (i < fields.length) - fields[i++].resolve(); - var oneofs = this.oneofsArray; i = 0; - while (i < oneofs.length) - oneofs[i++].resolve(); - return Namespace.prototype.resolveAll.call(this); -}; + const fields = this.fieldsArray; let + i = 0 + while (i < fields.length) fields[i++].resolve() + const oneofs = this.oneofsArray; i = 0 + while (i < oneofs.length) oneofs[i++].resolve() + return Namespace.prototype.resolveAll.call(this) +} Type.prototype.get = function get(name) { - return this.fields[name] - || this.oneofs && this.oneofs[name] - || this.nested && this.nested[name] - || null; -}; + return this.fields[name] || + this.oneofs && this.oneofs[name] || + this.nested && this.nested[name] || + null +} Type.prototype.add = function add(object) { - - if (this.get(object.name)) - throw Error("duplicate name '" + object.name + "' in " + this); - - if (object instanceof Field && object.extend === undefined) { - if (this._fieldsById && this._fieldsById[object.id]) - throw Error("duplicate id " + object.id + " in " + this); - if (this.isReservedId(object.id)) - throw Error("id " + object.id + " is reserved in " + this); - if (this.isReservedName(object.name)) - throw Error("name '" + object.name + "' is reserved in " + this); - - if (object.parent) - object.parent.remove(object); - this.fields[object.name] = object; - object.message = this; - object.onAdd(this); - return clearCache(this); - } - if (object instanceof OneOf) { - if (!this.oneofs) - this.oneofs = {}; - this.oneofs[object.name] = object; - object.onAdd(this); - return clearCache(this); - } - return Namespace.prototype.add.call(this, object); -}; + if (this.get(object.name)) throw Error("duplicate name '" + object.name + "' in " + this) + + if (object instanceof Field && object.extend === undefined) { + if (this._fieldsById && this._fieldsById[object.id]) throw Error('duplicate id ' + object.id + ' in ' + this) + if (this.isReservedId(object.id)) throw Error('id ' + object.id + ' is reserved in ' + this) + if (this.isReservedName(object.name)) throw Error("name '" + object.name + "' is reserved in " + this) + + if (object.parent) object.parent.remove(object) + this.fields[object.name] = object + object.message = this + object.onAdd(this) + return clearCache(this) + } + if (object instanceof OneOf) { + if (!this.oneofs) this.oneofs = {} + this.oneofs[object.name] = object + object.onAdd(this) + return clearCache(this) + } + return Namespace.prototype.add.call(this, object) +} Type.prototype.remove = function remove(object) { - if (object instanceof Field && object.extend === undefined) { - // See Type#add for the reason why extension fields are excluded here. - - /* istanbul ignore if */ - if (!this.fields || this.fields[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.fields[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - if (object instanceof OneOf) { - - /* istanbul ignore if */ - if (!this.oneofs || this.oneofs[object.name] !== object) - throw Error(object + " is not a member of " + this); - - delete this.oneofs[object.name]; - object.parent = null; - object.onRemove(this); - return clearCache(this); - } - return Namespace.prototype.remove.call(this, object); -}; + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) throw Error(object + ' is not a member of ' + this) + + delete this.fields[object.name] + object.parent = null + object.onRemove(this) + return clearCache(this) + } + if (object instanceof OneOf) { + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) throw Error(object + ' is not a member of ' + this) + + delete this.oneofs[object.name] + object.parent = null + object.onRemove(this) + return clearCache(this) + } + return Namespace.prototype.remove.call(this, object) +} Type.prototype.isReservedId = function isReservedId(id) { - return Namespace.isReservedId(this.reserved, id); -}; + return Namespace.isReservedId(this.reserved, id) +} Type.prototype.isReservedName = function isReservedName(name) { - return Namespace.isReservedName(this.reserved, name); -}; + return Namespace.isReservedName(this.reserved, name) +} Type.prototype.create = function create(properties) { - return new this.ctor(properties); -}; - + return new this.ctor(properties) +} Type.prototype.setup = function setup() { - // Sets up everything at once so that the prototype chain does not have to be re-evaluated - // multiple times (V8, soft-deopt prototype-check). - - var fullName = this.fullName, - types = []; - for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) - types.push(this._fieldsArray[i].resolve().resolvedType); - - // Replace setup methods with type-specific generated functions - this.encode = encoder(this)({ - Writer : Writer, - types : types, - util : util - }); - - - this.decode = decoder(this)({ - Reader : Reader, - types : types, - util : util - }); - this.verify = verifier(this)({ - types : types, - util : util - }); - - this.fromObject = converter.fromObject(this)({ - types : types, - util : util - }); - this.toObject = converter.toObject(this)({ - types : types, - util : util - }); - - // Inject custom wrappers for common types - var wrapper = wrappers[fullName]; - if (wrapper) { - var originalThis = Object.create(this); - // if (wrapper.fromObject) { - originalThis.fromObject = this.fromObject; - this.fromObject = wrapper.fromObject.bind(originalThis); - // } - // if (wrapper.toObject) { - originalThis.toObject = this.toObject; - this.toObject = wrapper.toObject.bind(originalThis); - // } - } + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + const fullName = this.fullName + const types = [] + for (let i = 0; i < /* initializes */ this.fieldsArray.length; ++i) types.push(this._fieldsArray[i].resolve().resolvedType) - return this; -}; + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer, + types, + util + }) + + this.decode = decoder(this)({ + Reader, + types, + util + }) + this.verify = verifier(this)({ + types, + util + }) + + this.fromObject = converter.fromObject(this)({ + types, + util + }) + this.toObject = converter.toObject(this)({ + types, + util + }) + + // Inject custom wrappers for common types + const wrapper = wrappers[fullName] + if (wrapper) { + const originalThis = Object.create(this) + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject + this.fromObject = wrapper.fromObject.bind(originalThis) + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject + this.toObject = wrapper.toObject.bind(originalThis) + // } + } + + return this +} /** * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. @@ -474,8 +437,8 @@ Type.prototype.setup = function setup() { */ Type.prototype.encode = function encode_setup(message, writer) { - return this.setup().encode(message, writer); // overrides this method -}; + return this.setup().encode(message, writer) // overrides this method +} /** * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. @@ -484,8 +447,8 @@ Type.prototype.encode = function encode_setup(message, writer) { * @returns {Writer} writer */ Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); -}; + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim() +} /** * Decodes a message of this type. @@ -496,8 +459,8 @@ Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { */ Type.prototype.decode = function decode_setup(reader, length) { - return this.setup().decode(reader, length); // overrides this method -}; + return this.setup().decode(reader, length) // overrides this method +} /** * Decodes a message of this type preceeded by its byte length as a varint. * @param {Reader|Uint8Array} reader Reader or buffer to decode from @@ -506,10 +469,9 @@ Type.prototype.decode = function decode_setup(reader, length) { * @throws {util.ProtocolError} If required fields are missing */ Type.prototype.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof Reader)) - reader = Reader.create(reader); - return this.decode(reader, reader.uint32()); -}; + if (!(reader instanceof Reader)) reader = Reader.create(reader) + return this.decode(reader, reader.uint32()) +} /** * Verifies that field values are valid and that required fields are present. @@ -518,8 +480,8 @@ Type.prototype.decodeDelimited = function decodeDelimited(reader) { */ Type.prototype.verify = function verify_setup(message) { - return this.setup().verify(message); // overrides this method -}; + return this.setup().verify(message) // overrides this method +} /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. @@ -527,8 +489,8 @@ Type.prototype.verify = function verify_setup(message) { * @returns {Message<{}>} Message instance */ Type.prototype.fromObject = function fromObject(object) { - return this.setup().fromObject(object); -}; + return this.setup().fromObject(object) +} /** * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. @@ -556,29 +518,28 @@ Type.prototype.fromObject = function fromObject(object) { * @returns {Object.} Plain object */ Type.prototype.toObject = function toObject(message, options) { - return this.setup().toObject(message, options); -}; + return this.setup().toObject(message, options) +} Type.d = function decorateType(typeName) { - return function typeDecorator(target) { - util.decorateType(target, typeName); - }; -}; - -Type._configure = function (){ - Enum = require("./enum"); - Field = require("./field"); - Message = require("./message"); - OneOf = require("./oneof"); - Writer = require("./writer"); - Reader = require("./reader"); - util = require("./util"); - verifier = require("./verifier"); - encoder = require("./encoder"); - decoder = require("./decoder"); - Service = require("./service"); - wrappers = require("./wrappers"); - converter = require("./converter"); - MapField = require("./mapField"); - -}; \ No newline at end of file + return function typeDecorator(target) { + util.decorateType(target, typeName) + } +} + +Type._configure = function () { + Enum = require('./enum') + Field = require('./field') + Message = require('./message') + OneOf = require('./oneof') + Writer = require('./writer') + Reader = require('./reader') + util = require('./util') + verifier = require('./verifier') + encoder = require('./encoder') + decoder = require('./decoder') + Service = require('./service') + wrappers = require('./wrappers') + converter = require('./converter') + MapField = require('./mapField') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/types.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/types.js index 6c0c93fb..79ff7adb 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/types.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/types.js @@ -1,35 +1,34 @@ -"use strict"; - /** * Common type constants. * @namespace */ -var types = module.exports; -var util = require("./util"); +const types = module.exports +let util = require('./util') -var s = [ - "double", // 0 - "float", // 1 - "int32", // 2 - "uint32", // 3 - "sint32", // 4 - "fixed32", // 5 - "sfixed32", // 6 - "int64", // 7 - "uint64", // 8 - "sint64", // 9 - "fixed64", // 10 - "sfixed64", // 11 - "bool", // 12 - "string", // 13 - "bytes" // 14 -]; +const s = [ + 'double', // 0 + 'float', // 1 + 'int32', // 2 + 'uint32', // 3 + 'sint32', // 4 + 'fixed32', // 5 + 'sfixed32', // 6 + 'int64', // 7 + 'uint64', // 8 + 'sint64', // 9 + 'fixed64', // 10 + 'sfixed64', // 11 + 'bool', // 12 + 'string', // 13 + 'bytes' // 14 +] function bake(values, offset) { - var i = 0, o = {}; - offset |= 0; - while (i < values.length) o[s[i + offset]] = values[i++]; - return o; + let i = 0; const + o = {} + offset |= 0 + while (i < values.length) o[s[i + offset]] = values[i++] + return o } /** @@ -53,22 +52,22 @@ function bake(values, offset) { * @property {number} bytes=2 Ldelim wire type */ types.basic = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2, - /* bytes */ 2 -]); + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]) /** * Basic type defaults. @@ -92,23 +91,23 @@ types.basic = bake([ * @property {null} message=null Message default */ types.defaults = bake([ - /* double */ 0, - /* float */ 0, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 0, - /* sfixed32 */ 0, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 0, - /* sfixed64 */ 0, - /* bool */ false, - /* string */ "", - /* bytes */ util.emptyArray, - /* message */ null -]); + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ '', + /* bytes */ util.emptyArray, + /* message */ null +]) /** * Basic long type wire types. @@ -121,12 +120,12 @@ types.defaults = bake([ * @property {number} sfixed64=1 Fixed64 wire type */ types.long = bake([ - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1 -], 7); + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7) /** * Allowed types for map keys with their associated wire type. @@ -146,19 +145,19 @@ types.long = bake([ * @property {number} string=2 Ldelim wire type */ types.mapKey = bake([ - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0, - /* string */ 2 -], 2); + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2) /** * Allowed types for packed repeated fields with their associated wire type. @@ -179,21 +178,21 @@ types.mapKey = bake([ * @property {number} bool=0 Varint wire type */ types.packed = bake([ - /* double */ 1, - /* float */ 5, - /* int32 */ 0, - /* uint32 */ 0, - /* sint32 */ 0, - /* fixed32 */ 5, - /* sfixed32 */ 5, - /* int64 */ 0, - /* uint64 */ 0, - /* sint64 */ 0, - /* fixed64 */ 1, - /* sfixed64 */ 1, - /* bool */ 0 -]); + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]) -types._configure = function (){ - util = require('./util'); +types._configure = function () { + util = require('./util') } diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/utf8.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/utf8.js index d0a1c1af..e321b3a0 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/utf8.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/utf8.js @@ -1,11 +1,9 @@ -"use strict"; - /** * A minimal UTF8 implementation for number arrays. * @memberof util * @namespace */ -var utf8 = module.exports; +const utf8 = module.exports /** * Calculates the UTF8 byte length of a string. @@ -13,22 +11,19 @@ var utf8 = module.exports; * @returns {number} Byte length */ utf8.length = function utf8_length(string) { - var len = 0, - c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { - ++i; - len += 4; - } else - len += 3; - } - return len; -}; + let len = 0 + let c = 0 + for (let i = 0; i < string.length; ++i) { + c = string.charCodeAt(i) + if (c < 128) len += 1 + else if (c < 2048) len += 2 + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i + len += 4 + } else len += 3 + } + return len +} /** * Reads UTF8 bytes as a string. @@ -38,37 +33,32 @@ utf8.length = function utf8_length(string) { * @returns {string} String read */ utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, - chunk = [], - i = 0, // char offset - t; // temporary - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); + const len = end - start + if (len < 1) return '' + let parts = null + const chunk = [] + let i = 0 // char offset + let t // temporary + while (start < end) { + t = buffer[start++] + if (t < 128) chunk[i++] = t + else if (t > 191 && t < 224) chunk[i++] = (t & 31) << 6 | buffer[start++] & 63 + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000 + chunk[i++] = 0xD800 + (t >> 10) + chunk[i++] = 0xDC00 + (t & 1023) + } else chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63 + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)) + i = 0 } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; + } + if (parts) { + if (i) parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))) + return parts.join('') + } + return String.fromCharCode.apply(String, chunk.slice(0, i)) +} /** * Writes a string as UTF8 bytes. @@ -78,28 +68,28 @@ utf8.read = function utf8_read(buffer, start, end) { * @returns {number} Bytes written */ utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, - c1, // character 1 - c2; // character 2 - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { - c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } + const start = offset + let c1 // character 1 + let c2 // character 2 + for (let i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i) + if (c1 < 128) { + buffer[offset++] = c1 + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192 + buffer[offset++] = c1 & 63 | 128 + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF) + ++i + buffer[offset++] = c1 >> 18 | 240 + buffer[offset++] = c1 >> 12 & 63 | 128 + buffer[offset++] = c1 >> 6 & 63 | 128 + buffer[offset++] = c1 & 63 | 128 + } else { + buffer[offset++] = c1 >> 12 | 224 + buffer[offset++] = c1 >> 6 & 63 | 128 + buffer[offset++] = c1 & 63 | 128 } - return offset - start; -}; + } + return offset - start +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/util.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/util.js index 6240e914..fba4ce9b 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/util.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/util.js @@ -1,53 +1,51 @@ /** * Created by zhangmiao on 2018/3/12. */ -var util = module.exports; - -var roots = require("./roots"); -util.LongBits = require("./longBits"); -util.Long = require("./long"); -util.pool = require('./pool'); -util.float = require('./float'); -util.asPromise = require('./asPromise'); -util.EventEmitter = require('./EventEmitter'); -util.path = require('./path'); -util.base64 =require('./base64'); -util.utf8 = require('./utf8'); - -util.compareFieldsById = function compareFieldsById(a, b){ - return a.id - b.id; -}; +const util = module.exports + +const roots = require('./roots') +util.LongBits = require('./longBits') +util.Long = require('./long') +util.pool = require('./pool') +util.float = require('./float') +util.asPromise = require('./asPromise') +util.EventEmitter = require('./EventEmitter') +util.path = require('./path') +util.base64 = require('./base64') +util.utf8 = require('./utf8') + +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id +} util.toArray = function toArray(object) { - if (object) { - var keys = Object.keys(object), - array = new Array(keys.length), - index = 0; - while (index < keys.length) - array[index] = object[keys[index++]]; - return array; - } - return []; -}; + if (object) { + const keys = Object.keys(object) + const array = new Array(keys.length) + let index = 0 + while (index < keys.length) array[index] = object[keys[index++]] + return array + } + return [] +} util.toObject = function toObject(array) { - var object = {}, - index = 0; - while (index < array.length) { - var key = array[index++], - val = array[index++]; - if (val !== undefined) - object[key] = val; - } - return object; -}; + const object = {} + let index = 0 + while (index < array.length) { + const key = array[index++] + const val = array[index++] + if (val !== undefined) object[key] = val + } + return object +} util.isString = function isString(value) { - return typeof value === "string" || value instanceof String; -}; + return typeof value === 'string' || value instanceof String +} -var safePropBackslashRe = /\\/g, - safePropQuoteRe = /"/g; +const safePropBackslashRe = /\\/g +const safePropQuoteRe = /"/g /** * Tests whether the specified name is a reserved word in JS. @@ -55,224 +53,205 @@ var safePropBackslashRe = /\\/g, * @returns {boolean} `true` if reserved, otherwise `false` */ util.isReserved = function isReserved(name) { - return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); -}; + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name) +} util.isObject = function isObject(value) { - return value && typeof value === "object"; -}; + return value && typeof value === 'object' +} -util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; +util.Array = typeof Uint8Array !== 'undefined' ? Uint8Array /* istanbul ignore next */ : Array util.oneOfGetter = function getOneOf(fieldNames) { - var fieldMap = {}; - for (var i = 0; i < fieldNames.length; ++i) - fieldMap[fieldNames[i]] = 1; + const fieldMap = {} + for (let i = 0; i < fieldNames.length; ++i) fieldMap[fieldNames[i]] = 1 - /** + /** * @returns {string|undefined} Set field name, if any * @this Object * @ignore */ - return function() { // eslint-disable-line consistent-return - for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) - if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) - return keys[i]; - }; -}; + return function () { // eslint-disable-line consistent-return + for (let keys = Object.keys(this), i = keys.length - 1; i > -1; --i) if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) return keys[i] + } +} util.oneOfSetter = function setOneOf(fieldNames) { - - /** + /** * @param {string} name Field name * @returns {undefined} * @this Object * @ignore */ - return function(name) { - for (var i = 0; i < fieldNames.length; ++i) - if (fieldNames[i] !== name) - delete this[/*"_"+*/fieldNames[i]];//设置为私有属性 - }; -}; - + return function (name) { + for (let i = 0; i < fieldNames.length; ++i) if (fieldNames[i] !== name) delete this[/* "_"+*/fieldNames[i]]// 设置为私有属性 + } +} util.merge = function merge(dst, src, ifNotSet) { // used by converters - for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) - if (dst[keys[i]] === undefined || !ifNotSet) - dst[keys[i]] = src[keys[i]]; - return dst; -}; + for (let keys = Object.keys(src), i = 0; i < keys.length; ++i) if (dst[keys[i]] === undefined || !ifNotSet) dst[keys[i]] = src[keys[i]] + return dst +} util.decorateType = function decorateType(ctor, typeName) { - - /* istanbul ignore if */ - if (ctor.$type) { - if (typeName && ctor.$type.name !== typeName) { - util.decorateRoot.remove(ctor.$type); - ctor.$type.name = typeName; - util.decorateRoot.add(ctor.$type); - } - return ctor.$type; + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type) + ctor.$type.name = typeName + util.decorateRoot.add(ctor.$type) } + return ctor.$type + } + + /* istanbul ignore next */ + if (!Type) Type = require('./type') + + const type = new Type(typeName || ctor.name) + util.decorateRoot.add(type) + type.ctor = ctor // sets up .encode, .decode etc. + Object.defineProperty(ctor, '$type', {value: type, enumerable: false}) + Object.defineProperty(ctor.prototype, '$type', {value: type, enumerable: false}) + return type +} - /* istanbul ignore next */ - if (!Type) - Type = require("./type"); - - var type = new Type(typeName || ctor.name); - util.decorateRoot.add(type); - type.ctor = ctor; // sets up .encode, .decode etc. - Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); - Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); - return type; -}; - -util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ [] // used on prototypes -util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {} // used on prototypes util.longToHash = function longToHash(value) { - return value - ? util.LongBits.from(value).toHash() - : util.LongBits.zeroHash; -}; - -util.copy = function(obj){ - if(typeof obj != 'object'){ - return obj; - } - var newObj = {}; - for (var attr in obj) { - newObj[attr] = obj[attr]; - } - return newObj; -}; - -function deepCopy(obj){ - if(typeof obj != 'object'){ - return obj; - } - var newobj = {}; - for ( var attr in obj) { - newobj[attr] = deepCopy(obj[attr]); - } - return newobj; + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash } -util.deepCopy = deepCopy; +util.copy = function (obj) { + if (typeof obj !== 'object') { + return obj + } + const newObj = {} + for (const attr in obj) { + newObj[attr] = obj[attr] + } + return newObj +} -util.ProtocolError =function newError(name) { +function deepCopy(obj) { + if (typeof obj !== 'object') { + return obj + } + const newobj = {} + for (const attr in obj) { + newobj[attr] = deepCopy(obj[attr]) + } + return newobj +} - function CustomError(message, properties) { +util.deepCopy = deepCopy - if (!(this instanceof CustomError)) - return new CustomError(message, properties); +util.ProtocolError = function newError(name) { + function CustomError(message, properties) { + if (!(this instanceof CustomError)) return new CustomError(message, properties) - // Error.call(this, message); - // ^ just returns a new error instance because the ctor can be called as a function + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function - Object.defineProperty(this, "message", { get: function() { return message; } }); + Object.defineProperty(this, 'message', {get() { return message }}) - /* istanbul ignore next */ - if (Error.captureStackTrace) // node - Error.captureStackTrace(this, CustomError); - else - Object.defineProperty(this, "stack", { value: (new Error()).stack || "" }); + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + { Error.captureStackTrace(this, CustomError) } else Object.defineProperty(this, 'stack', {value: (new Error()).stack || ''}) - if (properties) - merge(this, properties); - } + if (properties) merge(this, properties) + } - (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; + (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError - Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } }); + Object.defineProperty(CustomError.prototype, 'name', {get() { return name }}) - CustomError.prototype.toString = function toString() { - return this.name + ": " + this.message; - }; + CustomError.prototype.toString = function toString() { + return this.name + ': ' + this.message + } - return CustomError; + return CustomError } util.toJSONOptions = { - longs: String, - enums: String, - bytes: String, - json: true -}; - -util.Buffer = (function() { - return null; -})(); + longs: String, + enums: String, + bytes: String, + json: true +} +util.Buffer = (function () { + return null +}()) util.newBuffer = function newBuffer(sizeOrArray) { - /* istanbul ignore next */ - return typeof sizeOrArray === "number" - ? new util.Array(sizeOrArray) - : typeof Uint8Array === "undefined" - ? sizeOrArray - : new Uint8Array(sizeOrArray); -}; - -util.stringToBytes =function stringToBytes( str ) { - var bytes = []; - var len, c; - len = str.length; - for(var i = 0; i < len; i++) { - c = str.charCodeAt(i); - if(c >= 0x010000 && c <= 0x10FFFF) { - bytes.push(((c >> 18) & 0x07) | 0xF0); - bytes.push(((c >> 12) & 0x3F) | 0x80); - bytes.push(((c >> 6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000800 && c <= 0x00FFFF) { - bytes.push(((c >> 12) & 0x0F) | 0xE0); - bytes.push(((c >> 6) & 0x3F) | 0x80); - bytes.push((c & 0x3F) | 0x80); - } else if(c >= 0x000080 && c <= 0x0007FF) { - bytes.push(((c >> 6) & 0x1F) | 0xC0); - bytes.push((c & 0x3F) | 0x80); - } else { - bytes.push(c & 0xFF); - } - } - return bytes; + /* istanbul ignore next */ + return typeof sizeOrArray === 'number' + ? new util.Array(sizeOrArray) + : typeof Uint8Array === 'undefined' + ? sizeOrArray + : new Uint8Array(sizeOrArray) +} -}; +util.stringToBytes = function stringToBytes(str) { + const bytes = [] + let len; let + c + len = str.length + for (let i = 0; i < len; i++) { + c = str.charCodeAt(i) + if (c >= 0x010000 && c <= 0x10FFFF) { + bytes.push(((c >> 18) & 0x07) | 0xF0) + bytes.push(((c >> 12) & 0x3F) | 0x80) + bytes.push(((c >> 6) & 0x3F) | 0x80) + bytes.push((c & 0x3F) | 0x80) + } else if (c >= 0x000800 && c <= 0x00FFFF) { + bytes.push(((c >> 12) & 0x0F) | 0xE0) + bytes.push(((c >> 6) & 0x3F) | 0x80) + bytes.push((c & 0x3F) | 0x80) + } else if (c >= 0x000080 && c <= 0x0007FF) { + bytes.push(((c >> 6) & 0x1F) | 0xC0) + bytes.push((c & 0x3F) | 0x80) + } else { + bytes.push(c & 0xFF) + } + } + return bytes +} util.byteToString = function byteToString(arr) { - if(typeof arr === 'string') { - return arr; + if (typeof arr === 'string') { + return arr + } + let str = '' + const _arr = arr + for (let i = 0; i < _arr.length; i++) { + const one = _arr[i].toString(2) + const v = one.match(/^1+?(?=0)/) + if (v && one.length == 8) { + const bytesLength = v[0].length + let store = _arr[i].toString(2).slice(7 - bytesLength) + for (let st = 1; st < bytesLength; st++) { + store += _arr[st + i].toString(2).slice(2) + } + str += String.fromCharCode(parseInt(store, 2)) + i += bytesLength - 1 + } else { + str += String.fromCharCode(_arr[i]) } - var str = '', - _arr = arr; - for(var i = 0; i < _arr.length; i++) { - var one = _arr[i].toString(2), - v = one.match(/^1+?(?=0)/); - if(v && one.length == 8) { - var bytesLength = v[0].length; - var store = _arr[i].toString(2).slice(7 - bytesLength); - for(var st = 1; st < bytesLength; st++) { - store += _arr[st + i].toString(2).slice(2); - } - str += String.fromCharCode(parseInt(store, 2)); - i += bytesLength - 1; - } else { - str += String.fromCharCode(_arr[i]); - } - } - return str; + } + return str } - util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { - return typeof value === "number" && isFinite(value) && Math.floor(value) === value; - }; + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value +} -Object.defineProperty(util, "decorateRoot", { - get: function() { - return roots["decorated"] || (roots["decorated"] = new (require("./root"))()); - } -}); +Object.defineProperty(util, 'decorateRoot', { + get() { + return roots.decorated || (roots.decorated = new (require('./root'))()) + } +}) diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/verifier.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/verifier.js index 933d7548..bebeddbc 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/verifier.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/verifier.js @@ -1,157 +1,142 @@ /** * Created by zhangmiao on 2018/3/14. */ -module.exports = verifier; +module.exports = verifier -var Enum; -var util; +let Enum +let util function invalid(field, expected) { - return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; + return field.name + ': ' + expected + (field.repeated && expected !== 'array' ? '[]' : field.map && expected !== 'object' ? '{k:' + field.keyType + '}' : '') + ' expected' } -function verifyValue(field, fieldIndex, ref, options){ - var _types = options.types; - if(field.resolvedType){ - if(field.resolvedType instanceof Enum){ - var keys = Object.keys(field.resolvedType.values); - if (keys.indexOf(ref)<0){ - //没有找到时候 - return invalid(field, "enum value"); - } - }else { - var e = _types[fieldIndex].verify(ref); - if(e) - return field.name + "."+ e; - } +function verifyValue(field, fieldIndex, ref, options) { + const _types = options.types + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { + const keys = Object.keys(field.resolvedType.values) + if (keys.indexOf(ref) < 0) { + // 没有找到时候 + return invalid(field, 'enum value') + } } else { - switch (field.type) { - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": - if (!util.isInteger(ref)) - return invalid(field, "integer"); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": - if(!util.isInteger(ref)&&!(ref&&util.isInteger(ref.low)&&util.isInteger(ref.high))) - return invalid(field, "integer|Long"); - break; - case "float": - case "double": - if(typeof ref!=="number") - return invalid(field, "number"); - break; - case "bool": - if(typeof ref!=="boolean") - return invalid(field, "boolean"); - break; - case "string": - if(!util.isString(ref)) - return invalid(field, "string"); - break; - case "bytes": - if(!(ref&&typeof ref.length==="number"||util.isString(ref))) - return invalid(field, "buffer"); - break; - } + const e = _types[fieldIndex].verify(ref) + if (e) return field.name + '.' + e } + } else { + switch (field.type) { + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + if (!util.isInteger(ref)) return invalid(field, 'integer') + break + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (!util.isInteger(ref) && !(ref && util.isInteger(ref.low) && util.isInteger(ref.high))) return invalid(field, 'integer|Long') + break + case 'float': + case 'double': + if (typeof ref !== 'number') return invalid(field, 'number') + break + case 'bool': + if (typeof ref !== 'boolean') return invalid(field, 'boolean') + break + case 'string': + if (!util.isString(ref)) return invalid(field, 'string') + break + case 'bytes': + if (!(ref && typeof ref.length === 'number' || util.isString(ref))) return invalid(field, 'buffer') + break + } + } } -function verifyKey(field, ref){ - switch(field.keyType){ - case "int32": - case "uint32": - case "sint32": - case "fixed32": - case "sfixed32": - if(!util.key32Re.test(ref)) - return invalid(field, "integer key"); - break; - case "int64": - case "uint64": - case "sint64": - case "fixed64": - case "sfixed64": - if(!util.key64Re.test(ref)) - return invalid(field, "integer|Long key"); - break; - case "bool": - if(!util.key2Re.test(ref)) - return invalid(field, "boolean key"); - break; - } +function verifyKey(field, ref) { + switch (field.keyType) { + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + if (!util.key32Re.test(ref)) return invalid(field, 'integer key') + break + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (!util.key64Re.test(ref)) return invalid(field, 'integer|Long key') + break + case 'bool': + if (!util.key2Re.test(ref)) return invalid(field, 'boolean key') + break + } } -function verifier(mtype){ - return function (options){ - return function (m){ - var invalidDes; - if(typeof m !== 'object' || m === null) - return "object expected"; +function verifier(mtype) { + return function (options) { + return function (m) { + let invalidDes + if (typeof m !== 'object' || m === null) return 'object expected' - var oneofs = mtype.oneofsArray, - seenFirstField = {}; - var p; - if(oneofs.length) - p = {}; - for (var i = 0; i < mtype.fieldsArray.length; ++i){ - var field = mtype._fieldsArray[i].resolve(), - ref = m[field.name]; - if(!field.optional || (ref!=null&& m.hasOwnProperty(field.name))){ - var _i; - if (field.map){ - if(!util.isObject(ref)) - return invalid(field, "object"); - var k=Object.keys(ref); - for (_i = 0; _i < k.length; ++_i){ - //检查key值的合法性 - invalidDes = verifyKey(field, k[_i]); - if(invalidDes){ - return invalidDes; - } - //检查value值的合法性 - invalidDes = verifyValue(field, i, ref[k[_i]], options); - if(invalidDes){ - return invalidDes; - } - } - } else if(field.repeated){ - if(!Array.isArray(ref)){ - return invalid(field, "array"); - } + const oneofs = mtype.oneofsArray + const seenFirstField = {} + let p + if (oneofs.length) p = {} + for (let i = 0; i < mtype.fieldsArray.length; ++i) { + const field = mtype._fieldsArray[i].resolve() + const ref = m[field.name] + if (!field.optional || (ref != null && m.hasOwnProperty(field.name))) { + var _i + if (field.map) { + if (!util.isObject(ref)) return invalid(field, 'object') + const k = Object.keys(ref) + for (_i = 0; _i < k.length; ++_i) { + // 检查key值的合法性 + invalidDes = verifyKey(field, k[_i]) + if (invalidDes) { + return invalidDes + } + // 检查value值的合法性 + invalidDes = verifyValue(field, i, ref[k[_i]], options) + if (invalidDes) { + return invalidDes + } + } + } else if (field.repeated) { + if (!Array.isArray(ref)) { + return invalid(field, 'array') + } - for (_i = 0; _i < ref.length; ++_i) { - invalidDes = verifyValue(field, i, ref[_i], options); - if(invalidDes){ - return invalidDes; - } - } - } else { - if(field.partOf) { - var oneofPropName = field.partOf.name; - if (seenFirstField[field.partOf.name] === 1) - if(p[oneofPropName] === 1) - return field.partOf.name + ": multiple values"; - p[oneofPropName] = 1 - } - invalidDes = verifyValue(field, i, ref, options); - if(invalidDes){ - return invalidDes; - } - } - } + for (_i = 0; _i < ref.length; ++_i) { + invalidDes = verifyValue(field, i, ref[_i], options) + if (invalidDes) { + return invalidDes + } + } + } else { + if (field.partOf) { + const oneofPropName = field.partOf.name + if (seenFirstField[field.partOf.name] === 1) if (p[oneofPropName] === 1) return field.partOf.name + ': multiple values' + p[oneofPropName] = 1 } + invalidDes = verifyValue(field, i, ref, options) + if (invalidDes) { + return invalidDes + } + } } + } } + } } -verifier._configure = function(){ - Enum = require("./enum"); - util = require("./util"); -}; \ No newline at end of file +verifier._configure = function () { + Enum = require('./enum') + util = require('./util') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/wrappers.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/wrappers.js index 0df56cca..f3cee937 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/wrappers.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/wrappers.js @@ -1,7 +1,6 @@ -var wrappers = exports; +const wrappers = exports - -var Message; +let Message /** * From object converter part of an {@link IWrapper}. @@ -30,52 +29,49 @@ var Message; */ // Custom wrapper for Any -wrappers[".google.protobuf.Any"] = { - - fromObject: function(object) { - - // unwrap value type if mapped - if (object && object["@type"]) { - var type = this.lookup(object["@type"]); - /* istanbul ignore else */ - if (type) { - // type_url does not accept leading "." - var type_url = object["@type"].charAt(0) === "." ? - object["@type"].substr(1) : object["@type"]; - // type_url prefix is optional, but path seperator is required - return this.create({ - type_url: "/" + type_url, - value: type.encode(type.fromObject(object)).finish() - }); - } - } - - return this.fromObject(object); - }, +wrappers['.google.protobuf.Any'] = { - toObject: function(message, options) { + fromObject(object) { + // unwrap value type if mapped + if (object && object['@type']) { + const type = this.lookup(object['@type']) + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + const type_url = object['@type'].charAt(0) === '.' + ? object['@type'].substr(1) : object['@type'] + // type_url prefix is optional, but path seperator is required + return this.create({ + type_url: '/' + type_url, + value: type.encode(type.fromObject(object)).finish() + }) + } + } - // decode value if requested and unmapped - if (options && options.json && message.type_url && message.value) { - // Only use fully qualified type name after the last '/' - var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); - var type = this.lookup(name); - /* istanbul ignore else */ - if (type) - message = type.decode(message.value); - } + return this.fromObject(object) + }, - // wrap value if unmapped - if (!(message instanceof this.ctor) && message instanceof Message) { - var object = message.$type.toObject(message, options); - object["@type"] = message.$type.fullName; - return object; - } + toObject(message, options) { + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + const name = message.type_url.substring(message.type_url.lastIndexOf('/') + 1) + const type = this.lookup(name) + /* istanbul ignore else */ + if (type) message = type.decode(message.value) + } - return this.toObject(message, options); + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + const object = message.$type.toObject(message, options) + object['@type'] = message.$type.fullName + return object } -}; + + return this.toObject(message, options) + } +} wrappers._configure = function () { - Message = require("./message"); -} \ No newline at end of file + Message = require('./message') +} diff --git a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/writer.js b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/writer.js index 2866ee0c..fcd59821 100644 --- a/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/writer.js +++ b/miniprogram/packageAPI/pages/ar/3dmarker-ar/protobuf/src/writer.js @@ -1,13 +1,13 @@ -module.exports = Writer; +module.exports = Writer +const util = require('./util') -var util = require('./util'); -var LongBits; +let LongBits -var BufferWriter; // cyclic +let BufferWriter // cyclic -var base64; -var utf8 = require('./utf8'); +let base64 +let utf8 = require('./utf8') /** * Constructs a new writer operation instance. @@ -19,30 +19,29 @@ var utf8 = require('./utf8'); * @ignore */ function Op(fn, len, val) { - - /** + /** * Function to call. * @type {function(Uint8Array, number, *)} */ - this.fn = fn; + this.fn = fn - /** + /** * Value byte length. * @type {number} */ - this.len = len; + this.len = len - /** + /** * Next operation. * @type {Writer.Op|undefined} */ - this.next = undefined; + this.next = undefined - /** + /** * Value to write. * @type {*} */ - this.val = val; // type varies + this.val = val // type varies } /* istanbul ignore next */ @@ -57,30 +56,29 @@ function noop() {} // eslint-disable-line no-empty-function * @ignore */ function State(writer) { - - /** + /** * Current head. * @type {Writer.Op} */ - this.head = writer.head; + this.head = writer.head - /** + /** * Current tail. * @type {Writer.Op} */ - this.tail = writer.tail; + this.tail = writer.tail - /** + /** * Current buffer length. * @type {number} */ - this.len = writer.len; + this.len = writer.len - /** + /** * Next state. * @type {State|null} */ - this.next = writer.states; + this.next = writer.states } /** @@ -89,36 +87,35 @@ function State(writer) { * @constructor */ function Writer() { - - /** + /** * Current length. * @type {number} */ - this.len = 0; + this.len = 0 - /** + /** * Operations head. * @type {Object} */ - this.head = new Op(noop, 0, 0); + this.head = new Op(noop, 0, 0) - /** + /** * Operations tail * @type {Object} */ - this.tail = this.head; + this.tail = this.head - /** + /** * Linked forked states. * @type {Object|null} */ - this.states = null; + this.states = null - // When a value is written, the writer calculates its byte length and puts it into a linked - // list of operations to perform when finish() is called. This both allows us to allocate - // buffers of the exact required size and reduces the amount of work we have to do compared - // to first calculating over objects and then encoding over objects. In our case, the encoding - // part is just a linked list walk calling operations with already prepared values. + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. } /** @@ -127,15 +124,15 @@ function Writer() { * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} */ Writer.create = util.Buffer - ? function create_buffer_setup() { + ? function create_buffer_setup() { return (Writer.create = function create_buffer() { - return new BufferWriter(); - })(); -} - /* istanbul ignore next */ - : function create_array() { - return new Writer(); -}; + return new BufferWriter() + })() + } +/* istanbul ignore next */ + : function create_array() { + return new Writer() + } /** * Allocates a buffer of the specified size. @@ -143,13 +140,12 @@ Writer.create = util.Buffer * @returns {Uint8Array} Buffer */ Writer.alloc = function alloc(size) { - return new util.Array(size); -}; + return new util.Array(size) +} // Use Uint8Array buffer pool in the browser, just like node does with buffers /* istanbul ignore else */ -if (util.Array !== Array) - Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); +if (util.Array !== Array) Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray) /** * Pushes a new operation to the queue. @@ -160,21 +156,21 @@ if (util.Array !== Array) * @private */ Writer.prototype._push = function push(fn, len, val) { - this.tail = this.tail.next = new Op(fn, len, val); - this.len += len; - return this; -}; + this.tail = this.tail.next = new Op(fn, len, val) + this.len += len + return this +} function writeByte(val, buf, pos) { - buf[pos] = val & 255; + buf[pos] = val & 255 } function writeVarint32(val, buf, pos) { - while (val > 127) { - buf[pos++] = val & 127 | 128; - val >>>= 7; - } - buf[pos] = val; + while (val > 127) { + buf[pos++] = val & 127 | 128 + val >>>= 7 + } + buf[pos] = val } /** @@ -187,13 +183,13 @@ function writeVarint32(val, buf, pos) { * @ignore */ function VarintOp(len, val) { - this.len = len; - this.next = undefined; - this.val = val; + this.len = len + this.next = undefined + this.val = val } -VarintOp.prototype = Object.create(Op.prototype); -VarintOp.prototype.fn = writeVarint32; +VarintOp.prototype = Object.create(Op.prototype) +VarintOp.prototype.fn = writeVarint32 /** * Writes an unsigned 32 bit value as a varint. @@ -201,18 +197,19 @@ VarintOp.prototype.fn = writeVarint32; * @returns {Writer} `this` */ Writer.prototype.uint32 = function write_uint32(value) { - // here, the call to this.push has been inlined and a varint specific Op subclass is used. - // uint32 is by far the most frequently used operation and benefits significantly from this. - this.len += (this.tail = this.tail.next = new VarintOp( - (value = value >>> 0) //将有符号的数变为无符号的数 - < 128 ? 1 //2的7次方 - : value < 16384 ? 2 //2的14次方 - : value < 2097152 ? 3 //2的21次方 - : value < 268435456 ? 4 //2的28次方 - : 5, //2的35次方 最多32次方,所以最多是5 - value)).len; - return this; -}; + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value >>>= 0) < // 将有符号的数变为无符号的数 + 128 ? 1 // 2的7次方 + : value < 16384 ? 2 // 2的14次方 + : value < 2097152 ? 3 // 2的21次方 + : value < 268435456 ? 4 // 2的28次方 + : 5, // 2的35次方 最多32次方,所以最多是5 + value + )).len + return this +} /** * Writes a signed 32 bit value as a varint. @@ -221,10 +218,10 @@ Writer.prototype.uint32 = function write_uint32(value) { * @returns {Writer} `this` */ Writer.prototype.int32 = function write_int32(value) { - return value < 0 - ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec - : this.uint32(value); -}; + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value) +} /** * Writes a 32 bit value as a varint, zig-zag encoded. @@ -232,20 +229,20 @@ Writer.prototype.int32 = function write_int32(value) { * @returns {Writer} `this` */ Writer.prototype.sint32 = function write_sint32(value) { - return this.uint32((value << 1 ^ value >> 31) >>> 0); -}; + return this.uint32((value << 1 ^ value >> 31) >>> 0) +} function writeVarint64(val, buf, pos) { - while (val.hi) { - buf[pos++] = val.lo & 127 | 128; - val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; - val.hi >>>= 7; - } - while (val.lo > 127) { - buf[pos++] = val.lo & 127 | 128; - val.lo = val.lo >>> 7; - } - buf[pos++] = val.lo; + while (val.hi) { + buf[pos++] = val.lo & 127 | 128 + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0 + val.hi >>>= 7 + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128 + val.lo >>>= 7 + } + buf[pos++] = val.lo } /** @@ -255,9 +252,9 @@ function writeVarint64(val, buf, pos) { * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.uint64 = function write_uint64(value) { - var bits = LongBits.from(value); - return this._push(writeVarint64, bits.length(), bits); -}; + const bits = LongBits.from(value) + return this._push(writeVarint64, bits.length(), bits) +} /** * Writes a signed 64 bit value as a varint. @@ -266,7 +263,7 @@ Writer.prototype.uint64 = function write_uint64(value) { * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ -Writer.prototype.int64 = Writer.prototype.uint64; +Writer.prototype.int64 = Writer.prototype.uint64 /** * Writes a signed 64 bit value as a varint, zig-zag encoded. @@ -275,9 +272,9 @@ Writer.prototype.int64 = Writer.prototype.uint64; * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.sint64 = function write_sint64(value) { - var bits = LongBits.from(value).zzEncode(); - return this._push(writeVarint64, bits.length(), bits); -}; + const bits = LongBits.from(value).zzEncode() + return this._push(writeVarint64, bits.length(), bits) +} /** * Writes a boolish value as a varint. @@ -285,14 +282,14 @@ Writer.prototype.sint64 = function write_sint64(value) { * @returns {Writer} `this` */ Writer.prototype.bool = function write_bool(value) { - return this._push(writeByte, 1, value ? 1 : 0); -}; + return this._push(writeByte, 1, value ? 1 : 0) +} function writeFixed32(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; + buf[pos] = val & 255 + buf[pos + 1] = val >>> 8 & 255 + buf[pos + 2] = val >>> 16 & 255 + buf[pos + 3] = val >>> 24 } /** @@ -301,8 +298,8 @@ function writeFixed32(val, buf, pos) { * @returns {Writer} `this` */ Writer.prototype.fixed32 = function write_fixed32(value) { - return this._push(writeFixed32, 4, value >>> 0); -}; + return this._push(writeFixed32, 4, value >>> 0) +} /** * Writes a signed 32 bit value as fixed 32 bits. @@ -310,7 +307,7 @@ Writer.prototype.fixed32 = function write_fixed32(value) { * @param {number} value Value to write * @returns {Writer} `this` */ -Writer.prototype.sfixed32 = Writer.prototype.fixed32; +Writer.prototype.sfixed32 = Writer.prototype.fixed32 /** * Writes an unsigned 64 bit value as fixed 64 bits. @@ -319,9 +316,9 @@ Writer.prototype.sfixed32 = Writer.prototype.fixed32; * @throws {TypeError} If `value` is a string and no long library is present. */ Writer.prototype.fixed64 = function write_fixed64(value) { - var bits = LongBits.from(value); - return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); -}; + const bits = LongBits.from(value) + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi) +} /** * Writes a signed 64 bit value as fixed 64 bits. @@ -330,7 +327,7 @@ Writer.prototype.fixed64 = function write_fixed64(value) { * @returns {Writer} `this` * @throws {TypeError} If `value` is a string and no long library is present. */ -Writer.prototype.sfixed64 = Writer.prototype.fixed64; +Writer.prototype.sfixed64 = Writer.prototype.fixed64 /** * Writes a float (32 bit). @@ -339,8 +336,8 @@ Writer.prototype.sfixed64 = Writer.prototype.fixed64; * @returns {Writer} `this` */ Writer.prototype.float = function write_float(value) { - return this._push(util.float.writeFloatLE, 4, value); -}; + return this._push(util.float.writeFloatLE, 4, value) +} /** * Writes a double (64 bit float). @@ -349,18 +346,17 @@ Writer.prototype.float = function write_float(value) { * @returns {Writer} `this` */ Writer.prototype.double = function write_double(value) { - return this._push(util.float.writeDoubleLE, 8, value); -}; - -var writeBytes = util.Array.prototype.set - ? function writeBytes_set(val, buf, pos) { - buf.set(val, pos); // also works for plain array values + return this._push(util.float.writeDoubleLE, 8, value) } - /* istanbul ignore next */ - : function writeBytes_for(val, buf, pos) { - for (var i = 0; i < val.length; ++i) - buf[pos + i] = val[i]; -}; + +const writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos) // also works for plain array values + } +/* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (let i = 0; i < val.length; ++i) buf[pos + i] = val[i] + } /** * Writes a sequence of bytes. @@ -368,21 +364,20 @@ var writeBytes = util.Array.prototype.set * @returns {Writer} `this` */ Writer.prototype.bytes = function write_bytes(value) { - var len = value.length >>> 0; - if (!len) - return this._push(writeByte, 1, 0); - - if (util.isString(value)) { - //len = (value = util.stringToBytes(value)).length; - //var buf = Writer.alloc(len = base64.length(value)); - //base64.decode(value, buf, 0); - //value = buf; - var buf = Writer.alloc(len = utf8.length(value)); - utf8.write(value, buf, 0); - value = buf; - } - return this.uint32(len)._push(writeBytes, len, value); -}; + let len = value.length >>> 0 + if (!len) return this._push(writeByte, 1, 0) + + if (util.isString(value)) { + // len = (value = util.stringToBytes(value)).length; + // var buf = Writer.alloc(len = base64.length(value)); + // base64.decode(value, buf, 0); + // value = buf; + const buf = Writer.alloc(len = utf8.length(value)) + utf8.write(value, buf, 0) + value = buf + } + return this.uint32(len)._push(writeBytes, len, value) +} /** * Writes a string. @@ -390,11 +385,11 @@ Writer.prototype.bytes = function write_bytes(value) { * @returns {Writer} `this` */ Writer.prototype.string = function write_string(value) { - var len = utf8.length(value); - return len - ? this.uint32(len)._push(utf8.write, len, value) - : this._push(writeByte, 1, 0); -}; + const len = utf8.length(value) + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0) +} /** * Forks this writer's state by pushing it to a stack. @@ -402,67 +397,66 @@ Writer.prototype.string = function write_string(value) { * @returns {Writer} `this` */ Writer.prototype.fork = function fork() { - this.states = new State(this); - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - return this; -}; + this.states = new State(this) + this.head = this.tail = new Op(noop, 0, 0) + this.len = 0 + return this +} /** * Resets this instance to the last state. * @returns {Writer} `this` */ Writer.prototype.reset = function reset() { - if (this.states) { - this.head = this.states.head; - this.tail = this.states.tail; - this.len = this.states.len; - this.states = this.states.next; - } else { - this.head = this.tail = new Op(noop, 0, 0); - this.len = 0; - } - return this; -}; + if (this.states) { + this.head = this.states.head + this.tail = this.states.tail + this.len = this.states.len + this.states = this.states.next + } else { + this.head = this.tail = new Op(noop, 0, 0) + this.len = 0 + } + return this +} /** * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. * @returns {Writer} `this` */ Writer.prototype.ldelim = function ldelim() { - var head = this.head, - tail = this.tail, - len = this.len; - this.reset().uint32(len); - if (len) { - this.tail.next = head.next; // skip noop - this.tail = tail; - this.len += len; - } - return this; -}; + const head = this.head + const tail = this.tail + const len = this.len + this.reset().uint32(len) + if (len) { + this.tail.next = head.next // skip noop + this.tail = tail + this.len += len + } + return this +} /** * Finishes the write operation. * @returns {Uint8Array} Finished buffer */ Writer.prototype.finish = function finish() { - var head = this.head.next, // skip noop - buf = this.constructor.alloc(this.len), - pos = 0; - while (head) { - head.fn(head.val, buf, pos); - pos += head.len; - head = head.next; - } - // this.head = this.tail = null; - return buf; -}; - -Writer._configure = function() { - - //util = require("./util"); - LongBits = require("./longBits"); - base64 = require('./base64'); - utf8 = require('./utf8'); -}; + let head = this.head.next // skip noop + const buf = this.constructor.alloc(this.len) + let pos = 0 + while (head) { + head.fn(head.val, buf, pos) + pos += head.len + head = head.next + } + // this.head = this.tail = null; + return buf +} + +Writer._configure = function () { + // util = require("./util"); + LongBits = require('./longBits') + base64 = require('./base64') + utf8 = require('./utf8') +} 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..a7a0b5a2 100644 --- a/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js +++ b/miniprogram/packageAPI/pages/ar/behavior/behavior-three.js @@ -1,48 +1,48 @@ -import { createScopedThreejs } from 'threejs-miniprogram' -import { registerGLTFLoader } from '../loaders/gltf-loader' +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..21f56bac 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..536615c6 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,7 +68,7 @@ Component({ // VKSession EVENT resize session.on('resize', () => { - this.calcCanvasSize(); + this.calcCanvasSize() }) // 开启躯体三维识别 @@ -76,14 +76,14 @@ Component({ // 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..b7dce9d0 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..afcbe9dd 100644 --- a/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js +++ b/miniprogram/packageAPI/pages/ar/components/xr-frame-render/index.js @@ -10,13 +10,13 @@ Component({ lifetimes: {}, methods: { handleReady({detail}) { - const xrScene = this.scene = detail.value; - console.log('xr-scene', xrScene); + 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..56a054e6 100644 --- a/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js +++ b/miniprogram/packageAPI/pages/ar/components/xr-frame/index.js @@ -10,22 +10,22 @@ Component({ lifetimes: {}, methods: { handleReady({detail}) { - const xrScene = this.scene = detail.value; - console.log('xr-scene', xrScene); + 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..82a68b40 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,7 +70,7 @@ Component({ // VKSession EVENT resize session.on('resize', () => { - this.calcCanvasSize(); + this.calcCanvasSize() }) // 开启三维识别 @@ -78,111 +78,105 @@ Component({ // 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..8ee91dd1 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,7 +68,7 @@ Component({ // VKSession EVENT resize session.on('resize', () => { - this.calcCanvasSize(); + this.calcCanvasSize() }) // 开启三维识别 @@ -76,156 +76,150 @@ Component({ // 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..5bc29501 100644 --- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js +++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting-ar.js @@ -1,25 +1,26 @@ -import { loadPly } from './loaders/ply/ply-loader' -import { loadSplat } from './loaders/splat/splat-loader' +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 + +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..d186c344 100644 --- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js +++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/gaussian-splatting.js @@ -1,22 +1,23 @@ -import { loadPly } from './loaders/ply/ply-loader' -import { loadSplat } from './loaders/splat/splat-loader' +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 {mat4} = glMatrix -const baseMatrix = mat4.create(); +const renderScale = 1 + +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..b6660917 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 @@ -1,120 +1,123 @@ -import { wxDecodeAdapter, computeCov3D } from '../util-loader.js' +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..c25f6e35 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' +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..cd807e63 100644 --- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js +++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/loaders/util-loader.js @@ -1,6 +1,6 @@ import * as glMatrix from '../util/gl-matrix-min' -const { mat3 } = glMatrix +const {mat3} = glMatrix const tmp = mat3.create() const S = mat3.create() const R = mat3.create() @@ -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/gl-matrix-min.js b/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/gl-matrix-min.js index 63ed7904..0ba617b7 100644 --- a/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/gl-matrix-min.js +++ b/miniprogram/packageAPI/pages/ar/gaussian-splatting/util/gl-matrix-min.js @@ -25,4 +25,26 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).glMatrix={})}(this,(function(t){"use strict";var n=1e-6,a="undefined"!=typeof Float32Array?Float32Array:Array,r=Math.random,u="zyx";var e=Math.PI/180;Math.hypot||(Math.hypot=function(){for(var t=0,n=arguments.length;n--;)t+=arguments[n]*arguments[n];return Math.sqrt(t)});var o=Object.freeze({__proto__:null,EPSILON:n,get ARRAY_TYPE(){return a},RANDOM:r,ANGLE_ORDER:u,setMatrixArrayType:function(t){a=t},toRadian:function(t){return t*e},equals:function(t,a){return Math.abs(t-a)<=n*Math.max(1,Math.abs(t),Math.abs(a))}});function i(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=a[0],h=a[1],c=a[2],s=a[3];return t[0]=r*i+e*h,t[1]=u*i+o*h,t[2]=r*c+e*s,t[3]=u*c+o*s,t}function h(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t[2]=n[2]-a[2],t[3]=n[3]-a[3],t}var c=i,s=h,M=Object.freeze({__proto__:null,create:function(){var t=new a(4);return a!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t},clone:function(t){var n=new a(4);return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n},copy:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t},fromValues:function(t,n,r,u){var e=new a(4);return e[0]=t,e[1]=n,e[2]=r,e[3]=u,e},set:function(t,n,a,r,u){return t[0]=n,t[1]=a,t[2]=r,t[3]=u,t},transpose:function(t,n){if(t===n){var a=n[1];t[1]=n[2],t[2]=a}else t[0]=n[0],t[1]=n[2],t[2]=n[1],t[3]=n[3];return t},invert:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=a*e-u*r;return o?(o=1/o,t[0]=e*o,t[1]=-r*o,t[2]=-u*o,t[3]=a*o,t):null},adjoint:function(t,n){var a=n[0];return t[0]=n[3],t[1]=-n[1],t[2]=-n[2],t[3]=a,t},determinant:function(t){return t[0]*t[3]-t[2]*t[1]},multiply:i,rotate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=Math.sin(a),h=Math.cos(a);return t[0]=r*h+e*i,t[1]=u*h+o*i,t[2]=r*-i+e*h,t[3]=u*-i+o*h,t},scale:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=a[0],h=a[1];return t[0]=r*i,t[1]=u*i,t[2]=e*h,t[3]=o*h,t},fromRotation:function(t,n){var a=Math.sin(n),r=Math.cos(n);return t[0]=r,t[1]=a,t[2]=-a,t[3]=r,t},fromScaling:function(t,n){return t[0]=n[0],t[1]=0,t[2]=0,t[3]=n[1],t},str:function(t){return"mat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"},frob:function(t){return Math.hypot(t[0],t[1],t[2],t[3])},LDU:function(t,n,a,r){return t[2]=r[2]/r[0],a[0]=r[0],a[1]=r[1],a[3]=r[3]-t[2]*a[1],[t,n,a]},add:function(t,n,a){return t[0]=n[0]+a[0],t[1]=n[1]+a[1],t[2]=n[2]+a[2],t[3]=n[3]+a[3],t},subtract:h,exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]},equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=a[0],h=a[1],c=a[2],s=a[3];return Math.abs(r-i)<=n*Math.max(1,Math.abs(r),Math.abs(i))&&Math.abs(u-h)<=n*Math.max(1,Math.abs(u),Math.abs(h))&&Math.abs(e-c)<=n*Math.max(1,Math.abs(e),Math.abs(c))&&Math.abs(o-s)<=n*Math.max(1,Math.abs(o),Math.abs(s))},multiplyScalar:function(t,n,a){return t[0]=n[0]*a,t[1]=n[1]*a,t[2]=n[2]*a,t[3]=n[3]*a,t},multiplyScalarAndAdd:function(t,n,a,r){return t[0]=n[0]+a[0]*r,t[1]=n[1]+a[1]*r,t[2]=n[2]+a[2]*r,t[3]=n[3]+a[3]*r,t},mul:c,sub:s});function f(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=a[0],s=a[1],M=a[2],f=a[3],l=a[4],v=a[5];return t[0]=r*c+e*s,t[1]=u*c+o*s,t[2]=r*M+e*f,t[3]=u*M+o*f,t[4]=r*l+e*v+i,t[5]=u*l+o*v+h,t}function l(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t[2]=n[2]-a[2],t[3]=n[3]-a[3],t[4]=n[4]-a[4],t[5]=n[5]-a[5],t}var v=f,b=l,m=Object.freeze({__proto__:null,create:function(){var t=new a(6);return a!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t},clone:function(t){var n=new a(6);return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n},copy:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t},fromValues:function(t,n,r,u,e,o){var i=new a(6);return i[0]=t,i[1]=n,i[2]=r,i[3]=u,i[4]=e,i[5]=o,i},set:function(t,n,a,r,u,e,o){return t[0]=n,t[1]=a,t[2]=r,t[3]=u,t[4]=e,t[5]=o,t},invert:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=a*e-r*u;return h?(h=1/h,t[0]=e*h,t[1]=-r*h,t[2]=-u*h,t[3]=a*h,t[4]=(u*i-e*o)*h,t[5]=(r*o-a*i)*h,t):null},determinant:function(t){return t[0]*t[3]-t[1]*t[2]},multiply:f,rotate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=Math.sin(a),s=Math.cos(a);return t[0]=r*s+e*c,t[1]=u*s+o*c,t[2]=r*-c+e*s,t[3]=u*-c+o*s,t[4]=i,t[5]=h,t},scale:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=a[0],s=a[1];return t[0]=r*c,t[1]=u*c,t[2]=e*s,t[3]=o*s,t[4]=i,t[5]=h,t},translate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=a[0],s=a[1];return t[0]=r,t[1]=u,t[2]=e,t[3]=o,t[4]=r*c+e*s+i,t[5]=u*c+o*s+h,t},fromRotation:function(t,n){var a=Math.sin(n),r=Math.cos(n);return t[0]=r,t[1]=a,t[2]=-a,t[3]=r,t[4]=0,t[5]=0,t},fromScaling:function(t,n){return t[0]=n[0],t[1]=0,t[2]=0,t[3]=n[1],t[4]=0,t[5]=0,t},fromTranslation:function(t,n){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=n[0],t[5]=n[1],t},str:function(t){return"mat2d("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+")"},frob:function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],1)},add:function(t,n,a){return t[0]=n[0]+a[0],t[1]=n[1]+a[1],t[2]=n[2]+a[2],t[3]=n[3]+a[3],t[4]=n[4]+a[4],t[5]=n[5]+a[5],t},subtract:l,multiplyScalar:function(t,n,a){return t[0]=n[0]*a,t[1]=n[1]*a,t[2]=n[2]*a,t[3]=n[3]*a,t[4]=n[4]*a,t[5]=n[5]*a,t},multiplyScalarAndAdd:function(t,n,a,r){return t[0]=n[0]+a[0]*r,t[1]=n[1]+a[1]*r,t[2]=n[2]+a[2]*r,t[3]=n[3]+a[3]*r,t[4]=n[4]+a[4]*r,t[5]=n[5]+a[5]*r,t},exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]},equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=t[4],h=t[5],c=a[0],s=a[1],M=a[2],f=a[3],l=a[4],v=a[5];return Math.abs(r-c)<=n*Math.max(1,Math.abs(r),Math.abs(c))&&Math.abs(u-s)<=n*Math.max(1,Math.abs(u),Math.abs(s))&&Math.abs(e-M)<=n*Math.max(1,Math.abs(e),Math.abs(M))&&Math.abs(o-f)<=n*Math.max(1,Math.abs(o),Math.abs(f))&&Math.abs(i-l)<=n*Math.max(1,Math.abs(i),Math.abs(l))&&Math.abs(h-v)<=n*Math.max(1,Math.abs(h),Math.abs(v))},mul:v,sub:b});function d(){var t=new a(9);return a!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function p(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=n[8],f=a[0],l=a[1],v=a[2],b=a[3],m=a[4],d=a[5],p=a[6],x=a[7],y=a[8];return t[0]=f*r+l*o+v*c,t[1]=f*u+l*i+v*s,t[2]=f*e+l*h+v*M,t[3]=b*r+m*o+d*c,t[4]=b*u+m*i+d*s,t[5]=b*e+m*h+d*M,t[6]=p*r+x*o+y*c,t[7]=p*u+x*i+y*s,t[8]=p*e+x*h+y*M,t}function x(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t[2]=n[2]-a[2],t[3]=n[3]-a[3],t[4]=n[4]-a[4],t[5]=n[5]-a[5],t[6]=n[6]-a[6],t[7]=n[7]-a[7],t[8]=n[8]-a[8],t}var y=p,q=x,g=Object.freeze({__proto__:null,create:d,fromMat4:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[4],t[4]=n[5],t[5]=n[6],t[6]=n[8],t[7]=n[9],t[8]=n[10],t},clone:function(t){var n=new a(9);return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n[6]=t[6],n[7]=t[7],n[8]=t[8],n},copy:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t},fromValues:function(t,n,r,u,e,o,i,h,c){var s=new a(9);return s[0]=t,s[1]=n,s[2]=r,s[3]=u,s[4]=e,s[5]=o,s[6]=i,s[7]=h,s[8]=c,s},set:function(t,n,a,r,u,e,o,i,h,c){return t[0]=n,t[1]=a,t[2]=r,t[3]=u,t[4]=e,t[5]=o,t[6]=i,t[7]=h,t[8]=c,t},identity:function(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},transpose:function(t,n){if(t===n){var a=n[1],r=n[2],u=n[5];t[1]=n[3],t[2]=n[6],t[3]=a,t[5]=n[7],t[6]=r,t[7]=u}else t[0]=n[0],t[1]=n[3],t[2]=n[6],t[3]=n[1],t[4]=n[4],t[5]=n[7],t[6]=n[2],t[7]=n[5],t[8]=n[8];return t},invert:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=n[6],c=n[7],s=n[8],M=s*o-i*c,f=-s*e+i*h,l=c*e-o*h,v=a*M+r*f+u*l;return v?(v=1/v,t[0]=M*v,t[1]=(-s*r+u*c)*v,t[2]=(i*r-u*o)*v,t[3]=f*v,t[4]=(s*a-u*h)*v,t[5]=(-i*a+u*e)*v,t[6]=l*v,t[7]=(-c*a+r*h)*v,t[8]=(o*a-r*e)*v,t):null},adjoint:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=n[6],c=n[7],s=n[8];return t[0]=o*s-i*c,t[1]=u*c-r*s,t[2]=r*i-u*o,t[3]=i*h-e*s,t[4]=a*s-u*h,t[5]=u*e-a*i,t[6]=e*c-o*h,t[7]=r*h-a*c,t[8]=a*o-r*e,t},determinant:function(t){var n=t[0],a=t[1],r=t[2],u=t[3],e=t[4],o=t[5],i=t[6],h=t[7],c=t[8];return n*(c*e-o*h)+a*(-c*u+o*i)+r*(h*u-e*i)},multiply:p,translate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=n[8],f=a[0],l=a[1];return t[0]=r,t[1]=u,t[2]=e,t[3]=o,t[4]=i,t[5]=h,t[6]=f*r+l*o+c,t[7]=f*u+l*i+s,t[8]=f*e+l*h+M,t},rotate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=n[8],f=Math.sin(a),l=Math.cos(a);return t[0]=l*r+f*o,t[1]=l*u+f*i,t[2]=l*e+f*h,t[3]=l*o-f*r,t[4]=l*i-f*u,t[5]=l*h-f*e,t[6]=c,t[7]=s,t[8]=M,t},scale:function(t,n,a){var r=a[0],u=a[1];return t[0]=r*n[0],t[1]=r*n[1],t[2]=r*n[2],t[3]=u*n[3],t[4]=u*n[4],t[5]=u*n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t},fromTranslation:function(t,n){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=n[0],t[7]=n[1],t[8]=1,t},fromRotation:function(t,n){var a=Math.sin(n),r=Math.cos(n);return t[0]=r,t[1]=a,t[2]=0,t[3]=-a,t[4]=r,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},fromScaling:function(t,n){return t[0]=n[0],t[1]=0,t[2]=0,t[3]=0,t[4]=n[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t},fromMat2d:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=0,t[3]=n[2],t[4]=n[3],t[5]=0,t[6]=n[4],t[7]=n[5],t[8]=1,t},fromQuat:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=a+a,i=r+r,h=u+u,c=a*o,s=r*o,M=r*i,f=u*o,l=u*i,v=u*h,b=e*o,m=e*i,d=e*h;return t[0]=1-M-v,t[3]=s-d,t[6]=f+m,t[1]=s+d,t[4]=1-c-v,t[7]=l-b,t[2]=f-m,t[5]=l+b,t[8]=1-c-M,t},normalFromMat4:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=n[6],c=n[7],s=n[8],M=n[9],f=n[10],l=n[11],v=n[12],b=n[13],m=n[14],d=n[15],p=a*i-r*o,x=a*h-u*o,y=a*c-e*o,q=r*h-u*i,g=r*c-e*i,_=u*c-e*h,A=s*b-M*v,w=s*m-f*v,z=s*d-l*v,R=M*m-f*b,O=M*d-l*b,j=f*d-l*m,E=p*j-x*O+y*R+q*z-g*w+_*A;return E?(E=1/E,t[0]=(i*j-h*O+c*R)*E,t[1]=(h*z-o*j-c*w)*E,t[2]=(o*O-i*z+c*A)*E,t[3]=(u*O-r*j-e*R)*E,t[4]=(a*j-u*z+e*w)*E,t[5]=(r*z-a*O-e*A)*E,t[6]=(b*_-m*g+d*q)*E,t[7]=(m*y-v*_-d*x)*E,t[8]=(v*g-b*y+d*p)*E,t):null},projection:function(t,n,a){return t[0]=2/n,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/a,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t},str:function(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"},frob:function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])},add:function(t,n,a){return t[0]=n[0]+a[0],t[1]=n[1]+a[1],t[2]=n[2]+a[2],t[3]=n[3]+a[3],t[4]=n[4]+a[4],t[5]=n[5]+a[5],t[6]=n[6]+a[6],t[7]=n[7]+a[7],t[8]=n[8]+a[8],t},subtract:x,multiplyScalar:function(t,n,a){return t[0]=n[0]*a,t[1]=n[1]*a,t[2]=n[2]*a,t[3]=n[3]*a,t[4]=n[4]*a,t[5]=n[5]*a,t[6]=n[6]*a,t[7]=n[7]*a,t[8]=n[8]*a,t},multiplyScalarAndAdd:function(t,n,a,r){return t[0]=n[0]+a[0]*r,t[1]=n[1]+a[1]*r,t[2]=n[2]+a[2]*r,t[3]=n[3]+a[3]*r,t[4]=n[4]+a[4]*r,t[5]=n[5]+a[5]*r,t[6]=n[6]+a[6]*r,t[7]=n[7]+a[7]*r,t[8]=n[8]+a[8]*r,t},exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]&&t[6]===n[6]&&t[7]===n[7]&&t[8]===n[8]},equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=t[4],h=t[5],c=t[6],s=t[7],M=t[8],f=a[0],l=a[1],v=a[2],b=a[3],m=a[4],d=a[5],p=a[6],x=a[7],y=a[8];return Math.abs(r-f)<=n*Math.max(1,Math.abs(r),Math.abs(f))&&Math.abs(u-l)<=n*Math.max(1,Math.abs(u),Math.abs(l))&&Math.abs(e-v)<=n*Math.max(1,Math.abs(e),Math.abs(v))&&Math.abs(o-b)<=n*Math.max(1,Math.abs(o),Math.abs(b))&&Math.abs(i-m)<=n*Math.max(1,Math.abs(i),Math.abs(m))&&Math.abs(h-d)<=n*Math.max(1,Math.abs(h),Math.abs(d))&&Math.abs(c-p)<=n*Math.max(1,Math.abs(c),Math.abs(p))&&Math.abs(s-x)<=n*Math.max(1,Math.abs(s),Math.abs(x))&&Math.abs(M-y)<=n*Math.max(1,Math.abs(M),Math.abs(y))},mul:y,sub:q});function _(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function A(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=n[8],f=n[9],l=n[10],v=n[11],b=n[12],m=n[13],d=n[14],p=n[15],x=a[0],y=a[1],q=a[2],g=a[3];return t[0]=x*r+y*i+q*M+g*b,t[1]=x*u+y*h+q*f+g*m,t[2]=x*e+y*c+q*l+g*d,t[3]=x*o+y*s+q*v+g*p,x=a[4],y=a[5],q=a[6],g=a[7],t[4]=x*r+y*i+q*M+g*b,t[5]=x*u+y*h+q*f+g*m,t[6]=x*e+y*c+q*l+g*d,t[7]=x*o+y*s+q*v+g*p,x=a[8],y=a[9],q=a[10],g=a[11],t[8]=x*r+y*i+q*M+g*b,t[9]=x*u+y*h+q*f+g*m,t[10]=x*e+y*c+q*l+g*d,t[11]=x*o+y*s+q*v+g*p,x=a[12],y=a[13],q=a[14],g=a[15],t[12]=x*r+y*i+q*M+g*b,t[13]=x*u+y*h+q*f+g*m,t[14]=x*e+y*c+q*l+g*d,t[15]=x*o+y*s+q*v+g*p,t}function w(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=r+r,h=u+u,c=e+e,s=r*i,M=r*h,f=r*c,l=u*h,v=u*c,b=e*c,m=o*i,d=o*h,p=o*c;return t[0]=1-(l+b),t[1]=M+p,t[2]=f-d,t[3]=0,t[4]=M-p,t[5]=1-(s+b),t[6]=v+m,t[7]=0,t[8]=f+d,t[9]=v-m,t[10]=1-(s+l),t[11]=0,t[12]=a[0],t[13]=a[1],t[14]=a[2],t[15]=1,t}function z(t,n){return t[0]=n[12],t[1]=n[13],t[2]=n[14],t}function R(t,n){var a=n[0],r=n[1],u=n[2],e=n[4],o=n[5],i=n[6],h=n[8],c=n[9],s=n[10];return t[0]=Math.hypot(a,r,u),t[1]=Math.hypot(e,o,i),t[2]=Math.hypot(h,c,s),t}function O(t,n){var r=new a(3);R(r,n);var u=1/r[0],e=1/r[1],o=1/r[2],i=n[0]*u,h=n[1]*e,c=n[2]*o,s=n[4]*u,M=n[5]*e,f=n[6]*o,l=n[8]*u,v=n[9]*e,b=n[10]*o,m=i+M+b,d=0;return m>0?(d=2*Math.sqrt(m+1),t[3]=.25*d,t[0]=(f-v)/d,t[1]=(l-c)/d,t[2]=(h-s)/d):i>M&&i>b?(d=2*Math.sqrt(1+i-M-b),t[3]=(f-v)/d,t[0]=.25*d,t[1]=(h+s)/d,t[2]=(l+c)/d):M>b?(d=2*Math.sqrt(1+M-i-b),t[3]=(l-c)/d,t[0]=(h+s)/d,t[1]=.25*d,t[2]=(f+v)/d):(d=2*Math.sqrt(1+b-i-M),t[3]=(h-s)/d,t[0]=(l+c)/d,t[1]=(f+v)/d,t[2]=.25*d),t}function j(t,n,a,r,u){var e=1/Math.tan(n/2);if(t[0]=e/a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=u&&u!==1/0){var o=1/(r-u);t[10]=(u+r)*o,t[14]=2*u*r*o}else t[10]=-1,t[14]=-2*r;return t}var E=j;function P(t,n,a,r,u,e,o){var i=1/(n-a),h=1/(r-u),c=1/(e-o);return t[0]=-2*i,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(n+a)*i,t[13]=(u+r)*h,t[14]=(o+e)*c,t[15]=1,t}var T=P;function S(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t[2]=n[2]-a[2],t[3]=n[3]-a[3],t[4]=n[4]-a[4],t[5]=n[5]-a[5],t[6]=n[6]-a[6],t[7]=n[7]-a[7],t[8]=n[8]-a[8],t[9]=n[9]-a[9],t[10]=n[10]-a[10],t[11]=n[11]-a[11],t[12]=n[12]-a[12],t[13]=n[13]-a[13],t[14]=n[14]-a[14],t[15]=n[15]-a[15],t}var D=A,F=S,I=Object.freeze({__proto__:null,create:function(){var t=new a(16);return a!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t},clone:function(t){var n=new a(16);return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n[6]=t[6],n[7]=t[7],n[8]=t[8],n[9]=t[9],n[10]=t[10],n[11]=t[11],n[12]=t[12],n[13]=t[13],n[14]=t[14],n[15]=t[15],n},copy:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],t},fromValues:function(t,n,r,u,e,o,i,h,c,s,M,f,l,v,b,m){var d=new a(16);return d[0]=t,d[1]=n,d[2]=r,d[3]=u,d[4]=e,d[5]=o,d[6]=i,d[7]=h,d[8]=c,d[9]=s,d[10]=M,d[11]=f,d[12]=l,d[13]=v,d[14]=b,d[15]=m,d},set:function(t,n,a,r,u,e,o,i,h,c,s,M,f,l,v,b,m){return t[0]=n,t[1]=a,t[2]=r,t[3]=u,t[4]=e,t[5]=o,t[6]=i,t[7]=h,t[8]=c,t[9]=s,t[10]=M,t[11]=f,t[12]=l,t[13]=v,t[14]=b,t[15]=m,t},identity:_,transpose:function(t,n){if(t===n){var a=n[1],r=n[2],u=n[3],e=n[6],o=n[7],i=n[11];t[1]=n[4],t[2]=n[8],t[3]=n[12],t[4]=a,t[6]=n[9],t[7]=n[13],t[8]=r,t[9]=e,t[11]=n[14],t[12]=u,t[13]=o,t[14]=i}else t[0]=n[0],t[1]=n[4],t[2]=n[8],t[3]=n[12],t[4]=n[1],t[5]=n[5],t[6]=n[9],t[7]=n[13],t[8]=n[2],t[9]=n[6],t[10]=n[10],t[11]=n[14],t[12]=n[3],t[13]=n[7],t[14]=n[11],t[15]=n[15];return t},invert:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=n[6],c=n[7],s=n[8],M=n[9],f=n[10],l=n[11],v=n[12],b=n[13],m=n[14],d=n[15],p=a*i-r*o,x=a*h-u*o,y=a*c-e*o,q=r*h-u*i,g=r*c-e*i,_=u*c-e*h,A=s*b-M*v,w=s*m-f*v,z=s*d-l*v,R=M*m-f*b,O=M*d-l*b,j=f*d-l*m,E=p*j-x*O+y*R+q*z-g*w+_*A;return E?(E=1/E,t[0]=(i*j-h*O+c*R)*E,t[1]=(u*O-r*j-e*R)*E,t[2]=(b*_-m*g+d*q)*E,t[3]=(f*g-M*_-l*q)*E,t[4]=(h*z-o*j-c*w)*E,t[5]=(a*j-u*z+e*w)*E,t[6]=(m*y-v*_-d*x)*E,t[7]=(s*_-f*y+l*x)*E,t[8]=(o*O-i*z+c*A)*E,t[9]=(r*z-a*O-e*A)*E,t[10]=(v*g-b*y+d*p)*E,t[11]=(M*y-s*g-l*p)*E,t[12]=(i*w-o*R-h*A)*E,t[13]=(a*R-r*w+u*A)*E,t[14]=(b*x-v*q-m*p)*E,t[15]=(s*q-M*x+f*p)*E,t):null},adjoint:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=n[4],i=n[5],h=n[6],c=n[7],s=n[8],M=n[9],f=n[10],l=n[11],v=n[12],b=n[13],m=n[14],d=n[15],p=a*i-r*o,x=a*h-u*o,y=a*c-e*o,q=r*h-u*i,g=r*c-e*i,_=u*c-e*h,A=s*b-M*v,w=s*m-f*v,z=s*d-l*v,R=M*m-f*b,O=M*d-l*b,j=f*d-l*m;return t[0]=i*j-h*O+c*R,t[1]=u*O-r*j-e*R,t[2]=b*_-m*g+d*q,t[3]=f*g-M*_-l*q,t[4]=h*z-o*j-c*w,t[5]=a*j-u*z+e*w,t[6]=m*y-v*_-d*x,t[7]=s*_-f*y+l*x,t[8]=o*O-i*z+c*A,t[9]=r*z-a*O-e*A,t[10]=v*g-b*y+d*p,t[11]=M*y-s*g-l*p,t[12]=i*w-o*R-h*A,t[13]=a*R-r*w+u*A,t[14]=b*x-v*q-m*p,t[15]=s*q-M*x+f*p,t},determinant:function(t){var n=t[0],a=t[1],r=t[2],u=t[3],e=t[4],o=t[5],i=t[6],h=t[7],c=t[8],s=t[9],M=t[10],f=t[11],l=t[12],v=t[13],b=t[14],m=n*o-a*e,d=n*i-r*e,p=a*i-r*o,x=c*v-s*l,y=c*b-M*l,q=s*b-M*v;return h*(n*q-a*y+r*x)-u*(e*q-o*y+i*x)+t[15]*(c*p-s*d+M*m)-f*(l*p-v*d+b*m)},multiply:A,translate:function(t,n,a){var r,u,e,o,i,h,c,s,M,f,l,v,b=a[0],m=a[1],d=a[2];return n===t?(t[12]=n[0]*b+n[4]*m+n[8]*d+n[12],t[13]=n[1]*b+n[5]*m+n[9]*d+n[13],t[14]=n[2]*b+n[6]*m+n[10]*d+n[14],t[15]=n[3]*b+n[7]*m+n[11]*d+n[15]):(r=n[0],u=n[1],e=n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=n[8],f=n[9],l=n[10],v=n[11],t[0]=r,t[1]=u,t[2]=e,t[3]=o,t[4]=i,t[5]=h,t[6]=c,t[7]=s,t[8]=M,t[9]=f,t[10]=l,t[11]=v,t[12]=r*b+i*m+M*d+n[12],t[13]=u*b+h*m+f*d+n[13],t[14]=e*b+c*m+l*d+n[14],t[15]=o*b+s*m+v*d+n[15]),t},scale:function(t,n,a){var r=a[0],u=a[1],e=a[2];return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=n[3]*r,t[4]=n[4]*u,t[5]=n[5]*u,t[6]=n[6]*u,t[7]=n[7]*u,t[8]=n[8]*e,t[9]=n[9]*e,t[10]=n[10]*e,t[11]=n[11]*e,t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],t},rotate:function(t,a,r,u){var e,o,i,h,c,s,M,f,l,v,b,m,d,p,x,y,q,g,_,A,w,z,R,O,j=u[0],E=u[1],P=u[2],T=Math.hypot(j,E,P);return T0?(r[0]=2*(h*i+M*u+c*o-s*e)/f,r[1]=2*(c*i+M*e+s*u-h*o)/f,r[2]=2*(s*i+M*o+h*e-c*u)/f):(r[0]=2*(h*i+M*u+c*o-s*e),r[1]=2*(c*i+M*e+s*u-h*o),r[2]=2*(s*i+M*o+h*e-c*u)),w(t,n,r),t},getTranslation:z,getScaling:R,getRotation:O,decompose:function(t,n,a,r){n[0]=r[12],n[1]=r[13],n[2]=r[14];var u=r[0],e=r[1],o=r[2],i=r[4],h=r[5],c=r[6],s=r[8],M=r[9],f=r[10];a[0]=Math.hypot(u,e,o),a[1]=Math.hypot(i,h,c),a[2]=Math.hypot(s,M,f);var l=1/a[0],v=1/a[1],b=1/a[2],m=u*l,d=e*v,p=o*b,x=i*l,y=h*v,q=c*b,g=s*l,_=M*v,A=f*b,w=m+y+A,z=0;return w>0?(z=2*Math.sqrt(w+1),t[3]=.25*z,t[0]=(q-_)/z,t[1]=(g-p)/z,t[2]=(d-x)/z):m>y&&m>A?(z=2*Math.sqrt(1+m-y-A),t[3]=(q-_)/z,t[0]=.25*z,t[1]=(d+x)/z,t[2]=(g+p)/z):y>A?(z=2*Math.sqrt(1+y-m-A),t[3]=(g-p)/z,t[0]=(d+x)/z,t[1]=.25*z,t[2]=(q+_)/z):(z=2*Math.sqrt(1+A-m-y),t[3]=(d-x)/z,t[0]=(g+p)/z,t[1]=(q+_)/z,t[2]=.25*z),t},fromRotationTranslationScale:function(t,n,a,r){var u=n[0],e=n[1],o=n[2],i=n[3],h=u+u,c=e+e,s=o+o,M=u*h,f=u*c,l=u*s,v=e*c,b=e*s,m=o*s,d=i*h,p=i*c,x=i*s,y=r[0],q=r[1],g=r[2];return t[0]=(1-(v+m))*y,t[1]=(f+x)*y,t[2]=(l-p)*y,t[3]=0,t[4]=(f-x)*q,t[5]=(1-(M+m))*q,t[6]=(b+d)*q,t[7]=0,t[8]=(l+p)*g,t[9]=(b-d)*g,t[10]=(1-(M+v))*g,t[11]=0,t[12]=a[0],t[13]=a[1],t[14]=a[2],t[15]=1,t},fromRotationTranslationScaleOrigin:function(t,n,a,r,u){var e=n[0],o=n[1],i=n[2],h=n[3],c=e+e,s=o+o,M=i+i,f=e*c,l=e*s,v=e*M,b=o*s,m=o*M,d=i*M,p=h*c,x=h*s,y=h*M,q=r[0],g=r[1],_=r[2],A=u[0],w=u[1],z=u[2],R=(1-(b+d))*q,O=(l+y)*q,j=(v-x)*q,E=(l-y)*g,P=(1-(f+d))*g,T=(m+p)*g,S=(v+x)*_,D=(m-p)*_,F=(1-(f+b))*_;return t[0]=R,t[1]=O,t[2]=j,t[3]=0,t[4]=E,t[5]=P,t[6]=T,t[7]=0,t[8]=S,t[9]=D,t[10]=F,t[11]=0,t[12]=a[0]+A-(R*A+E*w+S*z),t[13]=a[1]+w-(O*A+P*w+D*z),t[14]=a[2]+z-(j*A+T*w+F*z),t[15]=1,t},fromQuat:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=a+a,i=r+r,h=u+u,c=a*o,s=r*o,M=r*i,f=u*o,l=u*i,v=u*h,b=e*o,m=e*i,d=e*h;return t[0]=1-M-v,t[1]=s+d,t[2]=f-m,t[3]=0,t[4]=s-d,t[5]=1-c-v,t[6]=l+b,t[7]=0,t[8]=f+m,t[9]=l-b,t[10]=1-c-M,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},frustum:function(t,n,a,r,u,e,o){var i=1/(a-n),h=1/(u-r),c=1/(e-o);return t[0]=2*e*i,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*e*h,t[6]=0,t[7]=0,t[8]=(a+n)*i,t[9]=(u+r)*h,t[10]=(o+e)*c,t[11]=-1,t[12]=0,t[13]=0,t[14]=o*e*2*c,t[15]=0,t},perspectiveNO:j,perspective:E,perspectiveZO:function(t,n,a,r,u){var e=1/Math.tan(n/2);if(t[0]=e/a,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=e,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=u&&u!==1/0){var o=1/(r-u);t[10]=u*o,t[14]=u*r*o}else t[10]=-1,t[14]=-r;return t},perspectiveFromFieldOfView:function(t,n,a,r){var u=Math.tan(n.upDegrees*Math.PI/180),e=Math.tan(n.downDegrees*Math.PI/180),o=Math.tan(n.leftDegrees*Math.PI/180),i=Math.tan(n.rightDegrees*Math.PI/180),h=2/(o+i),c=2/(u+e);return t[0]=h,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=c,t[6]=0,t[7]=0,t[8]=-(o-i)*h*.5,t[9]=(u-e)*c*.5,t[10]=r/(a-r),t[11]=-1,t[12]=0,t[13]=0,t[14]=r*a/(a-r),t[15]=0,t},orthoNO:P,ortho:T,orthoZO:function(t,n,a,r,u,e,o){var i=1/(n-a),h=1/(r-u),c=1/(e-o);return t[0]=-2*i,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=c,t[11]=0,t[12]=(n+a)*i,t[13]=(u+r)*h,t[14]=e*c,t[15]=1,t},lookAt:function(t,a,r,u){var e,o,i,h,c,s,M,f,l,v,b=a[0],m=a[1],d=a[2],p=u[0],x=u[1],y=u[2],q=r[0],g=r[1],A=r[2];return Math.abs(b-q)0&&(s*=l=1/Math.sqrt(l),M*=l,f*=l);var v=h*f-c*M,b=c*s-i*f,m=i*M-h*s;return(l=v*v+b*b+m*m)>0&&(v*=l=1/Math.sqrt(l),b*=l,m*=l),t[0]=v,t[1]=b,t[2]=m,t[3]=0,t[4]=M*m-f*b,t[5]=f*v-s*m,t[6]=s*b-M*v,t[7]=0,t[8]=s,t[9]=M,t[10]=f,t[11]=0,t[12]=u,t[13]=e,t[14]=o,t[15]=1,t},str:function(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"},frob:function(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])},add:function(t,n,a){return t[0]=n[0]+a[0],t[1]=n[1]+a[1],t[2]=n[2]+a[2],t[3]=n[3]+a[3],t[4]=n[4]+a[4],t[5]=n[5]+a[5],t[6]=n[6]+a[6],t[7]=n[7]+a[7],t[8]=n[8]+a[8],t[9]=n[9]+a[9],t[10]=n[10]+a[10],t[11]=n[11]+a[11],t[12]=n[12]+a[12],t[13]=n[13]+a[13],t[14]=n[14]+a[14],t[15]=n[15]+a[15],t},subtract:S,multiplyScalar:function(t,n,a){return t[0]=n[0]*a,t[1]=n[1]*a,t[2]=n[2]*a,t[3]=n[3]*a,t[4]=n[4]*a,t[5]=n[5]*a,t[6]=n[6]*a,t[7]=n[7]*a,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=n[11]*a,t[12]=n[12]*a,t[13]=n[13]*a,t[14]=n[14]*a,t[15]=n[15]*a,t},multiplyScalarAndAdd:function(t,n,a,r){return t[0]=n[0]+a[0]*r,t[1]=n[1]+a[1]*r,t[2]=n[2]+a[2]*r,t[3]=n[3]+a[3]*r,t[4]=n[4]+a[4]*r,t[5]=n[5]+a[5]*r,t[6]=n[6]+a[6]*r,t[7]=n[7]+a[7]*r,t[8]=n[8]+a[8]*r,t[9]=n[9]+a[9]*r,t[10]=n[10]+a[10]*r,t[11]=n[11]+a[11]*r,t[12]=n[12]+a[12]*r,t[13]=n[13]+a[13]*r,t[14]=n[14]+a[14]*r,t[15]=n[15]+a[15]*r,t},exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]&&t[6]===n[6]&&t[7]===n[7]&&t[8]===n[8]&&t[9]===n[9]&&t[10]===n[10]&&t[11]===n[11]&&t[12]===n[12]&&t[13]===n[13]&&t[14]===n[14]&&t[15]===n[15]},equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=t[4],h=t[5],c=t[6],s=t[7],M=t[8],f=t[9],l=t[10],v=t[11],b=t[12],m=t[13],d=t[14],p=t[15],x=a[0],y=a[1],q=a[2],g=a[3],_=a[4],A=a[5],w=a[6],z=a[7],R=a[8],O=a[9],j=a[10],E=a[11],P=a[12],T=a[13],S=a[14],D=a[15];return Math.abs(r-x)<=n*Math.max(1,Math.abs(r),Math.abs(x))&&Math.abs(u-y)<=n*Math.max(1,Math.abs(u),Math.abs(y))&&Math.abs(e-q)<=n*Math.max(1,Math.abs(e),Math.abs(q))&&Math.abs(o-g)<=n*Math.max(1,Math.abs(o),Math.abs(g))&&Math.abs(i-_)<=n*Math.max(1,Math.abs(i),Math.abs(_))&&Math.abs(h-A)<=n*Math.max(1,Math.abs(h),Math.abs(A))&&Math.abs(c-w)<=n*Math.max(1,Math.abs(c),Math.abs(w))&&Math.abs(s-z)<=n*Math.max(1,Math.abs(s),Math.abs(z))&&Math.abs(M-R)<=n*Math.max(1,Math.abs(M),Math.abs(R))&&Math.abs(f-O)<=n*Math.max(1,Math.abs(f),Math.abs(O))&&Math.abs(l-j)<=n*Math.max(1,Math.abs(l),Math.abs(j))&&Math.abs(v-E)<=n*Math.max(1,Math.abs(v),Math.abs(E))&&Math.abs(b-P)<=n*Math.max(1,Math.abs(b),Math.abs(P))&&Math.abs(m-T)<=n*Math.max(1,Math.abs(m),Math.abs(T))&&Math.abs(d-S)<=n*Math.max(1,Math.abs(d),Math.abs(S))&&Math.abs(p-D)<=n*Math.max(1,Math.abs(p),Math.abs(D))},mul:D,sub:F});function L(){var t=new a(3);return a!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function V(t){var n=t[0],a=t[1],r=t[2];return Math.hypot(n,a,r)}function k(t,n,r){var u=new a(3);return u[0]=t,u[1]=n,u[2]=r,u}function Q(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t[2]=n[2]-a[2],t}function Y(t,n,a){return t[0]=n[0]*a[0],t[1]=n[1]*a[1],t[2]=n[2]*a[2],t}function Z(t,n,a){return t[0]=n[0]/a[0],t[1]=n[1]/a[1],t[2]=n[2]/a[2],t}function N(t,n){var a=n[0]-t[0],r=n[1]-t[1],u=n[2]-t[2];return Math.hypot(a,r,u)}function X(t,n){var a=n[0]-t[0],r=n[1]-t[1],u=n[2]-t[2];return a*a+r*r+u*u}function B(t){var n=t[0],a=t[1],r=t[2];return n*n+a*a+r*r}function U(t,n){var a=n[0],r=n[1],u=n[2],e=a*a+r*r+u*u;return e>0&&(e=1/Math.sqrt(e)),t[0]=n[0]*e,t[1]=n[1]*e,t[2]=n[2]*e,t}function G(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function W(t,n,a){var r=n[0],u=n[1],e=n[2],o=a[0],i=a[1],h=a[2];return t[0]=u*h-e*i,t[1]=e*o-r*h,t[2]=r*i-u*o,t}var C,H=Q,J=Y,K=Z,$=N,tt=X,nt=V,at=B,rt=(C=L(),function(t,n,a,r,u,e){var o,i;for(n||(n=3),a||(a=0),i=r?Math.min(r*n+a,t.length):t.length,o=a;o0&&(o=1/Math.sqrt(o)),t[0]=a*o,t[1]=r*o,t[2]=u*o,t[3]=e*o,t}function yt(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]+t[3]*n[3]}function qt(t,n,a,r){var u=n[0],e=n[1],o=n[2],i=n[3];return t[0]=u+r*(a[0]-u),t[1]=e+r*(a[1]-e),t[2]=o+r*(a[2]-o),t[3]=i+r*(a[3]-i),t}function gt(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]}var _t=Mt,At=ft,wt=lt,zt=bt,Rt=mt,Ot=dt,jt=pt,Et=function(){var t=et();return function(n,a,r,u,e,o){var i,h;for(a||(a=4),r||(r=0),h=u?Math.min(u*a+r,n.length):n.length,i=r;i=1);do{h=(e=2*r()-1)*e+(o=2*r()-1)*o}while(h>=1);var c=Math.sqrt((1-i)/h);return t[0]=n*a,t[1]=n*u,t[2]=n*e*c,t[3]=n*o*c,t},transformMat4:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3];return t[0]=a[0]*r+a[4]*u+a[8]*e+a[12]*o,t[1]=a[1]*r+a[5]*u+a[9]*e+a[13]*o,t[2]=a[2]*r+a[6]*u+a[10]*e+a[14]*o,t[3]=a[3]*r+a[7]*u+a[11]*e+a[15]*o,t},transformQuat:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=a[0],i=a[1],h=a[2],c=a[3],s=c*r+i*e-h*u,M=c*u+h*r-o*e,f=c*e+o*u-i*r,l=-o*r-i*u-h*e;return t[0]=s*c+l*-o+M*-h-f*-i,t[1]=M*c+l*-i+f*-o-s*-h,t[2]=f*c+l*-h+s*-i-M*-o,t[3]=n[3],t},zero:function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t},str:function(t){return"vec4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"},exactEquals:gt,equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=a[0],h=a[1],c=a[2],s=a[3];return Math.abs(r-i)<=n*Math.max(1,Math.abs(r),Math.abs(i))&&Math.abs(u-h)<=n*Math.max(1,Math.abs(u),Math.abs(h))&&Math.abs(e-c)<=n*Math.max(1,Math.abs(e),Math.abs(c))&&Math.abs(o-s)<=n*Math.max(1,Math.abs(o),Math.abs(s))},sub:_t,mul:At,div:wt,dist:zt,sqrDist:Rt,len:Ot,sqrLen:jt,forEach:Et});function Tt(){var t=new a(4);return a!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function St(t,n,a){a*=.5;var r=Math.sin(a);return t[0]=r*n[0],t[1]=r*n[1],t[2]=r*n[2],t[3]=Math.cos(a),t}function Dt(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=a[0],h=a[1],c=a[2],s=a[3];return t[0]=r*s+o*i+u*c-e*h,t[1]=u*s+o*h+e*i-r*c,t[2]=e*s+o*c+r*h-u*i,t[3]=o*s-r*i-u*h-e*c,t}function Ft(t,n,a){a*=.5;var r=n[0],u=n[1],e=n[2],o=n[3],i=Math.sin(a),h=Math.cos(a);return t[0]=r*h+o*i,t[1]=u*h+e*i,t[2]=e*h-u*i,t[3]=o*h-r*i,t}function It(t,n,a){a*=.5;var r=n[0],u=n[1],e=n[2],o=n[3],i=Math.sin(a),h=Math.cos(a);return t[0]=r*h-e*i,t[1]=u*h+o*i,t[2]=e*h+r*i,t[3]=o*h-u*i,t}function Lt(t,n,a){a*=.5;var r=n[0],u=n[1],e=n[2],o=n[3],i=Math.sin(a),h=Math.cos(a);return t[0]=r*h+u*i,t[1]=u*h-r*i,t[2]=e*h+o*i,t[3]=o*h-e*i,t}function Vt(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=Math.sqrt(a*a+r*r+u*u),i=Math.exp(e),h=o>0?i*Math.sin(o)/o:0;return t[0]=a*h,t[1]=r*h,t[2]=u*h,t[3]=i*Math.cos(o),t}function kt(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=Math.sqrt(a*a+r*r+u*u),i=o>0?Math.atan2(o,e)/o:0;return t[0]=a*i,t[1]=r*i,t[2]=u*i,t[3]=.5*Math.log(a*a+r*r+u*u+e*e),t}function Qt(t,a,r,u){var e,o,i,h,c,s=a[0],M=a[1],f=a[2],l=a[3],v=r[0],b=r[1],m=r[2],d=r[3];return(o=s*v+M*b+f*m+l*d)<0&&(o=-o,v=-v,b=-b,m=-m,d=-d),1-o>n?(e=Math.acos(o),i=Math.sin(e),h=Math.sin((1-u)*e)/i,c=Math.sin(u*e)/i):(h=1-u,c=u),t[0]=h*s+c*v,t[1]=h*M+c*b,t[2]=h*f+c*m,t[3]=h*l+c*d,t}function Yt(t,n){var a,r=n[0]+n[4]+n[8];if(r>0)a=Math.sqrt(r+1),t[3]=.5*a,a=.5/a,t[0]=(n[5]-n[7])*a,t[1]=(n[6]-n[2])*a,t[2]=(n[1]-n[3])*a;else{var u=0;n[4]>n[0]&&(u=1),n[8]>n[3*u+u]&&(u=2);var e=(u+1)%3,o=(u+2)%3;a=Math.sqrt(n[3*u+u]-n[3*e+e]-n[3*o+o]+1),t[u]=.5*a,a=.5/a,t[3]=(n[3*e+o]-n[3*o+e])*a,t[e]=(n[3*e+u]+n[3*u+e])*a,t[o]=(n[3*o+u]+n[3*u+o])*a}return t}var Zt=ot,Nt=it,Xt=ht,Bt=ct,Ut=st,Gt=Dt,Wt=vt,Ct=yt,Ht=qt,Jt=dt,Kt=Jt,$t=pt,tn=$t,nn=xt,an=gt;var rn,un,en,on,hn,cn,sn=(rn=L(),un=k(1,0,0),en=k(0,1,0),function(t,n,a){var r=G(n,a);return r<-.999999?(W(rn,un,n),nt(rn)<1e-6&&W(rn,en,n),U(rn,rn),St(t,rn,Math.PI),t):r>.999999?(t[0]=0,t[1]=0,t[2]=0,t[3]=1,t):(W(rn,n,a),t[0]=rn[0],t[1]=rn[1],t[2]=rn[2],t[3]=1+r,nn(t,t))}),Mn=(on=Tt(),hn=Tt(),function(t,n,a,r,u,e){return Qt(on,n,u,e),Qt(hn,a,r,e),Qt(t,on,hn,2*e*(1-e)),t}),fn=(cn=d(),function(t,n,a,r){return cn[0]=a[0],cn[3]=a[1],cn[6]=a[2],cn[1]=r[0],cn[4]=r[1],cn[7]=r[2],cn[2]=-n[0],cn[5]=-n[1],cn[8]=-n[2],nn(t,Yt(t,cn))}),ln=Object.freeze({__proto__:null,create:Tt,identity:function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t},setAxisAngle:St,getAxisAngle:function(t,a){var r=2*Math.acos(a[3]),u=Math.sin(r/2);return u>n?(t[0]=a[0]/u,t[1]=a[1]/u,t[2]=a[2]/u):(t[0]=1,t[1]=0,t[2]=0),r},getAngle:function(t,n){var a=Ct(t,n);return Math.acos(2*a*a-1)},multiply:Dt,rotateX:Ft,rotateY:It,rotateZ:Lt,calculateW:function(t,n){var a=n[0],r=n[1],u=n[2];return t[0]=a,t[1]=r,t[2]=u,t[3]=Math.sqrt(Math.abs(1-a*a-r*r-u*u)),t},exp:Vt,ln:kt,pow:function(t,n,a){return kt(t,n),Wt(t,t,a),Vt(t,t),t},slerp:Qt,random:function(t){var n=r(),a=r(),u=r(),e=Math.sqrt(1-n),o=Math.sqrt(n);return t[0]=e*Math.sin(2*Math.PI*a),t[1]=e*Math.cos(2*Math.PI*a),t[2]=o*Math.sin(2*Math.PI*u),t[3]=o*Math.cos(2*Math.PI*u),t},invert:function(t,n){var a=n[0],r=n[1],u=n[2],e=n[3],o=a*a+r*r+u*u+e*e,i=o?1/o:0;return t[0]=-a*i,t[1]=-r*i,t[2]=-u*i,t[3]=e*i,t},conjugate:function(t,n){return t[0]=-n[0],t[1]=-n[1],t[2]=-n[2],t[3]=n[3],t},fromMat3:Yt,fromEuler:function(t,n,a,r){var e=arguments.length>4&&void 0!==arguments[4]?arguments[4]:u,o=Math.PI/360;n*=o,r*=o,a*=o;var i=Math.sin(n),h=Math.cos(n),c=Math.sin(a),s=Math.cos(a),M=Math.sin(r),f=Math.cos(r);switch(e){case"xyz":t[0]=i*s*f+h*c*M,t[1]=h*c*f-i*s*M,t[2]=h*s*M+i*c*f,t[3]=h*s*f-i*c*M;break;case"xzy":t[0]=i*s*f-h*c*M,t[1]=h*c*f-i*s*M,t[2]=h*s*M+i*c*f,t[3]=h*s*f+i*c*M;break;case"yxz":t[0]=i*s*f+h*c*M,t[1]=h*c*f-i*s*M,t[2]=h*s*M-i*c*f,t[3]=h*s*f+i*c*M;break;case"yzx":t[0]=i*s*f+h*c*M,t[1]=h*c*f+i*s*M,t[2]=h*s*M-i*c*f,t[3]=h*s*f-i*c*M;break;case"zxy":t[0]=i*s*f-h*c*M,t[1]=h*c*f+i*s*M,t[2]=h*s*M+i*c*f,t[3]=h*s*f-i*c*M;break;case"zyx":t[0]=i*s*f-h*c*M,t[1]=h*c*f+i*s*M,t[2]=h*s*M-i*c*f,t[3]=h*s*f+i*c*M;break;default:throw new Error("Unknown angle order "+e)}return t},str:function(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"},clone:Zt,fromValues:Nt,copy:Xt,set:Bt,add:Ut,mul:Gt,scale:Wt,dot:Ct,lerp:Ht,length:Jt,len:Kt,squaredLength:$t,sqrLen:tn,normalize:nn,exactEquals:an,equals:function(t,n){return Math.abs(yt(t,n))>=.999999},rotationTo:sn,sqlerp:Mn,setAxes:fn});function vn(t,n,a){var r=.5*a[0],u=.5*a[1],e=.5*a[2],o=n[0],i=n[1],h=n[2],c=n[3];return t[0]=o,t[1]=i,t[2]=h,t[3]=c,t[4]=r*c+u*h-e*i,t[5]=u*c+e*o-r*h,t[6]=e*c+r*i-u*o,t[7]=-r*o-u*i-e*h,t}function bn(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t}var mn=Xt;var dn=Xt;function pn(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=a[4],h=a[5],c=a[6],s=a[7],M=n[4],f=n[5],l=n[6],v=n[7],b=a[0],m=a[1],d=a[2],p=a[3];return t[0]=r*p+o*b+u*d-e*m,t[1]=u*p+o*m+e*b-r*d,t[2]=e*p+o*d+r*m-u*b,t[3]=o*p-r*b-u*m-e*d,t[4]=r*s+o*i+u*c-e*h+M*p+v*b+f*d-l*m,t[5]=u*s+o*h+e*i-r*c+f*p+v*m+l*b-M*d,t[6]=e*s+o*c+r*h-u*i+l*p+v*d+M*m-f*b,t[7]=o*s-r*i-u*h-e*c+v*p-M*b-f*m-l*d,t}var xn=pn;var yn=Ct;var qn=Jt,gn=qn,_n=$t,An=_n;var wn=Object.freeze({__proto__:null,create:function(){var t=new a(8);return a!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0),t[3]=1,t},clone:function(t){var n=new a(8);return n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=t[3],n[4]=t[4],n[5]=t[5],n[6]=t[6],n[7]=t[7],n},fromValues:function(t,n,r,u,e,o,i,h){var c=new a(8);return c[0]=t,c[1]=n,c[2]=r,c[3]=u,c[4]=e,c[5]=o,c[6]=i,c[7]=h,c},fromRotationTranslationValues:function(t,n,r,u,e,o,i){var h=new a(8);h[0]=t,h[1]=n,h[2]=r,h[3]=u;var c=.5*e,s=.5*o,M=.5*i;return h[4]=c*u+s*r-M*n,h[5]=s*u+M*t-c*r,h[6]=M*u+c*n-s*t,h[7]=-c*t-s*n-M*r,h},fromRotationTranslation:vn,fromTranslation:function(t,n){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=.5*n[0],t[5]=.5*n[1],t[6]=.5*n[2],t[7]=0,t},fromRotation:function(t,n){return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=0,t[5]=0,t[6]=0,t[7]=0,t},fromMat4:function(t,n){var r=Tt();O(r,n);var u=new a(3);return z(u,n),vn(t,r,u),t},copy:bn,identity:function(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t},set:function(t,n,a,r,u,e,o,i,h){return t[0]=n,t[1]=a,t[2]=r,t[3]=u,t[4]=e,t[5]=o,t[6]=i,t[7]=h,t},getReal:mn,getDual:function(t,n){return t[0]=n[4],t[1]=n[5],t[2]=n[6],t[3]=n[7],t},setReal:dn,setDual:function(t,n){return t[4]=n[0],t[5]=n[1],t[6]=n[2],t[7]=n[3],t},getTranslation:function(t,n){var a=n[4],r=n[5],u=n[6],e=n[7],o=-n[0],i=-n[1],h=-n[2],c=n[3];return t[0]=2*(a*c+e*o+r*h-u*i),t[1]=2*(r*c+e*i+u*o-a*h),t[2]=2*(u*c+e*h+a*i-r*o),t},translate:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=.5*a[0],h=.5*a[1],c=.5*a[2],s=n[4],M=n[5],f=n[6],l=n[7];return t[0]=r,t[1]=u,t[2]=e,t[3]=o,t[4]=o*i+u*c-e*h+s,t[5]=o*h+e*i-r*c+M,t[6]=o*c+r*h-u*i+f,t[7]=-r*i-u*h-e*c+l,t},rotateX:function(t,n,a){var r=-n[0],u=-n[1],e=-n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=i*o+s*r+h*e-c*u,f=h*o+s*u+c*r-i*e,l=c*o+s*e+i*u-h*r,v=s*o-i*r-h*u-c*e;return Ft(t,n,a),r=t[0],u=t[1],e=t[2],o=t[3],t[4]=M*o+v*r+f*e-l*u,t[5]=f*o+v*u+l*r-M*e,t[6]=l*o+v*e+M*u-f*r,t[7]=v*o-M*r-f*u-l*e,t},rotateY:function(t,n,a){var r=-n[0],u=-n[1],e=-n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=i*o+s*r+h*e-c*u,f=h*o+s*u+c*r-i*e,l=c*o+s*e+i*u-h*r,v=s*o-i*r-h*u-c*e;return It(t,n,a),r=t[0],u=t[1],e=t[2],o=t[3],t[4]=M*o+v*r+f*e-l*u,t[5]=f*o+v*u+l*r-M*e,t[6]=l*o+v*e+M*u-f*r,t[7]=v*o-M*r-f*u-l*e,t},rotateZ:function(t,n,a){var r=-n[0],u=-n[1],e=-n[2],o=n[3],i=n[4],h=n[5],c=n[6],s=n[7],M=i*o+s*r+h*e-c*u,f=h*o+s*u+c*r-i*e,l=c*o+s*e+i*u-h*r,v=s*o-i*r-h*u-c*e;return Lt(t,n,a),r=t[0],u=t[1],e=t[2],o=t[3],t[4]=M*o+v*r+f*e-l*u,t[5]=f*o+v*u+l*r-M*e,t[6]=l*o+v*e+M*u-f*r,t[7]=v*o-M*r-f*u-l*e,t},rotateByQuatAppend:function(t,n,a){var r=a[0],u=a[1],e=a[2],o=a[3],i=n[0],h=n[1],c=n[2],s=n[3];return t[0]=i*o+s*r+h*e-c*u,t[1]=h*o+s*u+c*r-i*e,t[2]=c*o+s*e+i*u-h*r,t[3]=s*o-i*r-h*u-c*e,i=n[4],h=n[5],c=n[6],s=n[7],t[4]=i*o+s*r+h*e-c*u,t[5]=h*o+s*u+c*r-i*e,t[6]=c*o+s*e+i*u-h*r,t[7]=s*o-i*r-h*u-c*e,t},rotateByQuatPrepend:function(t,n,a){var r=n[0],u=n[1],e=n[2],o=n[3],i=a[0],h=a[1],c=a[2],s=a[3];return t[0]=r*s+o*i+u*c-e*h,t[1]=u*s+o*h+e*i-r*c,t[2]=e*s+o*c+r*h-u*i,t[3]=o*s-r*i-u*h-e*c,i=a[4],h=a[5],c=a[6],s=a[7],t[4]=r*s+o*i+u*c-e*h,t[5]=u*s+o*h+e*i-r*c,t[6]=e*s+o*c+r*h-u*i,t[7]=o*s-r*i-u*h-e*c,t},rotateAroundAxis:function(t,a,r,u){if(Math.abs(u)0){a=Math.sqrt(a);var r=n[0]/a,u=n[1]/a,e=n[2]/a,o=n[3]/a,i=n[4],h=n[5],c=n[6],s=n[7],M=r*i+u*h+e*c+o*s;t[0]=r,t[1]=u,t[2]=e,t[3]=o,t[4]=(i-r*M)/a,t[5]=(h-u*M)/a,t[6]=(c-e*M)/a,t[7]=(s-o*M)/a}return t},str:function(t){return"quat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+")"},exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]&&t[2]===n[2]&&t[3]===n[3]&&t[4]===n[4]&&t[5]===n[5]&&t[6]===n[6]&&t[7]===n[7]},equals:function(t,a){var r=t[0],u=t[1],e=t[2],o=t[3],i=t[4],h=t[5],c=t[6],s=t[7],M=a[0],f=a[1],l=a[2],v=a[3],b=a[4],m=a[5],d=a[6],p=a[7];return Math.abs(r-M)<=n*Math.max(1,Math.abs(r),Math.abs(M))&&Math.abs(u-f)<=n*Math.max(1,Math.abs(u),Math.abs(f))&&Math.abs(e-l)<=n*Math.max(1,Math.abs(e),Math.abs(l))&&Math.abs(o-v)<=n*Math.max(1,Math.abs(o),Math.abs(v))&&Math.abs(i-b)<=n*Math.max(1,Math.abs(i),Math.abs(b))&&Math.abs(h-m)<=n*Math.max(1,Math.abs(h),Math.abs(m))&&Math.abs(c-d)<=n*Math.max(1,Math.abs(c),Math.abs(d))&&Math.abs(s-p)<=n*Math.max(1,Math.abs(s),Math.abs(p))}});function zn(){var t=new a(2);return a!=Float32Array&&(t[0]=0,t[1]=0),t}function Rn(t,n,a){return t[0]=n[0]-a[0],t[1]=n[1]-a[1],t}function On(t,n,a){return t[0]=n[0]*a[0],t[1]=n[1]*a[1],t}function jn(t,n,a){return t[0]=n[0]/a[0],t[1]=n[1]/a[1],t}function En(t,n){var a=n[0]-t[0],r=n[1]-t[1];return Math.hypot(a,r)}function Pn(t,n){var a=n[0]-t[0],r=n[1]-t[1];return a*a+r*r}function Tn(t){var n=t[0],a=t[1];return Math.hypot(n,a)}function Sn(t){var n=t[0],a=t[1];return n*n+a*a}var Dn=Tn,Fn=Rn,In=On,Ln=jn,Vn=En,kn=Pn,Qn=Sn,Yn=function(){var t=zn();return function(n,a,r,u,e,o){var i,h;for(a||(a=2),r||(r=0),h=u?Math.min(u*a+r,n.length):n.length,i=r;i0&&(u=1/Math.sqrt(u)),t[0]=n[0]*u,t[1]=n[1]*u,t},dot:function(t,n){return t[0]*n[0]+t[1]*n[1]},cross:function(t,n,a){var r=n[0]*a[1]-n[1]*a[0];return t[0]=t[1]=0,t[2]=r,t},lerp:function(t,n,a,r){var u=n[0],e=n[1];return t[0]=u+r*(a[0]-u),t[1]=e+r*(a[1]-e),t},random:function(t,n){n=void 0===n?1:n;var a=2*r()*Math.PI;return t[0]=Math.cos(a)*n,t[1]=Math.sin(a)*n,t},transformMat2:function(t,n,a){var r=n[0],u=n[1];return t[0]=a[0]*r+a[2]*u,t[1]=a[1]*r+a[3]*u,t},transformMat2d:function(t,n,a){var r=n[0],u=n[1];return t[0]=a[0]*r+a[2]*u+a[4],t[1]=a[1]*r+a[3]*u+a[5],t},transformMat3:function(t,n,a){var r=n[0],u=n[1];return t[0]=a[0]*r+a[3]*u+a[6],t[1]=a[1]*r+a[4]*u+a[7],t},transformMat4:function(t,n,a){var r=n[0],u=n[1];return t[0]=a[0]*r+a[4]*u+a[12],t[1]=a[1]*r+a[5]*u+a[13],t},rotate:function(t,n,a,r){var u=n[0]-a[0],e=n[1]-a[1],o=Math.sin(r),i=Math.cos(r);return t[0]=u*i-e*o+a[0],t[1]=u*o+e*i+a[1],t},angle:function(t,n){var a=t[0],r=t[1],u=n[0],e=n[1],o=Math.sqrt((a*a+r*r)*(u*u+e*e)),i=o&&(a*u+r*e)/o;return Math.acos(Math.min(Math.max(i,-1),1))},zero:function(t){return t[0]=0,t[1]=0,t},str:function(t){return"vec2("+t[0]+", "+t[1]+")"},exactEquals:function(t,n){return t[0]===n[0]&&t[1]===n[1]},equals:function(t,a){var r=t[0],u=t[1],e=a[0],o=a[1];return Math.abs(r-e)<=n*Math.max(1,Math.abs(r),Math.abs(e))&&Math.abs(u-o)<=n*Math.max(1,Math.abs(u),Math.abs(o))},len:Dn,sub:Fn,mul:In,div:Ln,dist:Vn,sqrDist:kn,sqrLen:Qn,forEach:Yn});t.glMatrix=o,t.mat2=M,t.mat2d=m,t.mat3=g,t.mat4=I,t.quat=ln,t.quat2=wn,t.vec2=Zn,t.vec3=ut,t.vec4=Pt,Object.defineProperty(t,"__esModule",{value:!0})})); +!(function (t, n) { typeof exports === 'object' && typeof module !== 'undefined' ? n(exports) : typeof define === 'function' && define.amd ? define(['exports'], n) : n((t = typeof globalThis !== 'undefined' ? globalThis : t || self).glMatrix = {}) }(this, (function (t) { + const n = 1e-6; let a = typeof Float32Array !== 'undefined' ? Float32Array : Array; const r = Math.random; const u = 'zyx'; const e = Math.PI / 180; Math.hypot || (Math.hypot = function () { for (var t = 0, n = arguments.length; n--;)t += arguments[n] * arguments[n]; return Math.sqrt(t) }); const o = Object.freeze({ + __proto__: null, EPSILON: n, get ARRAY_TYPE() { return a }, RANDOM: r, ANGLE_ORDER: u, setMatrixArrayType(t) { a = t }, toRadian(t) { return t * e }, equals(t, a) { return Math.abs(t - a) <= n * Math.max(1, Math.abs(t), Math.abs(a)) } + }); function i(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = a[0]; const h = a[1]; const c = a[2]; const s = a[3]; return t[0] = r * i + e * h, t[1] = u * i + o * h, t[2] = r * c + e * s, t[3] = u * c + o * s, t } function h(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t[3] = n[3] - a[3], t } const c = i; const s = h; const M = Object.freeze({ + __proto__: null, create() { const t = new a(4); return a != Float32Array && (t[1] = 0, t[2] = 0), t[0] = 1, t[3] = 1, t }, clone(t) { const n = new a(4); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n }, copy(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t }, identity(t) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 1, t }, fromValues(t, n, r, u) { const e = new a(4); return e[0] = t, e[1] = n, e[2] = r, e[3] = u, e }, set(t, n, a, r, u) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t }, transpose(t, n) { if (t === n) { const a = n[1]; t[1] = n[2], t[2] = a } else t[0] = n[0], t[1] = n[2], t[2] = n[1], t[3] = n[3]; return t }, invert(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; let o = a * e - u * r; return o ? (o = 1 / o, t[0] = e * o, t[1] = -r * o, t[2] = -u * o, t[3] = a * o, t) : null }, adjoint(t, n) { const a = n[0]; return t[0] = n[3], t[1] = -n[1], t[2] = -n[2], t[3] = a, t }, determinant(t) { return t[0] * t[3] - t[2] * t[1] }, multiply: i, rotate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = Math.sin(a); const h = Math.cos(a); return t[0] = r * h + e * i, t[1] = u * h + o * i, t[2] = r * -i + e * h, t[3] = u * -i + o * h, t }, scale(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = a[0]; const h = a[1]; return t[0] = r * i, t[1] = u * i, t[2] = e * h, t[3] = o * h, t }, fromRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = r, t[1] = a, t[2] = -a, t[3] = r, t }, fromScaling(t, n) { return t[0] = n[0], t[1] = 0, t[2] = 0, t[3] = n[1], t }, str(t) { return 'mat2(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ')' }, frob(t) { return Math.hypot(t[0], t[1], t[2], t[3]) }, LDU(t, n, a, r) { return t[2] = r[2] / r[0], a[0] = r[0], a[1] = r[1], a[3] = r[3] - t[2] * a[1], [t, n, a] }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t }, subtract: h, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = a[0]; const h = a[1]; const c = a[2]; const s = a[3]; return Math.abs(r - i) <= n * Math.max(1, Math.abs(r), Math.abs(i)) && Math.abs(u - h) <= n * Math.max(1, Math.abs(u), Math.abs(h)) && Math.abs(e - c) <= n * Math.max(1, Math.abs(e), Math.abs(c)) && Math.abs(o - s) <= n * Math.max(1, Math.abs(o), Math.abs(s)) }, multiplyScalar(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t }, multiplyScalarAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t[3] = n[3] + a[3] * r, t }, mul: c, sub: s + }); function f(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = a[0]; const s = a[1]; const M = a[2]; const f = a[3]; const l = a[4]; const v = a[5]; return t[0] = r * c + e * s, t[1] = u * c + o * s, t[2] = r * M + e * f, t[3] = u * M + o * f, t[4] = r * l + e * v + i, t[5] = u * l + o * v + h, t } function l(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t[3] = n[3] - a[3], t[4] = n[4] - a[4], t[5] = n[5] - a[5], t } const v = f; const b = l; const m = Object.freeze({ + __proto__: null, create() { const t = new a(6); return a != Float32Array && (t[1] = 0, t[2] = 0, t[4] = 0, t[5] = 0), t[0] = 1, t[3] = 1, t }, clone(t) { const n = new a(6); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n[4] = t[4], n[5] = t[5], n }, copy(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t }, identity(t) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 1, t[4] = 0, t[5] = 0, t }, fromValues(t, n, r, u, e, o) { const i = new a(6); return i[0] = t, i[1] = n, i[2] = r, i[3] = u, i[4] = e, i[5] = o, i }, set(t, n, a, r, u, e, o) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t[4] = e, t[5] = o, t }, invert(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; let h = a * e - r * u; return h ? (h = 1 / h, t[0] = e * h, t[1] = -r * h, t[2] = -u * h, t[3] = a * h, t[4] = (u * i - e * o) * h, t[5] = (r * o - a * i) * h, t) : null }, determinant(t) { return t[0] * t[3] - t[1] * t[2] }, multiply: f, rotate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = Math.sin(a); const s = Math.cos(a); return t[0] = r * s + e * c, t[1] = u * s + o * c, t[2] = r * -c + e * s, t[3] = u * -c + o * s, t[4] = i, t[5] = h, t }, scale(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = a[0]; const s = a[1]; return t[0] = r * c, t[1] = u * c, t[2] = e * s, t[3] = o * s, t[4] = i, t[5] = h, t }, translate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = a[0]; const s = a[1]; return t[0] = r, t[1] = u, t[2] = e, t[3] = o, t[4] = r * c + e * s + i, t[5] = u * c + o * s + h, t }, fromRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = r, t[1] = a, t[2] = -a, t[3] = r, t[4] = 0, t[5] = 0, t }, fromScaling(t, n) { return t[0] = n[0], t[1] = 0, t[2] = 0, t[3] = n[1], t[4] = 0, t[5] = 0, t }, fromTranslation(t, n) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 1, t[4] = n[0], t[5] = n[1], t }, str(t) { return 'mat2d(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ', ' + t[4] + ', ' + t[5] + ')' }, frob(t) { return Math.hypot(t[0], t[1], t[2], t[3], t[4], t[5], 1) }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t[4] = n[4] + a[4], t[5] = n[5] + a[5], t }, subtract: l, multiplyScalar(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t[4] = n[4] * a, t[5] = n[5] * a, t }, multiplyScalarAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t[3] = n[3] + a[3] * r, t[4] = n[4] + a[4] * r, t[5] = n[5] + a[5] * r, t }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] && t[4] === n[4] && t[5] === n[5] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = t[4]; const h = t[5]; const c = a[0]; const s = a[1]; const M = a[2]; const f = a[3]; const l = a[4]; const v = a[5]; return Math.abs(r - c) <= n * Math.max(1, Math.abs(r), Math.abs(c)) && Math.abs(u - s) <= n * Math.max(1, Math.abs(u), Math.abs(s)) && Math.abs(e - M) <= n * Math.max(1, Math.abs(e), Math.abs(M)) && Math.abs(o - f) <= n * Math.max(1, Math.abs(o), Math.abs(f)) && Math.abs(i - l) <= n * Math.max(1, Math.abs(i), Math.abs(l)) && Math.abs(h - v) <= n * Math.max(1, Math.abs(h), Math.abs(v)) }, mul: v, sub: b + }); function d() { const t = new a(9); return a != Float32Array && (t[1] = 0, t[2] = 0, t[3] = 0, t[5] = 0, t[6] = 0, t[7] = 0), t[0] = 1, t[4] = 1, t[8] = 1, t } function p(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = n[8]; const f = a[0]; const l = a[1]; const v = a[2]; const b = a[3]; const m = a[4]; const d = a[5]; const p = a[6]; const x = a[7]; const y = a[8]; return t[0] = f * r + l * o + v * c, t[1] = f * u + l * i + v * s, t[2] = f * e + l * h + v * M, t[3] = b * r + m * o + d * c, t[4] = b * u + m * i + d * s, t[5] = b * e + m * h + d * M, t[6] = p * r + x * o + y * c, t[7] = p * u + x * i + y * s, t[8] = p * e + x * h + y * M, t } function x(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t[3] = n[3] - a[3], t[4] = n[4] - a[4], t[5] = n[5] - a[5], t[6] = n[6] - a[6], t[7] = n[7] - a[7], t[8] = n[8] - a[8], t } const y = p; const q = x; const g = Object.freeze({ + __proto__: null, create: d, fromMat4(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[4], t[4] = n[5], t[5] = n[6], t[6] = n[8], t[7] = n[9], t[8] = n[10], t }, clone(t) { const n = new a(9); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n[4] = t[4], n[5] = t[5], n[6] = t[6], n[7] = t[7], n[8] = t[8], n }, copy(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t[8] = n[8], t }, fromValues(t, n, r, u, e, o, i, h, c) { const s = new a(9); return s[0] = t, s[1] = n, s[2] = r, s[3] = u, s[4] = e, s[5] = o, s[6] = i, s[7] = h, s[8] = c, s }, set(t, n, a, r, u, e, o, i, h, c) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t[4] = e, t[5] = o, t[6] = i, t[7] = h, t[8] = c, t }, identity(t) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 1, t[5] = 0, t[6] = 0, t[7] = 0, t[8] = 1, t }, transpose(t, n) { if (t === n) { const a = n[1]; const r = n[2]; const u = n[5]; t[1] = n[3], t[2] = n[6], t[3] = a, t[5] = n[7], t[6] = r, t[7] = u } else t[0] = n[0], t[1] = n[3], t[2] = n[6], t[3] = n[1], t[4] = n[4], t[5] = n[7], t[6] = n[2], t[7] = n[5], t[8] = n[8]; return t }, invert(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; const h = n[6]; const c = n[7]; const s = n[8]; const M = s * o - i * c; const f = -s * e + i * h; const l = c * e - o * h; let v = a * M + r * f + u * l; return v ? (v = 1 / v, t[0] = M * v, t[1] = (-s * r + u * c) * v, t[2] = (i * r - u * o) * v, t[3] = f * v, t[4] = (s * a - u * h) * v, t[5] = (-i * a + u * e) * v, t[6] = l * v, t[7] = (-c * a + r * h) * v, t[8] = (o * a - r * e) * v, t) : null }, adjoint(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; const h = n[6]; const c = n[7]; const s = n[8]; return t[0] = o * s - i * c, t[1] = u * c - r * s, t[2] = r * i - u * o, t[3] = i * h - e * s, t[4] = a * s - u * h, t[5] = u * e - a * i, t[6] = e * c - o * h, t[7] = r * h - a * c, t[8] = a * o - r * e, t }, determinant(t) { const n = t[0]; const a = t[1]; const r = t[2]; const u = t[3]; const e = t[4]; const o = t[5]; const i = t[6]; const h = t[7]; const c = t[8]; return n * (c * e - o * h) + a * (-c * u + o * i) + r * (h * u - e * i) }, multiply: p, translate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = n[8]; const f = a[0]; const l = a[1]; return t[0] = r, t[1] = u, t[2] = e, t[3] = o, t[4] = i, t[5] = h, t[6] = f * r + l * o + c, t[7] = f * u + l * i + s, t[8] = f * e + l * h + M, t }, rotate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = n[8]; const f = Math.sin(a); const l = Math.cos(a); return t[0] = l * r + f * o, t[1] = l * u + f * i, t[2] = l * e + f * h, t[3] = l * o - f * r, t[4] = l * i - f * u, t[5] = l * h - f * e, t[6] = c, t[7] = s, t[8] = M, t }, scale(t, n, a) { const r = a[0]; const u = a[1]; return t[0] = r * n[0], t[1] = r * n[1], t[2] = r * n[2], t[3] = u * n[3], t[4] = u * n[4], t[5] = u * n[5], t[6] = n[6], t[7] = n[7], t[8] = n[8], t }, fromTranslation(t, n) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 1, t[5] = 0, t[6] = n[0], t[7] = n[1], t[8] = 1, t }, fromRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = r, t[1] = a, t[2] = 0, t[3] = -a, t[4] = r, t[5] = 0, t[6] = 0, t[7] = 0, t[8] = 1, t }, fromScaling(t, n) { return t[0] = n[0], t[1] = 0, t[2] = 0, t[3] = 0, t[4] = n[1], t[5] = 0, t[6] = 0, t[7] = 0, t[8] = 1, t }, fromMat2d(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = 0, t[3] = n[2], t[4] = n[3], t[5] = 0, t[6] = n[4], t[7] = n[5], t[8] = 1, t }, fromQuat(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = a + a; const i = r + r; const h = u + u; const c = a * o; const s = r * o; const M = r * i; const f = u * o; const l = u * i; const v = u * h; const b = e * o; const m = e * i; const d = e * h; return t[0] = 1 - M - v, t[3] = s - d, t[6] = f + m, t[1] = s + d, t[4] = 1 - c - v, t[7] = l - b, t[2] = f - m, t[5] = l + b, t[8] = 1 - c - M, t }, normalFromMat4(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; const h = n[6]; const c = n[7]; const s = n[8]; const M = n[9]; const f = n[10]; const l = n[11]; const v = n[12]; const b = n[13]; const m = n[14]; const d = n[15]; const p = a * i - r * o; const x = a * h - u * o; const y = a * c - e * o; const q = r * h - u * i; const g = r * c - e * i; const _ = u * c - e * h; const A = s * b - M * v; const w = s * m - f * v; const z = s * d - l * v; const R = M * m - f * b; const O = M * d - l * b; const j = f * d - l * m; let E = p * j - x * O + y * R + q * z - g * w + _ * A; return E ? (E = 1 / E, t[0] = (i * j - h * O + c * R) * E, t[1] = (h * z - o * j - c * w) * E, t[2] = (o * O - i * z + c * A) * E, t[3] = (u * O - r * j - e * R) * E, t[4] = (a * j - u * z + e * w) * E, t[5] = (r * z - a * O - e * A) * E, t[6] = (b * _ - m * g + d * q) * E, t[7] = (m * y - v * _ - d * x) * E, t[8] = (v * g - b * y + d * p) * E, t) : null }, projection(t, n, a) { return t[0] = 2 / n, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = -2 / a, t[5] = 0, t[6] = -1, t[7] = 1, t[8] = 1, t }, str(t) { return 'mat3(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ', ' + t[4] + ', ' + t[5] + ', ' + t[6] + ', ' + t[7] + ', ' + t[8] + ')' }, frob(t) { return Math.hypot(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8]) }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t[4] = n[4] + a[4], t[5] = n[5] + a[5], t[6] = n[6] + a[6], t[7] = n[7] + a[7], t[8] = n[8] + a[8], t }, subtract: x, multiplyScalar(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t[4] = n[4] * a, t[5] = n[5] * a, t[6] = n[6] * a, t[7] = n[7] * a, t[8] = n[8] * a, t }, multiplyScalarAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t[3] = n[3] + a[3] * r, t[4] = n[4] + a[4] * r, t[5] = n[5] + a[5] * r, t[6] = n[6] + a[6] * r, t[7] = n[7] + a[7] * r, t[8] = n[8] + a[8] * r, t }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] && t[4] === n[4] && t[5] === n[5] && t[6] === n[6] && t[7] === n[7] && t[8] === n[8] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = t[4]; const h = t[5]; const c = t[6]; const s = t[7]; const M = t[8]; const f = a[0]; const l = a[1]; const v = a[2]; const b = a[3]; const m = a[4]; const d = a[5]; const p = a[6]; const x = a[7]; const y = a[8]; return Math.abs(r - f) <= n * Math.max(1, Math.abs(r), Math.abs(f)) && Math.abs(u - l) <= n * Math.max(1, Math.abs(u), Math.abs(l)) && Math.abs(e - v) <= n * Math.max(1, Math.abs(e), Math.abs(v)) && Math.abs(o - b) <= n * Math.max(1, Math.abs(o), Math.abs(b)) && Math.abs(i - m) <= n * Math.max(1, Math.abs(i), Math.abs(m)) && Math.abs(h - d) <= n * Math.max(1, Math.abs(h), Math.abs(d)) && Math.abs(c - p) <= n * Math.max(1, Math.abs(c), Math.abs(p)) && Math.abs(s - x) <= n * Math.max(1, Math.abs(s), Math.abs(x)) && Math.abs(M - y) <= n * Math.max(1, Math.abs(M), Math.abs(y)) }, mul: y, sub: q + }); function _(t) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = 1, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 1, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t } function A(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = n[8]; const f = n[9]; const l = n[10]; const v = n[11]; const b = n[12]; const m = n[13]; const d = n[14]; const p = n[15]; let x = a[0]; let y = a[1]; let q = a[2]; let g = a[3]; return t[0] = x * r + y * i + q * M + g * b, t[1] = x * u + y * h + q * f + g * m, t[2] = x * e + y * c + q * l + g * d, t[3] = x * o + y * s + q * v + g * p, x = a[4], y = a[5], q = a[6], g = a[7], t[4] = x * r + y * i + q * M + g * b, t[5] = x * u + y * h + q * f + g * m, t[6] = x * e + y * c + q * l + g * d, t[7] = x * o + y * s + q * v + g * p, x = a[8], y = a[9], q = a[10], g = a[11], t[8] = x * r + y * i + q * M + g * b, t[9] = x * u + y * h + q * f + g * m, t[10] = x * e + y * c + q * l + g * d, t[11] = x * o + y * s + q * v + g * p, x = a[12], y = a[13], q = a[14], g = a[15], t[12] = x * r + y * i + q * M + g * b, t[13] = x * u + y * h + q * f + g * m, t[14] = x * e + y * c + q * l + g * d, t[15] = x * o + y * s + q * v + g * p, t } function w(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = r + r; const h = u + u; const c = e + e; const s = r * i; const M = r * h; const f = r * c; const l = u * h; const v = u * c; const b = e * c; const m = o * i; const d = o * h; const p = o * c; return t[0] = 1 - (l + b), t[1] = M + p, t[2] = f - d, t[3] = 0, t[4] = M - p, t[5] = 1 - (s + b), t[6] = v + m, t[7] = 0, t[8] = f + d, t[9] = v - m, t[10] = 1 - (s + l), t[11] = 0, t[12] = a[0], t[13] = a[1], t[14] = a[2], t[15] = 1, t } function z(t, n) { return t[0] = n[12], t[1] = n[13], t[2] = n[14], t } function R(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[4]; const o = n[5]; const i = n[6]; const h = n[8]; const c = n[9]; const s = n[10]; return t[0] = Math.hypot(a, r, u), t[1] = Math.hypot(e, o, i), t[2] = Math.hypot(h, c, s), t } function O(t, n) { const r = new a(3); R(r, n); const u = 1 / r[0]; const e = 1 / r[1]; const o = 1 / r[2]; const i = n[0] * u; const h = n[1] * e; const c = n[2] * o; const s = n[4] * u; const M = n[5] * e; const f = n[6] * o; const l = n[8] * u; const v = n[9] * e; const b = n[10] * o; const m = i + M + b; let d = 0; return m > 0 ? (d = 2 * Math.sqrt(m + 1), t[3] = 0.25 * d, t[0] = (f - v) / d, t[1] = (l - c) / d, t[2] = (h - s) / d) : i > M && i > b ? (d = 2 * Math.sqrt(1 + i - M - b), t[3] = (f - v) / d, t[0] = 0.25 * d, t[1] = (h + s) / d, t[2] = (l + c) / d) : M > b ? (d = 2 * Math.sqrt(1 + M - i - b), t[3] = (l - c) / d, t[0] = (h + s) / d, t[1] = 0.25 * d, t[2] = (f + v) / d) : (d = 2 * Math.sqrt(1 + b - i - M), t[3] = (h - s) / d, t[0] = (l + c) / d, t[1] = (f + v) / d, t[2] = 0.25 * d), t } function j(t, n, a, r, u) { const e = 1 / Math.tan(n / 2); if (t[0] = e / a, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = e, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[11] = -1, t[12] = 0, t[13] = 0, t[15] = 0, u != null && u !== 1 / 0) { const o = 1 / (r - u); t[10] = (u + r) * o, t[14] = 2 * u * r * o } else t[10] = -1, t[14] = -2 * r; return t } const E = j; function P(t, n, a, r, u, e, o) { const i = 1 / (n - a); const h = 1 / (r - u); const c = 1 / (e - o); return t[0] = -2 * i, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = -2 * h, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 2 * c, t[11] = 0, t[12] = (n + a) * i, t[13] = (u + r) * h, t[14] = (o + e) * c, t[15] = 1, t } const T = P; function S(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t[3] = n[3] - a[3], t[4] = n[4] - a[4], t[5] = n[5] - a[5], t[6] = n[6] - a[6], t[7] = n[7] - a[7], t[8] = n[8] - a[8], t[9] = n[9] - a[9], t[10] = n[10] - a[10], t[11] = n[11] - a[11], t[12] = n[12] - a[12], t[13] = n[13] - a[13], t[14] = n[14] - a[14], t[15] = n[15] - a[15], t } const D = A; const F = S; const I = Object.freeze({ + __proto__: null, create() { const t = new a(16); return a != Float32Array && (t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0), t[0] = 1, t[5] = 1, t[10] = 1, t[15] = 1, t }, clone(t) { const n = new a(16); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n[4] = t[4], n[5] = t[5], n[6] = t[6], n[7] = t[7], n[8] = t[8], n[9] = t[9], n[10] = t[10], n[11] = t[11], n[12] = t[12], n[13] = t[13], n[14] = t[14], n[15] = t[15], n }, copy(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t[8] = n[8], t[9] = n[9], t[10] = n[10], t[11] = n[11], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15], t }, fromValues(t, n, r, u, e, o, i, h, c, s, M, f, l, v, b, m) { const d = new a(16); return d[0] = t, d[1] = n, d[2] = r, d[3] = u, d[4] = e, d[5] = o, d[6] = i, d[7] = h, d[8] = c, d[9] = s, d[10] = M, d[11] = f, d[12] = l, d[13] = v, d[14] = b, d[15] = m, d }, set(t, n, a, r, u, e, o, i, h, c, s, M, f, l, v, b, m) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t[4] = e, t[5] = o, t[6] = i, t[7] = h, t[8] = c, t[9] = s, t[10] = M, t[11] = f, t[12] = l, t[13] = v, t[14] = b, t[15] = m, t }, identity: _, transpose(t, n) { if (t === n) { const a = n[1]; const r = n[2]; const u = n[3]; const e = n[6]; const o = n[7]; const i = n[11]; t[1] = n[4], t[2] = n[8], t[3] = n[12], t[4] = a, t[6] = n[9], t[7] = n[13], t[8] = r, t[9] = e, t[11] = n[14], t[12] = u, t[13] = o, t[14] = i } else t[0] = n[0], t[1] = n[4], t[2] = n[8], t[3] = n[12], t[4] = n[1], t[5] = n[5], t[6] = n[9], t[7] = n[13], t[8] = n[2], t[9] = n[6], t[10] = n[10], t[11] = n[14], t[12] = n[3], t[13] = n[7], t[14] = n[11], t[15] = n[15]; return t }, invert(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; const h = n[6]; const c = n[7]; const s = n[8]; const M = n[9]; const f = n[10]; const l = n[11]; const v = n[12]; const b = n[13]; const m = n[14]; const d = n[15]; const p = a * i - r * o; const x = a * h - u * o; const y = a * c - e * o; const q = r * h - u * i; const g = r * c - e * i; const _ = u * c - e * h; const A = s * b - M * v; const w = s * m - f * v; const z = s * d - l * v; const R = M * m - f * b; const O = M * d - l * b; const j = f * d - l * m; let E = p * j - x * O + y * R + q * z - g * w + _ * A; return E ? (E = 1 / E, t[0] = (i * j - h * O + c * R) * E, t[1] = (u * O - r * j - e * R) * E, t[2] = (b * _ - m * g + d * q) * E, t[3] = (f * g - M * _ - l * q) * E, t[4] = (h * z - o * j - c * w) * E, t[5] = (a * j - u * z + e * w) * E, t[6] = (m * y - v * _ - d * x) * E, t[7] = (s * _ - f * y + l * x) * E, t[8] = (o * O - i * z + c * A) * E, t[9] = (r * z - a * O - e * A) * E, t[10] = (v * g - b * y + d * p) * E, t[11] = (M * y - s * g - l * p) * E, t[12] = (i * w - o * R - h * A) * E, t[13] = (a * R - r * w + u * A) * E, t[14] = (b * x - v * q - m * p) * E, t[15] = (s * q - M * x + f * p) * E, t) : null }, adjoint(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = n[4]; const i = n[5]; const h = n[6]; const c = n[7]; const s = n[8]; const M = n[9]; const f = n[10]; const l = n[11]; const v = n[12]; const b = n[13]; const m = n[14]; const d = n[15]; const p = a * i - r * o; const x = a * h - u * o; const y = a * c - e * o; const q = r * h - u * i; const g = r * c - e * i; const _ = u * c - e * h; const A = s * b - M * v; const w = s * m - f * v; const z = s * d - l * v; const R = M * m - f * b; const O = M * d - l * b; const j = f * d - l * m; return t[0] = i * j - h * O + c * R, t[1] = u * O - r * j - e * R, t[2] = b * _ - m * g + d * q, t[3] = f * g - M * _ - l * q, t[4] = h * z - o * j - c * w, t[5] = a * j - u * z + e * w, t[6] = m * y - v * _ - d * x, t[7] = s * _ - f * y + l * x, t[8] = o * O - i * z + c * A, t[9] = r * z - a * O - e * A, t[10] = v * g - b * y + d * p, t[11] = M * y - s * g - l * p, t[12] = i * w - o * R - h * A, t[13] = a * R - r * w + u * A, t[14] = b * x - v * q - m * p, t[15] = s * q - M * x + f * p, t }, determinant(t) { const n = t[0]; const a = t[1]; const r = t[2]; const u = t[3]; const e = t[4]; const o = t[5]; const i = t[6]; const h = t[7]; const c = t[8]; const s = t[9]; const M = t[10]; const f = t[11]; const l = t[12]; const v = t[13]; const b = t[14]; const m = n * o - a * e; const d = n * i - r * e; const p = a * i - r * o; const x = c * v - s * l; const y = c * b - M * l; const q = s * b - M * v; return h * (n * q - a * y + r * x) - u * (e * q - o * y + i * x) + t[15] * (c * p - s * d + M * m) - f * (l * p - v * d + b * m) }, multiply: A, translate(t, n, a) { let r; let u; let e; let o; let i; let h; let c; let s; let M; let f; let l; let v; const b = a[0]; const m = a[1]; const d = a[2]; return n === t ? (t[12] = n[0] * b + n[4] * m + n[8] * d + n[12], t[13] = n[1] * b + n[5] * m + n[9] * d + n[13], t[14] = n[2] * b + n[6] * m + n[10] * d + n[14], t[15] = n[3] * b + n[7] * m + n[11] * d + n[15]) : (r = n[0], u = n[1], e = n[2], o = n[3], i = n[4], h = n[5], c = n[6], s = n[7], M = n[8], f = n[9], l = n[10], v = n[11], t[0] = r, t[1] = u, t[2] = e, t[3] = o, t[4] = i, t[5] = h, t[6] = c, t[7] = s, t[8] = M, t[9] = f, t[10] = l, t[11] = v, t[12] = r * b + i * m + M * d + n[12], t[13] = u * b + h * m + f * d + n[13], t[14] = e * b + c * m + l * d + n[14], t[15] = o * b + s * m + v * d + n[15]), t }, scale(t, n, a) { const r = a[0]; const u = a[1]; const e = a[2]; return t[0] = n[0] * r, t[1] = n[1] * r, t[2] = n[2] * r, t[3] = n[3] * r, t[4] = n[4] * u, t[5] = n[5] * u, t[6] = n[6] * u, t[7] = n[7] * u, t[8] = n[8] * e, t[9] = n[9] * e, t[10] = n[10] * e, t[11] = n[11] * e, t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15], t }, rotate(t, a, r, u) { let e; let o; let i; let h; let c; let s; let M; let f; let l; let v; let b; let m; let d; let p; let x; let y; let q; let g; let _; let A; let w; let z; let R; let O; let j = u[0]; let E = u[1]; let P = u[2]; let T = Math.hypot(j, E, P); return T < n ? null : (j *= T = 1 / T, E *= T, P *= T, e = Math.sin(r), i = 1 - (o = Math.cos(r)), h = a[0], c = a[1], s = a[2], M = a[3], f = a[4], l = a[5], v = a[6], b = a[7], m = a[8], d = a[9], p = a[10], x = a[11], y = j * j * i + o, q = E * j * i + P * e, g = P * j * i - E * e, _ = j * E * i - P * e, A = E * E * i + o, w = P * E * i + j * e, z = j * P * i + E * e, R = E * P * i - j * e, O = P * P * i + o, t[0] = h * y + f * q + m * g, t[1] = c * y + l * q + d * g, t[2] = s * y + v * q + p * g, t[3] = M * y + b * q + x * g, t[4] = h * _ + f * A + m * w, t[5] = c * _ + l * A + d * w, t[6] = s * _ + v * A + p * w, t[7] = M * _ + b * A + x * w, t[8] = h * z + f * R + m * O, t[9] = c * z + l * R + d * O, t[10] = s * z + v * R + p * O, t[11] = M * z + b * R + x * O, a !== t && (t[12] = a[12], t[13] = a[13], t[14] = a[14], t[15] = a[15]), t) }, rotateX(t, n, a) { const r = Math.sin(a); const u = Math.cos(a); const e = n[4]; const o = n[5]; const i = n[6]; const h = n[7]; const c = n[8]; const s = n[9]; const M = n[10]; const f = n[11]; return n !== t && (t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15]), t[4] = e * u + c * r, t[5] = o * u + s * r, t[6] = i * u + M * r, t[7] = h * u + f * r, t[8] = c * u - e * r, t[9] = s * u - o * r, t[10] = M * u - i * r, t[11] = f * u - h * r, t }, rotateY(t, n, a) { const r = Math.sin(a); const u = Math.cos(a); const e = n[0]; const o = n[1]; const i = n[2]; const h = n[3]; const c = n[8]; const s = n[9]; const M = n[10]; const f = n[11]; return n !== t && (t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15]), t[0] = e * u - c * r, t[1] = o * u - s * r, t[2] = i * u - M * r, t[3] = h * u - f * r, t[8] = e * r + c * u, t[9] = o * r + s * u, t[10] = i * r + M * u, t[11] = h * r + f * u, t }, rotateZ(t, n, a) { const r = Math.sin(a); const u = Math.cos(a); const e = n[0]; const o = n[1]; const i = n[2]; const h = n[3]; const c = n[4]; const s = n[5]; const M = n[6]; const f = n[7]; return n !== t && (t[8] = n[8], t[9] = n[9], t[10] = n[10], t[11] = n[11], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15]), t[0] = e * u + c * r, t[1] = o * u + s * r, t[2] = i * u + M * r, t[3] = h * u + f * r, t[4] = c * u - e * r, t[5] = s * u - o * r, t[6] = M * u - i * r, t[7] = f * u - h * r, t }, fromTranslation(t, n) { return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = 1, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 1, t[11] = 0, t[12] = n[0], t[13] = n[1], t[14] = n[2], t[15] = 1, t }, fromScaling(t, n) { return t[0] = n[0], t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = n[1], t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = n[2], t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t }, fromRotation(t, a, r) { let u; let e; let o; let i = r[0]; let h = r[1]; let c = r[2]; let s = Math.hypot(i, h, c); return s < n ? null : (i *= s = 1 / s, h *= s, c *= s, u = Math.sin(a), o = 1 - (e = Math.cos(a)), t[0] = i * i * o + e, t[1] = h * i * o + c * u, t[2] = c * i * o - h * u, t[3] = 0, t[4] = i * h * o - c * u, t[5] = h * h * o + e, t[6] = c * h * o + i * u, t[7] = 0, t[8] = i * c * o + h * u, t[9] = h * c * o - i * u, t[10] = c * c * o + e, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t) }, fromXRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = r, t[6] = a, t[7] = 0, t[8] = 0, t[9] = -a, t[10] = r, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t }, fromYRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = r, t[1] = 0, t[2] = -a, t[3] = 0, t[4] = 0, t[5] = 1, t[6] = 0, t[7] = 0, t[8] = a, t[9] = 0, t[10] = r, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t }, fromZRotation(t, n) { const a = Math.sin(n); const r = Math.cos(n); return t[0] = r, t[1] = a, t[2] = 0, t[3] = 0, t[4] = -a, t[5] = r, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 1, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t }, fromRotationTranslation: w, fromQuat2(t, n) { const r = new a(3); const u = -n[0]; const e = -n[1]; const o = -n[2]; const i = n[3]; const h = n[4]; const c = n[5]; const s = n[6]; const M = n[7]; const f = u * u + e * e + o * o + i * i; return f > 0 ? (r[0] = 2 * (h * i + M * u + c * o - s * e) / f, r[1] = 2 * (c * i + M * e + s * u - h * o) / f, r[2] = 2 * (s * i + M * o + h * e - c * u) / f) : (r[0] = 2 * (h * i + M * u + c * o - s * e), r[1] = 2 * (c * i + M * e + s * u - h * o), r[2] = 2 * (s * i + M * o + h * e - c * u)), w(t, n, r), t }, getTranslation: z, getScaling: R, getRotation: O, decompose(t, n, a, r) { n[0] = r[12], n[1] = r[13], n[2] = r[14]; const u = r[0]; const e = r[1]; const o = r[2]; const i = r[4]; const h = r[5]; const c = r[6]; const s = r[8]; const M = r[9]; const f = r[10]; a[0] = Math.hypot(u, e, o), a[1] = Math.hypot(i, h, c), a[2] = Math.hypot(s, M, f); const l = 1 / a[0]; const v = 1 / a[1]; const b = 1 / a[2]; const m = u * l; const d = e * v; const p = o * b; const x = i * l; const y = h * v; const q = c * b; const g = s * l; const _ = M * v; const A = f * b; const w = m + y + A; let z = 0; return w > 0 ? (z = 2 * Math.sqrt(w + 1), t[3] = 0.25 * z, t[0] = (q - _) / z, t[1] = (g - p) / z, t[2] = (d - x) / z) : m > y && m > A ? (z = 2 * Math.sqrt(1 + m - y - A), t[3] = (q - _) / z, t[0] = 0.25 * z, t[1] = (d + x) / z, t[2] = (g + p) / z) : y > A ? (z = 2 * Math.sqrt(1 + y - m - A), t[3] = (g - p) / z, t[0] = (d + x) / z, t[1] = 0.25 * z, t[2] = (q + _) / z) : (z = 2 * Math.sqrt(1 + A - m - y), t[3] = (d - x) / z, t[0] = (g + p) / z, t[1] = (q + _) / z, t[2] = 0.25 * z), t }, fromRotationTranslationScale(t, n, a, r) { const u = n[0]; const e = n[1]; const o = n[2]; const i = n[3]; const h = u + u; const c = e + e; const s = o + o; const M = u * h; const f = u * c; const l = u * s; const v = e * c; const b = e * s; const m = o * s; const d = i * h; const p = i * c; const x = i * s; const y = r[0]; const q = r[1]; const g = r[2]; return t[0] = (1 - (v + m)) * y, t[1] = (f + x) * y, t[2] = (l - p) * y, t[3] = 0, t[4] = (f - x) * q, t[5] = (1 - (M + m)) * q, t[6] = (b + d) * q, t[7] = 0, t[8] = (l + p) * g, t[9] = (b - d) * g, t[10] = (1 - (M + v)) * g, t[11] = 0, t[12] = a[0], t[13] = a[1], t[14] = a[2], t[15] = 1, t }, fromRotationTranslationScaleOrigin(t, n, a, r, u) { const e = n[0]; const o = n[1]; const i = n[2]; const h = n[3]; const c = e + e; const s = o + o; const M = i + i; const f = e * c; const l = e * s; const v = e * M; const b = o * s; const m = o * M; const d = i * M; const p = h * c; const x = h * s; const y = h * M; const q = r[0]; const g = r[1]; const _ = r[2]; const A = u[0]; const w = u[1]; const z = u[2]; const R = (1 - (b + d)) * q; const O = (l + y) * q; const j = (v - x) * q; const E = (l - y) * g; const P = (1 - (f + d)) * g; const T = (m + p) * g; const S = (v + x) * _; const D = (m - p) * _; const F = (1 - (f + b)) * _; return t[0] = R, t[1] = O, t[2] = j, t[3] = 0, t[4] = E, t[5] = P, t[6] = T, t[7] = 0, t[8] = S, t[9] = D, t[10] = F, t[11] = 0, t[12] = a[0] + A - (R * A + E * w + S * z), t[13] = a[1] + w - (O * A + P * w + D * z), t[14] = a[2] + z - (j * A + T * w + F * z), t[15] = 1, t }, fromQuat(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = a + a; const i = r + r; const h = u + u; const c = a * o; const s = r * o; const M = r * i; const f = u * o; const l = u * i; const v = u * h; const b = e * o; const m = e * i; const d = e * h; return t[0] = 1 - M - v, t[1] = s + d, t[2] = f - m, t[3] = 0, t[4] = s - d, t[5] = 1 - c - v, t[6] = l + b, t[7] = 0, t[8] = f + m, t[9] = l - b, t[10] = 1 - c - M, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t }, frustum(t, n, a, r, u, e, o) { const i = 1 / (a - n); const h = 1 / (u - r); const c = 1 / (e - o); return t[0] = 2 * e * i, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = 2 * e * h, t[6] = 0, t[7] = 0, t[8] = (a + n) * i, t[9] = (u + r) * h, t[10] = (o + e) * c, t[11] = -1, t[12] = 0, t[13] = 0, t[14] = o * e * 2 * c, t[15] = 0, t }, perspectiveNO: j, perspective: E, perspectiveZO(t, n, a, r, u) { const e = 1 / Math.tan(n / 2); if (t[0] = e / a, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = e, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[11] = -1, t[12] = 0, t[13] = 0, t[15] = 0, u != null && u !== 1 / 0) { const o = 1 / (r - u); t[10] = u * o, t[14] = u * r * o } else t[10] = -1, t[14] = -r; return t }, perspectiveFromFieldOfView(t, n, a, r) { const u = Math.tan(n.upDegrees * Math.PI / 180); const e = Math.tan(n.downDegrees * Math.PI / 180); const o = Math.tan(n.leftDegrees * Math.PI / 180); const i = Math.tan(n.rightDegrees * Math.PI / 180); const h = 2 / (o + i); const c = 2 / (u + e); return t[0] = h, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = c, t[6] = 0, t[7] = 0, t[8] = -(o - i) * h * 0.5, t[9] = (u - e) * c * 0.5, t[10] = r / (a - r), t[11] = -1, t[12] = 0, t[13] = 0, t[14] = r * a / (a - r), t[15] = 0, t }, orthoNO: P, ortho: T, orthoZO(t, n, a, r, u, e, o) { const i = 1 / (n - a); const h = 1 / (r - u); const c = 1 / (e - o); return t[0] = -2 * i, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = -2 * h, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = c, t[11] = 0, t[12] = (n + a) * i, t[13] = (u + r) * h, t[14] = e * c, t[15] = 1, t }, lookAt(t, a, r, u) { let e; let o; let i; let h; let c; let s; let M; let f; let l; let v; const b = a[0]; const m = a[1]; const d = a[2]; const p = u[0]; const x = u[1]; const y = u[2]; const q = r[0]; const g = r[1]; const A = r[2]; return Math.abs(b - q) < n && Math.abs(m - g) < n && Math.abs(d - A) < n ? _(t) : (M = b - q, f = m - g, l = d - A, e = x * (l *= v = 1 / Math.hypot(M, f, l)) - y * (f *= v), o = y * (M *= v) - p * l, i = p * f - x * M, (v = Math.hypot(e, o, i)) ? (e *= v = 1 / v, o *= v, i *= v) : (e = 0, o = 0, i = 0), h = f * i - l * o, c = l * e - M * i, s = M * o - f * e, (v = Math.hypot(h, c, s)) ? (h *= v = 1 / v, c *= v, s *= v) : (h = 0, c = 0, s = 0), t[0] = e, t[1] = h, t[2] = M, t[3] = 0, t[4] = o, t[5] = c, t[6] = f, t[7] = 0, t[8] = i, t[9] = s, t[10] = l, t[11] = 0, t[12] = -(e * b + o * m + i * d), t[13] = -(h * b + c * m + s * d), t[14] = -(M * b + f * m + l * d), t[15] = 1, t) }, targetTo(t, n, a, r) { const u = n[0]; const e = n[1]; const o = n[2]; const i = r[0]; const h = r[1]; const c = r[2]; let s = u - a[0]; let M = e - a[1]; let f = o - a[2]; let l = s * s + M * M + f * f; l > 0 && (s *= l = 1 / Math.sqrt(l), M *= l, f *= l); let v = h * f - c * M; let b = c * s - i * f; let m = i * M - h * s; return (l = v * v + b * b + m * m) > 0 && (v *= l = 1 / Math.sqrt(l), b *= l, m *= l), t[0] = v, t[1] = b, t[2] = m, t[3] = 0, t[4] = M * m - f * b, t[5] = f * v - s * m, t[6] = s * b - M * v, t[7] = 0, t[8] = s, t[9] = M, t[10] = f, t[11] = 0, t[12] = u, t[13] = e, t[14] = o, t[15] = 1, t }, str(t) { return 'mat4(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ', ' + t[4] + ', ' + t[5] + ', ' + t[6] + ', ' + t[7] + ', ' + t[8] + ', ' + t[9] + ', ' + t[10] + ', ' + t[11] + ', ' + t[12] + ', ' + t[13] + ', ' + t[14] + ', ' + t[15] + ')' }, frob(t) { return Math.hypot(t[0], t[1], t[2], t[3], t[4], t[5], t[6], t[7], t[8], t[9], t[10], t[11], t[12], t[13], t[14], t[15]) }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t[4] = n[4] + a[4], t[5] = n[5] + a[5], t[6] = n[6] + a[6], t[7] = n[7] + a[7], t[8] = n[8] + a[8], t[9] = n[9] + a[9], t[10] = n[10] + a[10], t[11] = n[11] + a[11], t[12] = n[12] + a[12], t[13] = n[13] + a[13], t[14] = n[14] + a[14], t[15] = n[15] + a[15], t }, subtract: S, multiplyScalar(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t[4] = n[4] * a, t[5] = n[5] * a, t[6] = n[6] * a, t[7] = n[7] * a, t[8] = n[8] * a, t[9] = n[9] * a, t[10] = n[10] * a, t[11] = n[11] * a, t[12] = n[12] * a, t[13] = n[13] * a, t[14] = n[14] * a, t[15] = n[15] * a, t }, multiplyScalarAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t[3] = n[3] + a[3] * r, t[4] = n[4] + a[4] * r, t[5] = n[5] + a[5] * r, t[6] = n[6] + a[6] * r, t[7] = n[7] + a[7] * r, t[8] = n[8] + a[8] * r, t[9] = n[9] + a[9] * r, t[10] = n[10] + a[10] * r, t[11] = n[11] + a[11] * r, t[12] = n[12] + a[12] * r, t[13] = n[13] + a[13] * r, t[14] = n[14] + a[14] * r, t[15] = n[15] + a[15] * r, t }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] && t[4] === n[4] && t[5] === n[5] && t[6] === n[6] && t[7] === n[7] && t[8] === n[8] && t[9] === n[9] && t[10] === n[10] && t[11] === n[11] && t[12] === n[12] && t[13] === n[13] && t[14] === n[14] && t[15] === n[15] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = t[4]; const h = t[5]; const c = t[6]; const s = t[7]; const M = t[8]; const f = t[9]; const l = t[10]; const v = t[11]; const b = t[12]; const m = t[13]; const d = t[14]; const p = t[15]; const x = a[0]; const y = a[1]; const q = a[2]; const g = a[3]; const _ = a[4]; const A = a[5]; const w = a[6]; const z = a[7]; const R = a[8]; const O = a[9]; const j = a[10]; const E = a[11]; const P = a[12]; const T = a[13]; const S = a[14]; const D = a[15]; return Math.abs(r - x) <= n * Math.max(1, Math.abs(r), Math.abs(x)) && Math.abs(u - y) <= n * Math.max(1, Math.abs(u), Math.abs(y)) && Math.abs(e - q) <= n * Math.max(1, Math.abs(e), Math.abs(q)) && Math.abs(o - g) <= n * Math.max(1, Math.abs(o), Math.abs(g)) && Math.abs(i - _) <= n * Math.max(1, Math.abs(i), Math.abs(_)) && Math.abs(h - A) <= n * Math.max(1, Math.abs(h), Math.abs(A)) && Math.abs(c - w) <= n * Math.max(1, Math.abs(c), Math.abs(w)) && Math.abs(s - z) <= n * Math.max(1, Math.abs(s), Math.abs(z)) && Math.abs(M - R) <= n * Math.max(1, Math.abs(M), Math.abs(R)) && Math.abs(f - O) <= n * Math.max(1, Math.abs(f), Math.abs(O)) && Math.abs(l - j) <= n * Math.max(1, Math.abs(l), Math.abs(j)) && Math.abs(v - E) <= n * Math.max(1, Math.abs(v), Math.abs(E)) && Math.abs(b - P) <= n * Math.max(1, Math.abs(b), Math.abs(P)) && Math.abs(m - T) <= n * Math.max(1, Math.abs(m), Math.abs(T)) && Math.abs(d - S) <= n * Math.max(1, Math.abs(d), Math.abs(S)) && Math.abs(p - D) <= n * Math.max(1, Math.abs(p), Math.abs(D)) }, mul: D, sub: F + }); function L() { const t = new a(3); return a != Float32Array && (t[0] = 0, t[1] = 0, t[2] = 0), t } function V(t) { const n = t[0]; const a = t[1]; const r = t[2]; return Math.hypot(n, a, r) } function k(t, n, r) { const u = new a(3); return u[0] = t, u[1] = n, u[2] = r, u } function Q(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t } function Y(t, n, a) { return t[0] = n[0] * a[0], t[1] = n[1] * a[1], t[2] = n[2] * a[2], t } function Z(t, n, a) { return t[0] = n[0] / a[0], t[1] = n[1] / a[1], t[2] = n[2] / a[2], t } function N(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; const u = n[2] - t[2]; return Math.hypot(a, r, u) } function X(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; const u = n[2] - t[2]; return a * a + r * r + u * u } function B(t) { const n = t[0]; const a = t[1]; const r = t[2]; return n * n + a * a + r * r } function U(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; let e = a * a + r * r + u * u; return e > 0 && (e = 1 / Math.sqrt(e)), t[0] = n[0] * e, t[1] = n[1] * e, t[2] = n[2] * e, t } function G(t, n) { return t[0] * n[0] + t[1] * n[1] + t[2] * n[2] } function W(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = a[0]; const i = a[1]; const h = a[2]; return t[0] = u * h - e * i, t[1] = e * o - r * h, t[2] = r * i - u * o, t } let C; const H = Q; const J = Y; const K = Z; const $ = N; const tt = X; const nt = V; const at = B; const rt = (C = L(), function (t, n, a, r, u, e) { let o; let i; for (n || (n = 3), a || (a = 0), i = r ? Math.min(r * n + a, t.length) : t.length, o = a; o < i; o += n)C[0] = t[o], C[1] = t[o + 1], C[2] = t[o + 2], u(C, C, e), t[o] = C[0], t[o + 1] = C[1], t[o + 2] = C[2]; return t }); const ut = Object.freeze({ + __proto__: null, create: L, clone(t) { const n = new a(3); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n }, length: V, fromValues: k, copy(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t }, set(t, n, a, r) { return t[0] = n, t[1] = a, t[2] = r, t }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t }, subtract: Q, multiply: Y, divide: Z, ceil(t, n) { return t[0] = Math.ceil(n[0]), t[1] = Math.ceil(n[1]), t[2] = Math.ceil(n[2]), t }, floor(t, n) { return t[0] = Math.floor(n[0]), t[1] = Math.floor(n[1]), t[2] = Math.floor(n[2]), t }, min(t, n, a) { return t[0] = Math.min(n[0], a[0]), t[1] = Math.min(n[1], a[1]), t[2] = Math.min(n[2], a[2]), t }, max(t, n, a) { return t[0] = Math.max(n[0], a[0]), t[1] = Math.max(n[1], a[1]), t[2] = Math.max(n[2], a[2]), t }, round(t, n) { return t[0] = Math.round(n[0]), t[1] = Math.round(n[1]), t[2] = Math.round(n[2]), t }, scale(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t }, scaleAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t }, distance: N, squaredDistance: X, squaredLength: B, negate(t, n) { return t[0] = -n[0], t[1] = -n[1], t[2] = -n[2], t }, inverse(t, n) { return t[0] = 1 / n[0], t[1] = 1 / n[1], t[2] = 1 / n[2], t }, normalize: U, dot: G, cross: W, lerp(t, n, a, r) { const u = n[0]; const e = n[1]; const o = n[2]; return t[0] = u + r * (a[0] - u), t[1] = e + r * (a[1] - e), t[2] = o + r * (a[2] - o), t }, slerp(t, n, a, r) { const u = Math.acos(Math.min(Math.max(G(n, a), -1), 1)); const e = Math.sin(u); const o = Math.sin((1 - r) * u) / e; const i = Math.sin(r * u) / e; return t[0] = o * n[0] + i * a[0], t[1] = o * n[1] + i * a[1], t[2] = o * n[2] + i * a[2], t }, hermite(t, n, a, r, u, e) { const o = e * e; const i = o * (2 * e - 3) + 1; const h = o * (e - 2) + e; const c = o * (e - 1); const s = o * (3 - 2 * e); return t[0] = n[0] * i + a[0] * h + r[0] * c + u[0] * s, t[1] = n[1] * i + a[1] * h + r[1] * c + u[1] * s, t[2] = n[2] * i + a[2] * h + r[2] * c + u[2] * s, t }, bezier(t, n, a, r, u, e) { const o = 1 - e; const i = o * o; const h = e * e; const c = i * o; const s = 3 * e * i; const M = 3 * h * o; const f = h * e; return t[0] = n[0] * c + a[0] * s + r[0] * M + u[0] * f, t[1] = n[1] * c + a[1] * s + r[1] * M + u[1] * f, t[2] = n[2] * c + a[2] * s + r[2] * M + u[2] * f, t }, random(t, n) { n = void 0 === n ? 1 : n; const a = 2 * r() * Math.PI; const u = 2 * r() - 1; const e = Math.sqrt(1 - u * u) * n; return t[0] = Math.cos(a) * e, t[1] = Math.sin(a) * e, t[2] = u * n, t }, transformMat4(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; let o = a[3] * r + a[7] * u + a[11] * e + a[15]; return o = o || 1, t[0] = (a[0] * r + a[4] * u + a[8] * e + a[12]) / o, t[1] = (a[1] * r + a[5] * u + a[9] * e + a[13]) / o, t[2] = (a[2] * r + a[6] * u + a[10] * e + a[14]) / o, t }, transformMat3(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; return t[0] = r * a[0] + u * a[3] + e * a[6], t[1] = r * a[1] + u * a[4] + e * a[7], t[2] = r * a[2] + u * a[5] + e * a[8], t }, transformQuat(t, n, a) { const r = a[0]; const u = a[1]; const e = a[2]; const o = a[3]; const i = n[0]; const h = n[1]; const c = n[2]; let s = u * c - e * h; let M = e * i - r * c; let f = r * h - u * i; let l = u * f - e * M; let v = e * s - r * f; let b = r * M - u * s; const m = 2 * o; return s *= m, M *= m, f *= m, l *= 2, v *= 2, b *= 2, t[0] = i + s + l, t[1] = h + M + v, t[2] = c + f + b, t }, rotateX(t, n, a, r) { const u = []; const e = []; return u[0] = n[0] - a[0], u[1] = n[1] - a[1], u[2] = n[2] - a[2], e[0] = u[0], e[1] = u[1] * Math.cos(r) - u[2] * Math.sin(r), e[2] = u[1] * Math.sin(r) + u[2] * Math.cos(r), t[0] = e[0] + a[0], t[1] = e[1] + a[1], t[2] = e[2] + a[2], t }, rotateY(t, n, a, r) { const u = []; const e = []; return u[0] = n[0] - a[0], u[1] = n[1] - a[1], u[2] = n[2] - a[2], e[0] = u[2] * Math.sin(r) + u[0] * Math.cos(r), e[1] = u[1], e[2] = u[2] * Math.cos(r) - u[0] * Math.sin(r), t[0] = e[0] + a[0], t[1] = e[1] + a[1], t[2] = e[2] + a[2], t }, rotateZ(t, n, a, r) { const u = []; const e = []; return u[0] = n[0] - a[0], u[1] = n[1] - a[1], u[2] = n[2] - a[2], e[0] = u[0] * Math.cos(r) - u[1] * Math.sin(r), e[1] = u[0] * Math.sin(r) + u[1] * Math.cos(r), e[2] = u[2], t[0] = e[0] + a[0], t[1] = e[1] + a[1], t[2] = e[2] + a[2], t }, angle(t, n) { const a = t[0]; const r = t[1]; const u = t[2]; const e = n[0]; const o = n[1]; const i = n[2]; const h = Math.sqrt((a * a + r * r + u * u) * (e * e + o * o + i * i)); const c = h && G(t, n) / h; return Math.acos(Math.min(Math.max(c, -1), 1)) }, zero(t) { return t[0] = 0, t[1] = 0, t[2] = 0, t }, str(t) { return 'vec3(' + t[0] + ', ' + t[1] + ', ' + t[2] + ')' }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = a[0]; const i = a[1]; const h = a[2]; return Math.abs(r - o) <= n * Math.max(1, Math.abs(r), Math.abs(o)) && Math.abs(u - i) <= n * Math.max(1, Math.abs(u), Math.abs(i)) && Math.abs(e - h) <= n * Math.max(1, Math.abs(e), Math.abs(h)) }, sub: H, mul: J, div: K, dist: $, sqrDist: tt, len: nt, sqrLen: at, forEach: rt + }); function et() { const t = new a(4); return a != Float32Array && (t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 0), t } function ot(t) { const n = new a(4); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n } function it(t, n, r, u) { const e = new a(4); return e[0] = t, e[1] = n, e[2] = r, e[3] = u, e } function ht(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t } function ct(t, n, a, r, u) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t } function st(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t } function Mt(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t[2] = n[2] - a[2], t[3] = n[3] - a[3], t } function ft(t, n, a) { return t[0] = n[0] * a[0], t[1] = n[1] * a[1], t[2] = n[2] * a[2], t[3] = n[3] * a[3], t } function lt(t, n, a) { return t[0] = n[0] / a[0], t[1] = n[1] / a[1], t[2] = n[2] / a[2], t[3] = n[3] / a[3], t } function vt(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t } function bt(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; const u = n[2] - t[2]; const e = n[3] - t[3]; return Math.hypot(a, r, u, e) } function mt(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; const u = n[2] - t[2]; const e = n[3] - t[3]; return a * a + r * r + u * u + e * e } function dt(t) { const n = t[0]; const a = t[1]; const r = t[2]; const u = t[3]; return Math.hypot(n, a, r, u) } function pt(t) { const n = t[0]; const a = t[1]; const r = t[2]; const u = t[3]; return n * n + a * a + r * r + u * u } function xt(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; let o = a * a + r * r + u * u + e * e; return o > 0 && (o = 1 / Math.sqrt(o)), t[0] = a * o, t[1] = r * o, t[2] = u * o, t[3] = e * o, t } function yt(t, n) { return t[0] * n[0] + t[1] * n[1] + t[2] * n[2] + t[3] * n[3] } function qt(t, n, a, r) { const u = n[0]; const e = n[1]; const o = n[2]; const i = n[3]; return t[0] = u + r * (a[0] - u), t[1] = e + r * (a[1] - e), t[2] = o + r * (a[2] - o), t[3] = i + r * (a[3] - i), t } function gt(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] } const _t = Mt; const At = ft; const wt = lt; const zt = bt; const Rt = mt; const Ot = dt; const jt = pt; const Et = (function () { const t = et(); return function (n, a, r, u, e, o) { let i; let h; for (a || (a = 4), r || (r = 0), h = u ? Math.min(u * a + r, n.length) : n.length, i = r; i < h; i += a)t[0] = n[i], t[1] = n[i + 1], t[2] = n[i + 2], t[3] = n[i + 3], e(t, t, o), n[i] = t[0], n[i + 1] = t[1], n[i + 2] = t[2], n[i + 3] = t[3]; return n } }()); const Pt = Object.freeze({ + __proto__: null, create: et, clone: ot, fromValues: it, copy: ht, set: ct, add: st, subtract: Mt, multiply: ft, divide: lt, ceil(t, n) { return t[0] = Math.ceil(n[0]), t[1] = Math.ceil(n[1]), t[2] = Math.ceil(n[2]), t[3] = Math.ceil(n[3]), t }, floor(t, n) { return t[0] = Math.floor(n[0]), t[1] = Math.floor(n[1]), t[2] = Math.floor(n[2]), t[3] = Math.floor(n[3]), t }, min(t, n, a) { return t[0] = Math.min(n[0], a[0]), t[1] = Math.min(n[1], a[1]), t[2] = Math.min(n[2], a[2]), t[3] = Math.min(n[3], a[3]), t }, max(t, n, a) { return t[0] = Math.max(n[0], a[0]), t[1] = Math.max(n[1], a[1]), t[2] = Math.max(n[2], a[2]), t[3] = Math.max(n[3], a[3]), t }, round(t, n) { return t[0] = Math.round(n[0]), t[1] = Math.round(n[1]), t[2] = Math.round(n[2]), t[3] = Math.round(n[3]), t }, scale: vt, scaleAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t[2] = n[2] + a[2] * r, t[3] = n[3] + a[3] * r, t }, distance: bt, squaredDistance: mt, length: dt, squaredLength: pt, negate(t, n) { return t[0] = -n[0], t[1] = -n[1], t[2] = -n[2], t[3] = -n[3], t }, inverse(t, n) { return t[0] = 1 / n[0], t[1] = 1 / n[1], t[2] = 1 / n[2], t[3] = 1 / n[3], t }, normalize: xt, dot: yt, cross(t, n, a, r) { const u = a[0] * r[1] - a[1] * r[0]; const e = a[0] * r[2] - a[2] * r[0]; const o = a[0] * r[3] - a[3] * r[0]; const i = a[1] * r[2] - a[2] * r[1]; const h = a[1] * r[3] - a[3] * r[1]; const c = a[2] * r[3] - a[3] * r[2]; const s = n[0]; const M = n[1]; const f = n[2]; const l = n[3]; return t[0] = M * c - f * h + l * i, t[1] = -s * c + f * o - l * e, t[2] = s * h - M * o + l * u, t[3] = -s * i + M * e - f * u, t }, lerp: qt, random(t, n) { let a; let u; let e; let o; let i; let h; n = void 0 === n ? 1 : n; do { i = (a = 2 * r() - 1) * a + (u = 2 * r() - 1) * u } while (i >= 1); do { h = (e = 2 * r() - 1) * e + (o = 2 * r() - 1) * o } while (h >= 1); const c = Math.sqrt((1 - i) / h); return t[0] = n * a, t[1] = n * u, t[2] = n * e * c, t[3] = n * o * c, t }, transformMat4(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; return t[0] = a[0] * r + a[4] * u + a[8] * e + a[12] * o, t[1] = a[1] * r + a[5] * u + a[9] * e + a[13] * o, t[2] = a[2] * r + a[6] * u + a[10] * e + a[14] * o, t[3] = a[3] * r + a[7] * u + a[11] * e + a[15] * o, t }, transformQuat(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = a[0]; const i = a[1]; const h = a[2]; const c = a[3]; const s = c * r + i * e - h * u; const M = c * u + h * r - o * e; const f = c * e + o * u - i * r; const l = -o * r - i * u - h * e; return t[0] = s * c + l * -o + M * -h - f * -i, t[1] = M * c + l * -i + f * -o - s * -h, t[2] = f * c + l * -h + s * -i - M * -o, t[3] = n[3], t }, zero(t) { return t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 0, t }, str(t) { return 'vec4(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ')' }, exactEquals: gt, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = a[0]; const h = a[1]; const c = a[2]; const s = a[3]; return Math.abs(r - i) <= n * Math.max(1, Math.abs(r), Math.abs(i)) && Math.abs(u - h) <= n * Math.max(1, Math.abs(u), Math.abs(h)) && Math.abs(e - c) <= n * Math.max(1, Math.abs(e), Math.abs(c)) && Math.abs(o - s) <= n * Math.max(1, Math.abs(o), Math.abs(s)) }, sub: _t, mul: At, div: wt, dist: zt, sqrDist: Rt, len: Ot, sqrLen: jt, forEach: Et + }); function Tt() { const t = new a(4); return a != Float32Array && (t[0] = 0, t[1] = 0, t[2] = 0), t[3] = 1, t } function St(t, n, a) { a *= 0.5; const r = Math.sin(a); return t[0] = r * n[0], t[1] = r * n[1], t[2] = r * n[2], t[3] = Math.cos(a), t } function Dt(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = a[0]; const h = a[1]; const c = a[2]; const s = a[3]; return t[0] = r * s + o * i + u * c - e * h, t[1] = u * s + o * h + e * i - r * c, t[2] = e * s + o * c + r * h - u * i, t[3] = o * s - r * i - u * h - e * c, t } function Ft(t, n, a) { a *= 0.5; const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = Math.sin(a); const h = Math.cos(a); return t[0] = r * h + o * i, t[1] = u * h + e * i, t[2] = e * h - u * i, t[3] = o * h - r * i, t } function It(t, n, a) { a *= 0.5; const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = Math.sin(a); const h = Math.cos(a); return t[0] = r * h - e * i, t[1] = u * h + o * i, t[2] = e * h + r * i, t[3] = o * h - u * i, t } function Lt(t, n, a) { a *= 0.5; const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = Math.sin(a); const h = Math.cos(a); return t[0] = r * h + u * i, t[1] = u * h - r * i, t[2] = e * h + o * i, t[3] = o * h - e * i, t } function Vt(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = Math.sqrt(a * a + r * r + u * u); const i = Math.exp(e); const h = o > 0 ? i * Math.sin(o) / o : 0; return t[0] = a * h, t[1] = r * h, t[2] = u * h, t[3] = i * Math.cos(o), t } function kt(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = Math.sqrt(a * a + r * r + u * u); const i = o > 0 ? Math.atan2(o, e) / o : 0; return t[0] = a * i, t[1] = r * i, t[2] = u * i, t[3] = 0.5 * Math.log(a * a + r * r + u * u + e * e), t } function Qt(t, a, r, u) { let e; let o; let i; let h; let c; const s = a[0]; const M = a[1]; const f = a[2]; const l = a[3]; let v = r[0]; let b = r[1]; let m = r[2]; let d = r[3]; return (o = s * v + M * b + f * m + l * d) < 0 && (o = -o, v = -v, b = -b, m = -m, d = -d), 1 - o > n ? (e = Math.acos(o), i = Math.sin(e), h = Math.sin((1 - u) * e) / i, c = Math.sin(u * e) / i) : (h = 1 - u, c = u), t[0] = h * s + c * v, t[1] = h * M + c * b, t[2] = h * f + c * m, t[3] = h * l + c * d, t } function Yt(t, n) { let a; const r = n[0] + n[4] + n[8]; if (r > 0)a = Math.sqrt(r + 1), t[3] = 0.5 * a, a = 0.5 / a, t[0] = (n[5] - n[7]) * a, t[1] = (n[6] - n[2]) * a, t[2] = (n[1] - n[3]) * a; else { let u = 0; n[4] > n[0] && (u = 1), n[8] > n[3 * u + u] && (u = 2); const e = (u + 1) % 3; const o = (u + 2) % 3; a = Math.sqrt(n[3 * u + u] - n[3 * e + e] - n[3 * o + o] + 1), t[u] = 0.5 * a, a = 0.5 / a, t[3] = (n[3 * e + o] - n[3 * o + e]) * a, t[e] = (n[3 * e + u] + n[3 * u + e]) * a, t[o] = (n[3 * o + u] + n[3 * u + o]) * a } return t } const Zt = ot; const Nt = it; const Xt = ht; const Bt = ct; const Ut = st; const Gt = Dt; const Wt = vt; const Ct = yt; const Ht = qt; const Jt = dt; const Kt = Jt; const $t = pt; const tn = $t; const nn = xt; const an = gt; let rn; let un; let en; let on; let hn; let cn; const sn = (rn = L(), un = k(1, 0, 0), en = k(0, 1, 0), function (t, n, a) { const r = G(n, a); return r < -0.999999 ? (W(rn, un, n), nt(rn) < 1e-6 && W(rn, en, n), U(rn, rn), St(t, rn, Math.PI), t) : r > 0.999999 ? (t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 1, t) : (W(rn, n, a), t[0] = rn[0], t[1] = rn[1], t[2] = rn[2], t[3] = 1 + r, nn(t, t)) }); const Mn = (on = Tt(), hn = Tt(), function (t, n, a, r, u, e) { return Qt(on, n, u, e), Qt(hn, a, r, e), Qt(t, on, hn, 2 * e * (1 - e)), t }); const fn = (cn = d(), function (t, n, a, r) { return cn[0] = a[0], cn[3] = a[1], cn[6] = a[2], cn[1] = r[0], cn[4] = r[1], cn[7] = r[2], cn[2] = -n[0], cn[5] = -n[1], cn[8] = -n[2], nn(t, Yt(t, cn)) }); const ln = Object.freeze({ + __proto__: null, create: Tt, identity(t) { return t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 1, t }, setAxisAngle: St, getAxisAngle(t, a) { const r = 2 * Math.acos(a[3]); const u = Math.sin(r / 2); return u > n ? (t[0] = a[0] / u, t[1] = a[1] / u, t[2] = a[2] / u) : (t[0] = 1, t[1] = 0, t[2] = 0), r }, getAngle(t, n) { const a = Ct(t, n); return Math.acos(2 * a * a - 1) }, multiply: Dt, rotateX: Ft, rotateY: It, rotateZ: Lt, calculateW(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; return t[0] = a, t[1] = r, t[2] = u, t[3] = Math.sqrt(Math.abs(1 - a * a - r * r - u * u)), t }, exp: Vt, ln: kt, pow(t, n, a) { return kt(t, n), Wt(t, t, a), Vt(t, t), t }, slerp: Qt, random(t) { const n = r(); const a = r(); const u = r(); const e = Math.sqrt(1 - n); const o = Math.sqrt(n); return t[0] = e * Math.sin(2 * Math.PI * a), t[1] = e * Math.cos(2 * Math.PI * a), t[2] = o * Math.sin(2 * Math.PI * u), t[3] = o * Math.cos(2 * Math.PI * u), t }, invert(t, n) { const a = n[0]; const r = n[1]; const u = n[2]; const e = n[3]; const o = a * a + r * r + u * u + e * e; const i = o ? 1 / o : 0; return t[0] = -a * i, t[1] = -r * i, t[2] = -u * i, t[3] = e * i, t }, conjugate(t, n) { return t[0] = -n[0], t[1] = -n[1], t[2] = -n[2], t[3] = n[3], t }, fromMat3: Yt, fromEuler(t, n, a, r) { const e = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : u; const o = Math.PI / 360; n *= o, r *= o, a *= o; const i = Math.sin(n); const h = Math.cos(n); const c = Math.sin(a); const s = Math.cos(a); const M = Math.sin(r); const f = Math.cos(r); switch (e) { case 'xyz': t[0] = i * s * f + h * c * M, t[1] = h * c * f - i * s * M, t[2] = h * s * M + i * c * f, t[3] = h * s * f - i * c * M; break; case 'xzy': t[0] = i * s * f - h * c * M, t[1] = h * c * f - i * s * M, t[2] = h * s * M + i * c * f, t[3] = h * s * f + i * c * M; break; case 'yxz': t[0] = i * s * f + h * c * M, t[1] = h * c * f - i * s * M, t[2] = h * s * M - i * c * f, t[3] = h * s * f + i * c * M; break; case 'yzx': t[0] = i * s * f + h * c * M, t[1] = h * c * f + i * s * M, t[2] = h * s * M - i * c * f, t[3] = h * s * f - i * c * M; break; case 'zxy': t[0] = i * s * f - h * c * M, t[1] = h * c * f + i * s * M, t[2] = h * s * M + i * c * f, t[3] = h * s * f - i * c * M; break; case 'zyx': t[0] = i * s * f - h * c * M, t[1] = h * c * f + i * s * M, t[2] = h * s * M - i * c * f, t[3] = h * s * f + i * c * M; break; default: throw new Error('Unknown angle order ' + e) } return t }, str(t) { return 'quat(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ')' }, clone: Zt, fromValues: Nt, copy: Xt, set: Bt, add: Ut, mul: Gt, scale: Wt, dot: Ct, lerp: Ht, length: Jt, len: Kt, squaredLength: $t, sqrLen: tn, normalize: nn, exactEquals: an, equals(t, n) { return Math.abs(yt(t, n)) >= 0.999999 }, rotationTo: sn, sqlerp: Mn, setAxes: fn + }); function vn(t, n, a) { const r = 0.5 * a[0]; const u = 0.5 * a[1]; const e = 0.5 * a[2]; const o = n[0]; const i = n[1]; const h = n[2]; const c = n[3]; return t[0] = o, t[1] = i, t[2] = h, t[3] = c, t[4] = r * c + u * h - e * i, t[5] = u * c + e * o - r * h, t[6] = e * c + r * i - u * o, t[7] = -r * o - u * i - e * h, t } function bn(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = n[4], t[5] = n[5], t[6] = n[6], t[7] = n[7], t } const mn = Xt; const dn = Xt; function pn(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = a[4]; const h = a[5]; const c = a[6]; const s = a[7]; const M = n[4]; const f = n[5]; const l = n[6]; const v = n[7]; const b = a[0]; const m = a[1]; const d = a[2]; const p = a[3]; return t[0] = r * p + o * b + u * d - e * m, t[1] = u * p + o * m + e * b - r * d, t[2] = e * p + o * d + r * m - u * b, t[3] = o * p - r * b - u * m - e * d, t[4] = r * s + o * i + u * c - e * h + M * p + v * b + f * d - l * m, t[5] = u * s + o * h + e * i - r * c + f * p + v * m + l * b - M * d, t[6] = e * s + o * c + r * h - u * i + l * p + v * d + M * m - f * b, t[7] = o * s - r * i - u * h - e * c + v * p - M * b - f * m - l * d, t } const xn = pn; const yn = Ct; const qn = Jt; const gn = qn; const _n = $t; const An = _n; const wn = Object.freeze({ + __proto__: null, create() { const t = new a(8); return a != Float32Array && (t[0] = 0, t[1] = 0, t[2] = 0, t[4] = 0, t[5] = 0, t[6] = 0, t[7] = 0), t[3] = 1, t }, clone(t) { const n = new a(8); return n[0] = t[0], n[1] = t[1], n[2] = t[2], n[3] = t[3], n[4] = t[4], n[5] = t[5], n[6] = t[6], n[7] = t[7], n }, fromValues(t, n, r, u, e, o, i, h) { const c = new a(8); return c[0] = t, c[1] = n, c[2] = r, c[3] = u, c[4] = e, c[5] = o, c[6] = i, c[7] = h, c }, fromRotationTranslationValues(t, n, r, u, e, o, i) { const h = new a(8); h[0] = t, h[1] = n, h[2] = r, h[3] = u; const c = 0.5 * e; const s = 0.5 * o; const M = 0.5 * i; return h[4] = c * u + s * r - M * n, h[5] = s * u + M * t - c * r, h[6] = M * u + c * n - s * t, h[7] = -c * t - s * n - M * r, h }, fromRotationTranslation: vn, fromTranslation(t, n) { return t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 1, t[4] = 0.5 * n[0], t[5] = 0.5 * n[1], t[6] = 0.5 * n[2], t[7] = 0, t }, fromRotation(t, n) { return t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[4] = 0, t[5] = 0, t[6] = 0, t[7] = 0, t }, fromMat4(t, n) { const r = Tt(); O(r, n); const u = new a(3); return z(u, n), vn(t, r, u), t }, copy: bn, identity(t) { return t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 1, t[4] = 0, t[5] = 0, t[6] = 0, t[7] = 0, t }, set(t, n, a, r, u, e, o, i, h) { return t[0] = n, t[1] = a, t[2] = r, t[3] = u, t[4] = e, t[5] = o, t[6] = i, t[7] = h, t }, getReal: mn, getDual(t, n) { return t[0] = n[4], t[1] = n[5], t[2] = n[6], t[3] = n[7], t }, setReal: dn, setDual(t, n) { return t[4] = n[0], t[5] = n[1], t[6] = n[2], t[7] = n[3], t }, getTranslation(t, n) { const a = n[4]; const r = n[5]; const u = n[6]; const e = n[7]; const o = -n[0]; const i = -n[1]; const h = -n[2]; const c = n[3]; return t[0] = 2 * (a * c + e * o + r * h - u * i), t[1] = 2 * (r * c + e * i + u * o - a * h), t[2] = 2 * (u * c + e * h + a * i - r * o), t }, translate(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; const i = 0.5 * a[0]; const h = 0.5 * a[1]; const c = 0.5 * a[2]; const s = n[4]; const M = n[5]; const f = n[6]; const l = n[7]; return t[0] = r, t[1] = u, t[2] = e, t[3] = o, t[4] = o * i + u * c - e * h + s, t[5] = o * h + e * i - r * c + M, t[6] = o * c + r * h - u * i + f, t[7] = -r * i - u * h - e * c + l, t }, rotateX(t, n, a) { let r = -n[0]; let u = -n[1]; let e = -n[2]; let o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = i * o + s * r + h * e - c * u; const f = h * o + s * u + c * r - i * e; const l = c * o + s * e + i * u - h * r; const v = s * o - i * r - h * u - c * e; return Ft(t, n, a), r = t[0], u = t[1], e = t[2], o = t[3], t[4] = M * o + v * r + f * e - l * u, t[5] = f * o + v * u + l * r - M * e, t[6] = l * o + v * e + M * u - f * r, t[7] = v * o - M * r - f * u - l * e, t }, rotateY(t, n, a) { let r = -n[0]; let u = -n[1]; let e = -n[2]; let o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = i * o + s * r + h * e - c * u; const f = h * o + s * u + c * r - i * e; const l = c * o + s * e + i * u - h * r; const v = s * o - i * r - h * u - c * e; return It(t, n, a), r = t[0], u = t[1], e = t[2], o = t[3], t[4] = M * o + v * r + f * e - l * u, t[5] = f * o + v * u + l * r - M * e, t[6] = l * o + v * e + M * u - f * r, t[7] = v * o - M * r - f * u - l * e, t }, rotateZ(t, n, a) { let r = -n[0]; let u = -n[1]; let e = -n[2]; let o = n[3]; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = i * o + s * r + h * e - c * u; const f = h * o + s * u + c * r - i * e; const l = c * o + s * e + i * u - h * r; const v = s * o - i * r - h * u - c * e; return Lt(t, n, a), r = t[0], u = t[1], e = t[2], o = t[3], t[4] = M * o + v * r + f * e - l * u, t[5] = f * o + v * u + l * r - M * e, t[6] = l * o + v * e + M * u - f * r, t[7] = v * o - M * r - f * u - l * e, t }, rotateByQuatAppend(t, n, a) { const r = a[0]; const u = a[1]; const e = a[2]; const o = a[3]; let i = n[0]; let h = n[1]; let c = n[2]; let s = n[3]; return t[0] = i * o + s * r + h * e - c * u, t[1] = h * o + s * u + c * r - i * e, t[2] = c * o + s * e + i * u - h * r, t[3] = s * o - i * r - h * u - c * e, i = n[4], h = n[5], c = n[6], s = n[7], t[4] = i * o + s * r + h * e - c * u, t[5] = h * o + s * u + c * r - i * e, t[6] = c * o + s * e + i * u - h * r, t[7] = s * o - i * r - h * u - c * e, t }, rotateByQuatPrepend(t, n, a) { const r = n[0]; const u = n[1]; const e = n[2]; const o = n[3]; let i = a[0]; let h = a[1]; let c = a[2]; let s = a[3]; return t[0] = r * s + o * i + u * c - e * h, t[1] = u * s + o * h + e * i - r * c, t[2] = e * s + o * c + r * h - u * i, t[3] = o * s - r * i - u * h - e * c, i = a[4], h = a[5], c = a[6], s = a[7], t[4] = r * s + o * i + u * c - e * h, t[5] = u * s + o * h + e * i - r * c, t[6] = e * s + o * c + r * h - u * i, t[7] = o * s - r * i - u * h - e * c, t }, rotateAroundAxis(t, a, r, u) { if (Math.abs(u) < n) return bn(t, a); const e = Math.hypot(r[0], r[1], r[2]); u *= 0.5; const o = Math.sin(u); const i = o * r[0] / e; const h = o * r[1] / e; const c = o * r[2] / e; const s = Math.cos(u); const M = a[0]; const f = a[1]; const l = a[2]; const v = a[3]; t[0] = M * s + v * i + f * c - l * h, t[1] = f * s + v * h + l * i - M * c, t[2] = l * s + v * c + M * h - f * i, t[3] = v * s - M * i - f * h - l * c; const b = a[4]; const m = a[5]; const d = a[6]; const p = a[7]; return t[4] = b * s + p * i + m * c - d * h, t[5] = m * s + p * h + d * i - b * c, t[6] = d * s + p * c + b * h - m * i, t[7] = p * s - b * i - m * h - d * c, t }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t[2] = n[2] + a[2], t[3] = n[3] + a[3], t[4] = n[4] + a[4], t[5] = n[5] + a[5], t[6] = n[6] + a[6], t[7] = n[7] + a[7], t }, multiply: pn, mul: xn, scale(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t[2] = n[2] * a, t[3] = n[3] * a, t[4] = n[4] * a, t[5] = n[5] * a, t[6] = n[6] * a, t[7] = n[7] * a, t }, dot: yn, lerp(t, n, a, r) { const u = 1 - r; return yn(n, a) < 0 && (r = -r), t[0] = n[0] * u + a[0] * r, t[1] = n[1] * u + a[1] * r, t[2] = n[2] * u + a[2] * r, t[3] = n[3] * u + a[3] * r, t[4] = n[4] * u + a[4] * r, t[5] = n[5] * u + a[5] * r, t[6] = n[6] * u + a[6] * r, t[7] = n[7] * u + a[7] * r, t }, invert(t, n) { const a = _n(n); return t[0] = -n[0] / a, t[1] = -n[1] / a, t[2] = -n[2] / a, t[3] = n[3] / a, t[4] = -n[4] / a, t[5] = -n[5] / a, t[6] = -n[6] / a, t[7] = n[7] / a, t }, conjugate(t, n) { return t[0] = -n[0], t[1] = -n[1], t[2] = -n[2], t[3] = n[3], t[4] = -n[4], t[5] = -n[5], t[6] = -n[6], t[7] = n[7], t }, length: qn, len: gn, squaredLength: _n, sqrLen: An, normalize(t, n) { let a = _n(n); if (a > 0) { a = Math.sqrt(a); const r = n[0] / a; const u = n[1] / a; const e = n[2] / a; const o = n[3] / a; const i = n[4]; const h = n[5]; const c = n[6]; const s = n[7]; const M = r * i + u * h + e * c + o * s; t[0] = r, t[1] = u, t[2] = e, t[3] = o, t[4] = (i - r * M) / a, t[5] = (h - u * M) / a, t[6] = (c - e * M) / a, t[7] = (s - o * M) / a } return t }, str(t) { return 'quat2(' + t[0] + ', ' + t[1] + ', ' + t[2] + ', ' + t[3] + ', ' + t[4] + ', ' + t[5] + ', ' + t[6] + ', ' + t[7] + ')' }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] && t[2] === n[2] && t[3] === n[3] && t[4] === n[4] && t[5] === n[5] && t[6] === n[6] && t[7] === n[7] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = t[2]; const o = t[3]; const i = t[4]; const h = t[5]; const c = t[6]; const s = t[7]; const M = a[0]; const f = a[1]; const l = a[2]; const v = a[3]; const b = a[4]; const m = a[5]; const d = a[6]; const p = a[7]; return Math.abs(r - M) <= n * Math.max(1, Math.abs(r), Math.abs(M)) && Math.abs(u - f) <= n * Math.max(1, Math.abs(u), Math.abs(f)) && Math.abs(e - l) <= n * Math.max(1, Math.abs(e), Math.abs(l)) && Math.abs(o - v) <= n * Math.max(1, Math.abs(o), Math.abs(v)) && Math.abs(i - b) <= n * Math.max(1, Math.abs(i), Math.abs(b)) && Math.abs(h - m) <= n * Math.max(1, Math.abs(h), Math.abs(m)) && Math.abs(c - d) <= n * Math.max(1, Math.abs(c), Math.abs(d)) && Math.abs(s - p) <= n * Math.max(1, Math.abs(s), Math.abs(p)) } + }); function zn() { const t = new a(2); return a != Float32Array && (t[0] = 0, t[1] = 0), t } function Rn(t, n, a) { return t[0] = n[0] - a[0], t[1] = n[1] - a[1], t } function On(t, n, a) { return t[0] = n[0] * a[0], t[1] = n[1] * a[1], t } function jn(t, n, a) { return t[0] = n[0] / a[0], t[1] = n[1] / a[1], t } function En(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; return Math.hypot(a, r) } function Pn(t, n) { const a = n[0] - t[0]; const r = n[1] - t[1]; return a * a + r * r } function Tn(t) { const n = t[0]; const a = t[1]; return Math.hypot(n, a) } function Sn(t) { const n = t[0]; const a = t[1]; return n * n + a * a } const Dn = Tn; const Fn = Rn; const In = On; const Ln = jn; const Vn = En; const kn = Pn; const Qn = Sn; const Yn = (function () { const t = zn(); return function (n, a, r, u, e, o) { let i; let h; for (a || (a = 2), r || (r = 0), h = u ? Math.min(u * a + r, n.length) : n.length, i = r; i < h; i += a)t[0] = n[i], t[1] = n[i + 1], e(t, t, o), n[i] = t[0], n[i + 1] = t[1]; return n } }()); const Zn = Object.freeze({ + __proto__: null, create: zn, clone(t) { const n = new a(2); return n[0] = t[0], n[1] = t[1], n }, fromValues(t, n) { const r = new a(2); return r[0] = t, r[1] = n, r }, copy(t, n) { return t[0] = n[0], t[1] = n[1], t }, set(t, n, a) { return t[0] = n, t[1] = a, t }, add(t, n, a) { return t[0] = n[0] + a[0], t[1] = n[1] + a[1], t }, subtract: Rn, multiply: On, divide: jn, ceil(t, n) { return t[0] = Math.ceil(n[0]), t[1] = Math.ceil(n[1]), t }, floor(t, n) { return t[0] = Math.floor(n[0]), t[1] = Math.floor(n[1]), t }, min(t, n, a) { return t[0] = Math.min(n[0], a[0]), t[1] = Math.min(n[1], a[1]), t }, max(t, n, a) { return t[0] = Math.max(n[0], a[0]), t[1] = Math.max(n[1], a[1]), t }, round(t, n) { return t[0] = Math.round(n[0]), t[1] = Math.round(n[1]), t }, scale(t, n, a) { return t[0] = n[0] * a, t[1] = n[1] * a, t }, scaleAndAdd(t, n, a, r) { return t[0] = n[0] + a[0] * r, t[1] = n[1] + a[1] * r, t }, distance: En, squaredDistance: Pn, length: Tn, squaredLength: Sn, negate(t, n) { return t[0] = -n[0], t[1] = -n[1], t }, inverse(t, n) { return t[0] = 1 / n[0], t[1] = 1 / n[1], t }, normalize(t, n) { const a = n[0]; const r = n[1]; let u = a * a + r * r; return u > 0 && (u = 1 / Math.sqrt(u)), t[0] = n[0] * u, t[1] = n[1] * u, t }, dot(t, n) { return t[0] * n[0] + t[1] * n[1] }, cross(t, n, a) { const r = n[0] * a[1] - n[1] * a[0]; return t[0] = t[1] = 0, t[2] = r, t }, lerp(t, n, a, r) { const u = n[0]; const e = n[1]; return t[0] = u + r * (a[0] - u), t[1] = e + r * (a[1] - e), t }, random(t, n) { n = void 0 === n ? 1 : n; const a = 2 * r() * Math.PI; return t[0] = Math.cos(a) * n, t[1] = Math.sin(a) * n, t }, transformMat2(t, n, a) { const r = n[0]; const u = n[1]; return t[0] = a[0] * r + a[2] * u, t[1] = a[1] * r + a[3] * u, t }, transformMat2d(t, n, a) { const r = n[0]; const u = n[1]; return t[0] = a[0] * r + a[2] * u + a[4], t[1] = a[1] * r + a[3] * u + a[5], t }, transformMat3(t, n, a) { const r = n[0]; const u = n[1]; return t[0] = a[0] * r + a[3] * u + a[6], t[1] = a[1] * r + a[4] * u + a[7], t }, transformMat4(t, n, a) { const r = n[0]; const u = n[1]; return t[0] = a[0] * r + a[4] * u + a[12], t[1] = a[1] * r + a[5] * u + a[13], t }, rotate(t, n, a, r) { const u = n[0] - a[0]; const e = n[1] - a[1]; const o = Math.sin(r); const i = Math.cos(r); return t[0] = u * i - e * o + a[0], t[1] = u * o + e * i + a[1], t }, angle(t, n) { const a = t[0]; const r = t[1]; const u = n[0]; const e = n[1]; const o = Math.sqrt((a * a + r * r) * (u * u + e * e)); const i = o && (a * u + r * e) / o; return Math.acos(Math.min(Math.max(i, -1), 1)) }, zero(t) { return t[0] = 0, t[1] = 0, t }, str(t) { return 'vec2(' + t[0] + ', ' + t[1] + ')' }, exactEquals(t, n) { return t[0] === n[0] && t[1] === n[1] }, equals(t, a) { const r = t[0]; const u = t[1]; const e = a[0]; const o = a[1]; return Math.abs(r - e) <= n * Math.max(1, Math.abs(r), Math.abs(e)) && Math.abs(u - o) <= n * Math.max(1, Math.abs(u), Math.abs(o)) }, len: Dn, sub: Fn, mul: In, div: Ln, dist: Vn, sqrDist: kn, sqrLen: Qn, forEach: Yn + }); t.glMatrix = o, t.mat2 = M, t.mat2d = m, t.mat3 = g, t.mat4 = I, t.quat = ln, t.quat2 = wn, t.vec2 = Zn, t.vec3 = ut, t.vec4 = Pt, Object.defineProperty(t, '__esModule', {value: !0}) +}))) 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..8f677a84 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..a91d5aaa 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..be72fcbe 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,7 +68,7 @@ Component({ // VKSession EVENT resize session.on('resize', () => { - this.calcCanvasSize(); + this.calcCanvasSize() }) // 开启三维识别 @@ -76,14 +76,14 @@ Component({ // 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..0ea3f3ca 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..bd9dde75 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..f00e6759 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..557b95f9 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..54f51402 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..2135c30c 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..208eceda 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..244e2f8b 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..9876b54c 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..8de4537d 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..92d52b81 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 } - }; - + 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..8de4537d 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..9876b54c 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..f936c99b 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,58 +457,57 @@ 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({ properties: [ - { key: 'u_baseColorFactor', type: xrFrameSystem.EUniformType.FLOAT4, default: [1, 1, 1, 1] }, + {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..e1088c00 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..e1088c00 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..daed749d 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,14 +34,14 @@ Page({ env: config.envId, traceUser: true, }) - + 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}) }) } }, @@ -63,7 +64,7 @@ Page({ console.info('fetchActivityList: ', resp) if (resp.result) { const activityList = resp.result.dataList - this.setData({ activityList }) + this.setData({activityList}) } }).catch(err => { console.error('fetchActivityList fail: ', err) @@ -77,7 +78,7 @@ Page({ }, goDetail(e) { - const { id, roomid, singlechat } = e.currentTarget.dataset + const {id, roomid, singlechat} = e.currentTarget.dataset wx.openChatTool({ roomid, isSingleChat: Boolean(singlechat), diff --git a/miniprogram/packageAPI/pages/chattool/material_open/material_open.js b/miniprogram/packageAPI/pages/chattool/material_open/material_open.js index f06e7a8f..0a621c03 100644 --- a/miniprogram/packageAPI/pages/chattool/material_open/material_open.js +++ b/miniprogram/packageAPI/pages/chattool/material_open/material_open.js @@ -1,9 +1,10 @@ -import { getGroupEnterInfo } from '../util' +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' @@ -48,14 +49,14 @@ Page({ env: config.envId, traceUser: true, }) - + 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}) }) } }, @@ -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..1326ff76 100644 --- a/miniprogram/packageAPI/pages/chattool/material_view/material_view.js +++ b/miniprogram/packageAPI/pages/chattool/material_view/material_view.js @@ -104,12 +104,12 @@ Page({ // this.formatMaterials(mockData.materials) 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}) }) } }, @@ -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 } }, @@ -214,74 +213,78 @@ Page({ return new Promise((resolve, reject) => { wx.createSelectorQuery() .select('#myCanvas') - .fields({ node: true, size: true }) + .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..ac826ff2 100644 --- a/miniprogram/packageAPI/pages/device/add-contact/add-contact.js +++ b/miniprogram/packageAPI/pages/device/add-contact/add-contact.js @@ -29,7 +29,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js b/miniprogram/packageAPI/pages/device/bluetooth/bluetooth.js index b67860c1..c2fd7b71 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,10 +249,11 @@ Page({ if (wx.offThemeChange) { wx.offThemeChange() } + this.closeBluetoothAdapter() }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js b/miniprogram/packageAPI/pages/device/bluetooth/slave/slave.js index 7d0886c9..590422d5 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,10 +41,14 @@ 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) { @@ -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..3115773e 100644 --- a/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js +++ b/miniprogram/packageAPI/pages/device/capture-screen/capture-screen.js @@ -17,7 +17,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js b/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js index 32d86f58..3a3c69da 100644 --- a/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js +++ b/miniprogram/packageAPI/pages/device/clipboard-data/clipboard-data.js @@ -58,7 +58,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..4902f2f0 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,7 +29,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..27a839f4 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,7 +35,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..87ad4226 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,7 +27,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js b/miniprogram/packageAPI/pages/device/ibeacon/ibeacon.js index 6ebbed60..485ba4d5 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 @@ -49,10 +45,11 @@ Page({ if (wx.offThemeChange) { wx.offThemeChange() } + this.stopSearch() }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..a3154406 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,7 +38,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..cc7cc22e 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,17 +117,15 @@ 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) { 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..d7c9aaea 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,7 +52,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..37b4e4d2 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,7 +17,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/scan-code/scan-code.js b/miniprogram/packageAPI/pages/device/scan-code/scan-code.js index 112e2796..992de206 100644 --- a/miniprogram/packageAPI/pages/device/scan-code/scan-code.js +++ b/miniprogram/packageAPI/pages/device/scan-code/scan-code.js @@ -32,7 +32,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js b/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js index a7976ab7..3768abd3 100644 --- a/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js +++ b/miniprogram/packageAPI/pages/device/screen-brightness/screen-brightness.js @@ -18,7 +18,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/vibrate/vibrate.js b/miniprogram/packageAPI/pages/device/vibrate/vibrate.js index 1f4af12a..73edf939 100644 --- a/miniprogram/packageAPI/pages/device/vibrate/vibrate.js +++ b/miniprogram/packageAPI/pages/device/vibrate/vibrate.js @@ -40,7 +40,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/device/wifi/wifi.js b/miniprogram/packageAPI/pages/device/wifi/wifi.js index a56657c9..01900445 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({ @@ -76,13 +72,14 @@ 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) { diff --git a/miniprogram/packageAPI/pages/framework/resizable/resizable.js b/miniprogram/packageAPI/pages/framework/resizable/resizable.js index 2f66ecd8..219f63ce 100644 --- a/miniprogram/packageAPI/pages/framework/resizable/resizable.js +++ b/miniprogram/packageAPI/pages/framework/resizable/resizable.js @@ -22,7 +22,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..974064cc 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,14 +12,9 @@ Page({ /** * 生命周期函数--监听页面加载 */ - onUnload() { - if (wx.offThemeChange) { - wx.offThemeChange() - } - }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -27,7 +22,6 @@ Page({ 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..95d566a6 100644 --- a/miniprogram/packageAPI/pages/framework/wxs/movable.js +++ b/miniprogram/packageAPI/pages/framework/wxs/movable.js @@ -30,7 +30,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -38,7 +38,6 @@ Page({ this.setData({theme}) }) } - }, /** diff --git a/miniprogram/packageAPI/pages/framework/wxs/nearby.js b/miniprogram/packageAPI/pages/framework/wxs/nearby.js index 4b4e0efd..b7721ea1 100644 --- a/miniprogram/packageAPI/pages/framework/wxs/nearby.js +++ b/miniprogram/packageAPI/pages/framework/wxs/nearby.js @@ -65,7 +65,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/framework/wxs/sidebar.js b/miniprogram/packageAPI/pages/framework/wxs/sidebar.js index 8ae91b66..da266e14 100644 --- a/miniprogram/packageAPI/pages/framework/wxs/sidebar.js +++ b/miniprogram/packageAPI/pages/framework/wxs/sidebar.js @@ -19,7 +19,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/framework/wxs/stick-top.js b/miniprogram/packageAPI/pages/framework/wxs/stick-top.js index e9fd54d7..7c090dce 100644 --- a/miniprogram/packageAPI/pages/framework/wxs/stick-top.js +++ b/miniprogram/packageAPI/pages/framework/wxs/stick-top.js @@ -25,7 +25,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/framework/wxs/wxs.js b/miniprogram/packageAPI/pages/framework/wxs/wxs.js index 6a9037fe..4b50dd95 100644 --- a/miniprogram/packageAPI/pages/framework/wxs/wxs.js +++ b/miniprogram/packageAPI/pages/framework/wxs/wxs.js @@ -19,7 +19,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/location/choose-location/choose-location.js b/miniprogram/packageAPI/pages/location/choose-location/choose-location.js index 62ed518d..b03fe522 100644 --- a/miniprogram/packageAPI/pages/location/choose-location/choose-location.js +++ b/miniprogram/packageAPI/pages/location/choose-location/choose-location.js @@ -39,7 +39,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/location/get-location/get-location.js b/miniprogram/packageAPI/pages/location/get-location/get-location.js index e21854be..7b60f750 100644 --- a/miniprogram/packageAPI/pages/location/get-location/get-location.js +++ b/miniprogram/packageAPI/pages/location/get-location/get-location.js @@ -41,7 +41,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/location/open-location/open-location.js b/miniprogram/packageAPI/pages/location/open-location/open-location.js index 3347250b..cfe9ebab 100644 --- a/miniprogram/packageAPI/pages/location/open-location/open-location.js +++ b/miniprogram/packageAPI/pages/location/open-location/open-location.js @@ -24,7 +24,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/audio/audio.js b/miniprogram/packageAPI/pages/media/audio/audio.js index ec4b7074..19d21bb1 100644 --- a/miniprogram/packageAPI/pages/media/audio/audio.js +++ b/miniprogram/packageAPI/pages/media/audio/audio.js @@ -34,7 +34,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/background-audio/background-audio.js b/miniprogram/packageAPI/pages/media/background-audio/background-audio.js index 47be9d5b..9dc82d86 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,28 +72,26 @@ 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) { @@ -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..65444ba7 100644 --- a/miniprogram/packageAPI/pages/media/file/file.js +++ b/miniprogram/packageAPI/pages/media/file/file.js @@ -13,7 +13,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/image/image.js b/miniprogram/packageAPI/pages/media/image/image.js index 3f8153c6..122a9096 100644 --- a/miniprogram/packageAPI/pages/media/image/image.js +++ b/miniprogram/packageAPI/pages/media/image/image.js @@ -65,7 +65,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..08273a3c 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,7 +19,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/media-container/media-container.js b/miniprogram/packageAPI/pages/media/media-container/media-container.js index 87a48057..d1c84cb1 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,7 +12,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/video/video.js b/miniprogram/packageAPI/pages/media/video/video.js index 64249875..5d47c8eb 100644 --- a/miniprogram/packageAPI/pages/media/video/video.js +++ b/miniprogram/packageAPI/pages/media/video/video.js @@ -62,7 +62,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/media/voice/voice.js b/miniprogram/packageAPI/pages/media/voice/voice.js index 377528c5..a725cd24 100644 --- a/miniprogram/packageAPI/pages/media/voice/voice.js +++ b/miniprogram/packageAPI/pages/media/voice/voice.js @@ -37,7 +37,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/network/download-file/download-file.js b/miniprogram/packageAPI/pages/network/download-file/download-file.js index b06c1854..aaa52a8c 100644 --- a/miniprogram/packageAPI/pages/network/download-file/download-file.js +++ b/miniprogram/packageAPI/pages/network/download-file/download-file.js @@ -30,7 +30,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/network/mdns/mdns.js b/miniprogram/packageAPI/pages/network/mdns/mdns.js index 4e376ff5..dafbfa9c 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,7 +134,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/network/request/request.js b/miniprogram/packageAPI/pages/network/request/request.js index ddf8b842..8b937769 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) { @@ -51,7 +51,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js b/miniprogram/packageAPI/pages/network/udp-socket/udp-socket.js index 0a9e8681..b5408512 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,7 +28,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -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..33dfe390 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' @@ -59,21 +59,20 @@ 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) { diff --git a/miniprogram/packageAPI/pages/network/web-socket/web-socket.js b/miniprogram/packageAPI/pages/network/web-socket/web-socket.js index ae0e1a3b..01794dee 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,10 +31,11 @@ Page({ if (wx.offThemeChange) { wx.offThemeChange() } + this.closeSocket() }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { @@ -63,10 +63,6 @@ Page({ // }) }, - onUnload() { - this.closeSocket() - }, - toggleSocket(e) { const turnedOn = e.detail.value diff --git a/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js b/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js index 380b9982..abb5a833 100644 --- a/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js +++ b/miniprogram/packageAPI/pages/page/action-sheet/action-sheet.js @@ -21,7 +21,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/animation/animation.js b/miniprogram/packageAPI/pages/page/animation/animation.js index cc00e08f..a7c690a2 100644 --- a/miniprogram/packageAPI/pages/page/animation/animation.js +++ b/miniprogram/packageAPI/pages/page/animation/animation.js @@ -18,7 +18,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/canvas/canvas.js b/miniprogram/packageAPI/pages/page/canvas/canvas.js index 49f1c744..99b3f302 100644 --- a/miniprogram/packageAPI/pages/page/canvas/canvas.js +++ b/miniprogram/packageAPI/pages/page/canvas/canvas.js @@ -15,7 +15,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..406ffd3c 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 @@ -43,7 +43,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js b/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js index 671153c9..21b6945f 100644 --- a/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js +++ b/miniprogram/packageAPI/pages/page/intersection-observer/intersection-observer.js @@ -14,10 +14,11 @@ 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) { @@ -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..530f56e3 100644 --- a/miniprogram/packageAPI/pages/page/modal/modal.js +++ b/miniprogram/packageAPI/pages/page/modal/modal.js @@ -33,7 +33,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..171b5cd3 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,7 +19,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/navigator/navigator.js b/miniprogram/packageAPI/pages/page/navigator/navigator.js index ab183fbb..d5fce1ed 100644 --- a/miniprogram/packageAPI/pages/page/navigator/navigator.js +++ b/miniprogram/packageAPI/pages/page/navigator/navigator.js @@ -32,7 +32,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js b/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js index df59b257..f43f1bbc 100644 --- a/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js +++ b/miniprogram/packageAPI/pages/page/page-scroll/page-scroll.js @@ -26,7 +26,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..3d95eb72 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,7 +29,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..54839d16 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,7 +28,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/page/toast/toast.js b/miniprogram/packageAPI/pages/page/toast/toast.js index a940d1be..6a0444e3 100644 --- a/miniprogram/packageAPI/pages/page/toast/toast.js +++ b/miniprogram/packageAPI/pages/page/toast/toast.js @@ -37,7 +37,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js b/miniprogram/packageAPI/pages/performance/get-performance/get-performance.js index 5f6f8346..90955df1 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,7 +24,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..ef6cd6bc 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 @@ -60,7 +60,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..39099d64 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 @@ -71,7 +71,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { wx.onThemeChange(({theme}) => { diff --git a/miniprogram/packageAPI/pages/storage/storage/storage.js b/miniprogram/packageAPI/pages/storage/storage/storage.js index 6f7ec126..7b42f6dd 100644 --- a/miniprogram/packageAPI/pages/storage/storage/storage.js +++ b/miniprogram/packageAPI/pages/storage/storage/storage.js @@ -104,7 +104,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageAPI/pages/worker/worker/worker.js b/miniprogram/packageAPI/pages/worker/worker/worker.js index c5b0ce63..f2f0fb42 100644 --- a/miniprogram/packageAPI/pages/worker/worker/worker.js +++ b/miniprogram/packageAPI/pages/worker/worker/worker.js @@ -18,10 +18,13 @@ 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) { @@ -32,11 +35,6 @@ Page({ 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} 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..9abd4750 100644 --- a/miniprogram/packageChatTool/components/apiCategory/index.js +++ b/miniprogram/packageChatTool/components/apiCategory/index.js @@ -11,7 +11,7 @@ Component({ data: { apiCategory: '', }, - + methods: { }, @@ -22,4 +22,4 @@ Component({ this.setData({apiCategory}) } } -}) \ No newline at end of file +}) diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/badge.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/badge.js index 370a57e3..78f720db 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/badge.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/badge.js @@ -1,43 +1,46 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { uniqueFactory } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-badge`; -const getUniqueID = uniqueFactory('badge'); +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {uniqueFactory} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-badge` +const getUniqueID = uniqueFactory('badge') let Badge = class Badge extends SuperComponent { - constructor() { - super(...arguments); - this.options = { - multipleSlots: true, - }; - this.externalClasses = [`${prefix}-class`, `${prefix}-class-count`, `${prefix}-class-content`]; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - value: '', - labelID: '', - descriptionID: '', - }; - this.lifetimes = { - ready() { - const uniqueID = getUniqueID(); - this.setData({ - labelID: `${uniqueID}_label`, - descriptionID: `${uniqueID}_description`, - }); - }, - }; + constructor() { + super(...arguments) + this.options = { + multipleSlots: true, } -}; + this.externalClasses = [`${prefix}-class`, `${prefix}-class-count`, `${prefix}-class-content`] + this.properties = props + this.data = { + prefix, + classPrefix: name, + value: '', + labelID: '', + descriptionID: '', + } + this.lifetimes = { + ready() { + const uniqueID = getUniqueID() + this.setData({ + labelID: `${uniqueID}_label`, + descriptionID: `${uniqueID}_description`, + }) + }, + } + } +} Badge = __decorate([ - wxComponent() -], Badge); -export default Badge; + wxComponent() +], Badge) +export default Badge diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/index.js index 85b119ac..ca9515de 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/index.js @@ -1,3 +1,3 @@ -export * from './type'; -export * from './props'; -export * from './badge'; +export * from './type' +export * from './props' +export * from './badge' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/props.js index 095f798b..2c0564af 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/props.js @@ -1,41 +1,41 @@ const props = { - color: { - type: String, - value: '', - }, - content: { - type: String, - value: '', - }, - count: { - type: null, - value: 0, - }, - dot: { - type: Boolean, - value: false, - }, - externalClasses: { - type: Array, - }, - maxCount: { - type: Number, - value: 99, - }, - offset: { - type: Array, - }, - shape: { - type: String, - value: 'circle', - }, - showZero: { - type: Boolean, - value: false, - }, - size: { - type: String, - value: 'medium', - }, -}; -export default props; + color: { + type: String, + value: '', + }, + content: { + type: String, + value: '', + }, + count: { + type: null, + value: 0, + }, + dot: { + type: Boolean, + value: false, + }, + externalClasses: { + type: Array, + }, + maxCount: { + type: Number, + value: 99, + }, + offset: { + type: Array, + }, + shape: { + type: String, + value: 'circle', + }, + showZero: { + type: Boolean, + value: false, + }, + size: { + type: String, + value: 'medium', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/badge/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/button.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/button.js index 54498189..9cdf8cae 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/button.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/button.js @@ -1,101 +1,103 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { canIUseFormFieldButton } from '../common/version'; -import { calcIcon } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-button`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {canIUseFormFieldButton} from '../common/version' +import {calcIcon} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-button` let Button = class Button extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-icon`, `${prefix}-class-loading`]; - this.behaviors = canIUseFormFieldButton() ? ['wx://form-field-button'] : []; - this.properties = props; - this.options = { - multipleSlots: true, - }; - this.data = { - prefix, - className: '', - classPrefix: name, - }; - this.observers = { - 'theme, size, plain, block, shape, disabled, loading, variant'() { - this.setClass(); - }, - icon(icon) { - this.setData({ - _icon: calcIcon(icon, ''), - }); - }, - }; - this.lifetimes = { - attached() { - this.setClass(); - }, - }; - this.methods = { - setClass() { - const classList = [ - name, - `${prefix}-class`, - `${name}--${this.data.variant || 'base'}`, - `${name}--${this.data.theme || 'default'}`, - `${name}--${this.data.shape || 'rectangle'}`, - `${name}--size-${this.data.size || 'medium'}`, - ]; - if (this.data.block) { - classList.push(`${name}--block`); - } - if (this.data.disabled) { - classList.push(`${name}--disabled`); - } - if (this.data.ghost) { - classList.push(`${name}--ghost`); - } - this.setData({ - className: classList.join(' '), - }); - }, - getuserinfo(e) { - this.triggerEvent('getuserinfo', e.detail); - }, - contact(e) { - this.triggerEvent('contact', e.detail); - }, - getphonenumber(e) { - this.triggerEvent('getphonenumber', e.detail); - }, - error(e) { - this.triggerEvent('error', e.detail); - }, - opensetting(e) { - this.triggerEvent('opensetting', e.detail); - }, - launchapp(e) { - this.triggerEvent('launchapp', e.detail); - }, - chooseavatar(e) { - this.triggerEvent('chooseavatar', e.detail); - }, - agreeprivacyauthorization(e) { - this.triggerEvent('agreeprivacyauthorization', e.detail); - }, - handleTap(e) { - if (this.data.disabled || this.data.loading) - return; - this.triggerEvent('tap', e); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-icon`, `${prefix}-class-loading`] + this.behaviors = canIUseFormFieldButton() ? ['wx://form-field-button'] : [] + this.properties = props + this.options = { + multipleSlots: true, } -}; + this.data = { + prefix, + className: '', + classPrefix: name, + } + this.observers = { + 'theme, size, plain, block, shape, disabled, loading, variant': function () { + this.setClass() + }, + icon(icon) { + this.setData({ + _icon: calcIcon(icon, ''), + }) + }, + } + this.lifetimes = { + attached() { + this.setClass() + }, + } + this.methods = { + setClass() { + const classList = [ + name, + `${prefix}-class`, + `${name}--${this.data.variant || 'base'}`, + `${name}--${this.data.theme || 'default'}`, + `${name}--${this.data.shape || 'rectangle'}`, + `${name}--size-${this.data.size || 'medium'}`, + ] + if (this.data.block) { + classList.push(`${name}--block`) + } + if (this.data.disabled) { + classList.push(`${name}--disabled`) + } + if (this.data.ghost) { + classList.push(`${name}--ghost`) + } + this.setData({ + className: classList.join(' '), + }) + }, + getuserinfo(e) { + this.triggerEvent('getuserinfo', e.detail) + }, + contact(e) { + this.triggerEvent('contact', e.detail) + }, + getphonenumber(e) { + this.triggerEvent('getphonenumber', e.detail) + }, + error(e) { + this.triggerEvent('error', e.detail) + }, + opensetting(e) { + this.triggerEvent('opensetting', e.detail) + }, + launchapp(e) { + this.triggerEvent('launchapp', e.detail) + }, + chooseavatar(e) { + this.triggerEvent('chooseavatar', e.detail) + }, + agreeprivacyauthorization(e) { + this.triggerEvent('agreeprivacyauthorization', e.detail) + }, + handleTap(e) { + if (this.data.disabled || this.data.loading) return + this.triggerEvent('tap', e) + }, + } + } +} Button = __decorate([ - wxComponent() -], Button); -export default Button; + wxComponent() +], Button) +export default Button diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/index.js index beb0ad57..68cecd89 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/index.js @@ -1,3 +1,3 @@ -export * from './props'; -export * from './type'; -export * from './button'; +export * from './props' +export * from './type' +export * from './button' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/props.js index b81e71bd..7e236d7c 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/props.js @@ -1,108 +1,108 @@ const props = { - appParameter: { - type: String, - value: '', - }, - block: { - type: Boolean, - value: false, - }, - content: { - type: String, - }, - customDataset: { - type: null, - }, - disabled: { - type: null, - value: undefined, - }, - ghost: { - type: Boolean, - value: false, - }, - hoverClass: { - type: String, - value: '', - }, - hoverStartTime: { - type: Number, - value: 20, - }, - hoverStayTime: { - type: Number, - value: 70, - }, - hoverStopPropagation: { - type: Boolean, - value: false, - }, - icon: { - type: null, - }, - lang: { - type: String, - }, - loading: { - type: Boolean, - value: false, - }, - loadingProps: { - type: Object, - }, - openType: { - type: String, - }, - phoneNumberNoQuotaToast: { - type: Boolean, - value: true, - }, - sendMessageImg: { - type: String, - value: '截图', - }, - sendMessagePath: { - type: String, - value: '当前分享路径', - }, - sendMessageTitle: { - type: String, - value: '当前标题', - }, - sessionFrom: { - type: String, - value: '', - }, - shape: { - type: String, - value: 'rectangle', - }, - showMessageCard: { - type: Boolean, - value: false, - }, - size: { - type: String, - value: 'medium', - }, - style: { - type: String, - value: '', - }, - tId: { - type: String, - value: '', - }, - theme: { - type: String, - value: 'default', - }, - type: { - type: String, - }, - variant: { - type: String, - value: 'base', - }, -}; -export default props; + appParameter: { + type: String, + value: '', + }, + block: { + type: Boolean, + value: false, + }, + content: { + type: String, + }, + customDataset: { + type: null, + }, + disabled: { + type: null, + value: undefined, + }, + ghost: { + type: Boolean, + value: false, + }, + hoverClass: { + type: String, + value: '', + }, + hoverStartTime: { + type: Number, + value: 20, + }, + hoverStayTime: { + type: Number, + value: 70, + }, + hoverStopPropagation: { + type: Boolean, + value: false, + }, + icon: { + type: null, + }, + lang: { + type: String, + }, + loading: { + type: Boolean, + value: false, + }, + loadingProps: { + type: Object, + }, + openType: { + type: String, + }, + phoneNumberNoQuotaToast: { + type: Boolean, + value: true, + }, + sendMessageImg: { + type: String, + value: '截图', + }, + sendMessagePath: { + type: String, + value: '当前分享路径', + }, + sendMessageTitle: { + type: String, + value: '当前标题', + }, + sessionFrom: { + type: String, + value: '', + }, + shape: { + type: String, + value: 'rectangle', + }, + showMessageCard: { + type: Boolean, + value: false, + }, + size: { + type: String, + value: 'medium', + }, + style: { + type: String, + value: '', + }, + tId: { + type: String, + value: '', + }, + theme: { + type: String, + value: 'default', + }, + type: { + type: String, + }, + variant: { + type: String, + value: 'base', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/button/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/button/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/cell-group.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/cell-group.js index 966ceece..344c9a04 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/cell-group.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/cell-group.js @@ -1,43 +1,46 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-cell-group`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-cell-group` let CellGroup = class CellGroup extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-title`]; - this.relations = { - '../cell/cell': { - type: 'child', - linked() { - this.updateLastChid(); - }, - unlinked() { - this.updateLastChid(); - }, - }, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.methods = { - updateLastChid() { - const items = this.$children; - items.forEach((child, index) => child.setData({ isLastChild: index === items.length - 1 })); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-title`] + this.relations = { + '../cell/cell': { + type: 'child', + linked() { + this.updateLastChid() + }, + unlinked() { + this.updateLastChid() + }, + }, } -}; + this.properties = props + this.data = { + prefix, + classPrefix: name, + } + this.methods = { + updateLastChid() { + const items = this.$children + items.forEach((child, index) => child.setData({isLastChild: index === items.length - 1})) + }, + } + } +} CellGroup = __decorate([ - wxComponent() -], CellGroup); -export default CellGroup; + wxComponent() +], CellGroup) +export default CellGroup diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/props.js index c8d887e8..b43d430d 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/props.js @@ -1,17 +1,17 @@ const props = { - bordered: { - type: Boolean, - }, - externalClasses: { - type: Array, - }, - theme: { - type: String, - value: 'default', - }, - title: { - type: String, - value: '', - }, -}; -export default props; + bordered: { + type: Boolean, + }, + externalClasses: { + type: Array, + }, + theme: { + type: String, + value: 'default', + }, + title: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell-group/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/cell.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/cell.js index c7c5ec5e..a58aee5b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/cell.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/cell.js @@ -1,75 +1,81 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { calcIcon } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-cell`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {calcIcon} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-cell` let Cell = class Cell extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-title`, - `${prefix}-class-description`, - `${prefix}-class-note`, - `${prefix}-class-hover`, - `${prefix}-class-image`, - `${prefix}-class-left`, - `${prefix}-class-left-icon`, - `${prefix}-class-center`, - `${prefix}-class-right`, - `${prefix}-class-right-icon`, - ]; - this.relations = { - '../cell-group/cell-group': { - type: 'parent', - }, - }; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - isLastChild: false, - }; - this.observers = { - leftIcon(v) { - this.setIcon('_leftIcon', v, ''); - }, - rightIcon(v) { - this.setIcon('_rightIcon', v, ''); - }, - arrow(v) { - this.setIcon('_arrow', v, 'chevron-right'); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-title`, + `${prefix}-class-description`, + `${prefix}-class-note`, + `${prefix}-class-hover`, + `${prefix}-class-image`, + `${prefix}-class-left`, + `${prefix}-class-left-icon`, + `${prefix}-class-center`, + `${prefix}-class-right`, + `${prefix}-class-right-icon`, + ] + this.relations = { + '../cell-group/cell-group': { + type: 'parent', + }, } - setIcon(name, value, defaultValue) { - this.setData({ - [name]: calcIcon(value, defaultValue), - }); + this.options = { + multipleSlots: true, } - onClick(e) { - this.triggerEvent('click', e.detail); - this.jumpLink(); + this.properties = props + this.data = { + prefix, + classPrefix: name, + isLastChild: false, } - jumpLink(urlKey = 'url', link = 'jumpType') { - const url = this.data[urlKey]; - const jumpType = this.data[link]; - if (url) { - wx[jumpType]({ url }); - } + this.observers = { + leftIcon(v) { + this.setIcon('_leftIcon', v, '') + }, + rightIcon(v) { + this.setIcon('_rightIcon', v, '') + }, + arrow(v) { + this.setIcon('_arrow', v, 'chevron-right') + }, } -}; + } + + setIcon(name, value, defaultValue) { + this.setData({ + [name]: calcIcon(value, defaultValue), + }) + } + + onClick(e) { + this.triggerEvent('click', e.detail) + this.jumpLink() + } + + jumpLink(urlKey = 'url', link = 'jumpType') { + const url = this.data[urlKey] + const jumpType = this.data[link] + if (url) { + wx[jumpType]({url}) + } + } +} Cell = __decorate([ - wxComponent() -], Cell); -export default Cell; + wxComponent() +], Cell) +export default Cell diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/props.js index c5382532..c7347992 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/props.js @@ -1,48 +1,48 @@ const props = { - align: { - type: String, - value: 'middle', - }, - arrow: { - type: null, - value: false, - }, - bordered: { - type: Boolean, - value: true, - }, - description: { - type: String, - }, - hover: { - type: Boolean, - }, - image: { - type: String, - }, - jumpType: { - type: String, - value: 'navigateTo', - }, - leftIcon: { - type: null, - }, - note: { - type: String, - }, - required: { - type: Boolean, - value: false, - }, - rightIcon: { - type: null, - }, - title: { - type: String, - }, - url: { - type: String, - value: '', - }, -}; -export default props; + align: { + type: String, + value: 'middle', + }, + arrow: { + type: null, + value: false, + }, + bordered: { + type: Boolean, + value: true, + }, + description: { + type: String, + }, + hover: { + type: Boolean, + }, + image: { + type: String, + }, + jumpType: { + type: String, + value: 'navigateTo', + }, + leftIcon: { + type: null, + }, + note: { + type: String, + }, + required: { + type: Boolean, + value: false, + }, + rightIcon: { + type: null, + }, + title: { + type: String, + }, + url: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/cell/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/checkbox-group.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/checkbox-group.js index 6d57e566..53207a8c 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/checkbox-group.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/checkbox-group.js @@ -1,162 +1,167 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-checkbox-group`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-checkbox-group` let CheckBoxGroup = class CheckBoxGroup extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.relations = { - '../checkbox/checkbox': { - type: 'descendant', - }, - }; - this.data = { - prefix, - classPrefix: name, - checkboxOptions: [], - }; - this.properties = props; - this.observers = { - value() { - this.updateChildren(); - }, - options() { - this.initWithOptions(); - }, - disabled(v) { - var _a; - if ((_a = this.data.options) === null || _a === void 0 ? void 0 : _a.length) { - this.initWithOptions(); - return; - } - this.getChildren().forEach((item) => { - item.setDisabled(v); - }); - }, - }; - this.lifetimes = { - ready() { - this.setCheckall(); - }, - }; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.$checkAll = null; - this.methods = { - getChildren() { - let items = this.$children; - if (!items.length) { - items = this.selectAllComponents(`.${prefix}-checkbox-option`); - } - return items || []; - }, - updateChildren() { - const items = this.getChildren(); - const { value } = this.data; - if (items.length > 0) { - items.forEach((item) => { - !item.data.checkAll && + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.relations = { + '../checkbox/checkbox': { + type: 'descendant', + }, + } + this.data = { + prefix, + classPrefix: name, + checkboxOptions: [], + } + this.properties = props + this.observers = { + value() { + this.updateChildren() + }, + options() { + this.initWithOptions() + }, + disabled(v) { + let _a + if ((_a = this.data.options) === null || _a === void 0 ? void 0 : _a.length) { + this.initWithOptions() + return + } + this.getChildren().forEach((item) => { + item.setDisabled(v) + }) + }, + } + this.lifetimes = { + ready() { + this.setCheckall() + }, + } + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.$checkAll = null + this.methods = { + getChildren() { + let items = this.$children + if (!items.length) { + items = this.selectAllComponents(`.${prefix}-checkbox-option`) + } + return items || [] + }, + updateChildren() { + const items = this.getChildren() + const {value} = this.data + if (items.length > 0) { + items.forEach((item) => { + !item.data.checkAll && item.setData({ - checked: value === null || value === void 0 ? void 0 : value.includes(item.data.value), - }); - }); - if (items.some((item) => item.data.checkAll)) { - this.setCheckall(); - } - } - }, - updateValue({ value, checked, checkAll, item, indeterminate }) { - let { value: newValue } = this.data; - const { max } = this.data; - const keySet = new Set(this.getChildren().map((item) => item.data.value)); - newValue = newValue.filter((value) => keySet.has(value)); - if (max && checked && newValue.length === max) - return; - if (checkAll) { - const items = this.getChildren(); - newValue = + checked: value === null || value === void 0 ? void 0 : value.includes(item.data.value), + }) + }) + if (items.some((item) => item.data.checkAll)) { + this.setCheckall() + } + } + }, + updateValue({ + value, checked, checkAll, item, indeterminate + }) { + let {value: newValue} = this.data + const {max} = this.data + const keySet = new Set(this.getChildren().map((item) => item.data.value)) + newValue = newValue.filter((value) => keySet.has(value)) + if (max && checked && newValue.length === max) return + if (checkAll) { + const items = this.getChildren() + newValue = !checked && indeterminate - ? items - .filter(({ data }) => !(data.disabled && !newValue.includes(data.value))) - .map((item) => item.data.value) - : items - .filter(({ data }) => { - if (data.disabled) { - return newValue.includes(data.value); - } - return checked && !data.checkAll; + ? items + .filter(({data}) => !(data.disabled && !newValue.includes(data.value))) + .map((item) => item.data.value) + : items + .filter(({data}) => { + if (data.disabled) { + return newValue.includes(data.value) + } + return checked && !data.checkAll }) - .map(({ data }) => data.value); - } - else if (checked) { - newValue = newValue.concat(value); - } - else { - const index = newValue.findIndex((v) => v === value); - newValue.splice(index, 1); - } - this._trigger('change', { value: newValue, context: item }); - }, - initWithOptions() { - const { options, value, keys } = this.data; - if (!(options === null || options === void 0 ? void 0 : options.length) || !Array.isArray(options)) - return; - const checkboxOptions = options.map((item) => { - var _a, _b, _c; - const isLabel = ['number', 'string'].includes(typeof item); - return isLabel - ? { - label: `${item}`, - value: item, - checked: value === null || value === void 0 ? void 0 : value.includes(item), - } - : Object.assign(Object.assign({}, item), { label: item[(_a = keys === null || keys === void 0 ? void 0 : keys.label) !== null && _a !== void 0 ? _a : 'label'], value: item[(_b = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _b !== void 0 ? _b : 'value'], checked: value === null || value === void 0 ? void 0 : value.includes(item[(_c = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _c !== void 0 ? _c : 'value']) }); - }); - this.setData({ - checkboxOptions, - }); - }, - handleInnerChildChange(e) { - var _a; - const { item } = e.target.dataset; - const { checked } = e.detail; - const rect = {}; - if (item.checkAll) { - rect.indeterminate = (_a = this.$checkAll) === null || _a === void 0 ? void 0 : _a.data.indeterminate; - } - this.updateValue(Object.assign(Object.assign(Object.assign({}, item), { checked, item }), rect)); - }, - setCheckall() { - const items = this.getChildren(); - if (!this.$checkAll) { - this.$checkAll = items.find((item) => item.data.checkAll); - } - if (!this.$checkAll) - return; - const { value } = this.data; - const valueSet = new Set(value === null || value === void 0 ? void 0 : value.filter((val) => val !== this.$checkAll.data.value)); - const isCheckall = items.every((item) => (item.data.checkAll ? true : valueSet.has(item.data.value))); - this.$checkAll.setData({ - checked: valueSet.size > 0, - indeterminate: !isCheckall, - }); - }, - }; + .map(({data}) => data.value) + } else if (checked) { + newValue = newValue.concat(value) + } else { + const index = newValue.findIndex((v) => v === value) + newValue.splice(index, 1) + } + this._trigger('change', {value: newValue, context: item}) + }, + initWithOptions() { + const {options, value, keys} = this.data + if (!(options === null || options === void 0 ? void 0 : options.length) || !Array.isArray(options)) return + const checkboxOptions = options.map((item) => { + let _a; let _b; let + _c + const isLabel = ['number', 'string'].includes(typeof item) + return isLabel + ? { + label: `${item}`, + value: item, + checked: value === null || value === void 0 ? void 0 : value.includes(item), + } + : ({ + ...item, label: item[(_a = keys === null || keys === void 0 ? void 0 : keys.label) !== null && _a !== void 0 ? _a : 'label'], value: item[(_b = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _b !== void 0 ? _b : 'value'], checked: value === null || value === void 0 ? void 0 : value.includes(item[(_c = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _c !== void 0 ? _c : 'value']) + }) + }) + this.setData({ + checkboxOptions, + }) + }, + handleInnerChildChange(e) { + let _a + const {item} = e.target.dataset + const {checked} = e.detail + const rect = {} + if (item.checkAll) { + rect.indeterminate = (_a = this.$checkAll) === null || _a === void 0 ? void 0 : _a.data.indeterminate + } + this.updateValue({ + ...item, checked, item, ...rect + }) + }, + setCheckall() { + const items = this.getChildren() + if (!this.$checkAll) { + this.$checkAll = items.find((item) => item.data.checkAll) + } + if (!this.$checkAll) return + const {value} = this.data + const valueSet = new Set(value === null || value === void 0 ? void 0 : value.filter((val) => val !== this.$checkAll.data.value)) + const isCheckall = items.every((item) => (item.data.checkAll ? true : valueSet.has(item.data.value))) + this.$checkAll.setData({ + checked: valueSet.size > 0, + indeterminate: !isCheckall, + }) + }, } -}; + } +} CheckBoxGroup = __decorate([ - wxComponent() -], CheckBoxGroup); -export default CheckBoxGroup; + wxComponent() +], CheckBoxGroup) +export default CheckBoxGroup diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/props.js index 008d05ed..3460eaa0 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/props.js @@ -1,34 +1,34 @@ const props = { - borderless: { - type: Boolean, - value: false, - }, - disabled: { - type: null, - value: undefined, - }, - keys: { - type: Object, - }, - max: { - type: Number, - value: undefined, - }, - name: { - type: String, - value: '', - }, - options: { - type: Array, - value: [], - }, - value: { - type: Array, - value: null, - }, - defaultValue: { - type: Array, - value: [], - }, -}; -export default props; + borderless: { + type: Boolean, + value: false, + }, + disabled: { + type: null, + value: undefined, + }, + keys: { + type: Object, + }, + max: { + type: Number, + value: undefined, + }, + name: { + type: String, + value: '', + }, + options: { + type: Array, + value: [], + }, + value: { + type: Array, + value: null, + }, + defaultValue: { + type: Array, + value: [], + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox-group/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/checkbox.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/checkbox.js index b4e3025a..355a4b26 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/checkbox.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/checkbox.js @@ -1,99 +1,104 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import Props from './props'; -const { prefix } = config; -const name = `${prefix}-checkbox`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import Props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-checkbox` let CheckBox = class CheckBox extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-label`, - `${prefix}-class-icon`, - `${prefix}-class-content`, - `${prefix}-class-border`, - ]; - this.behaviors = ['wx://form-field']; - this.relations = { - '../checkbox-group/checkbox-group': { - type: 'ancestor', - linked(parent) { - const { value, disabled, borderless } = parent.data; - const valueSet = new Set(value); - const checkedFromParent = valueSet.has(this.data.value); - const data = { - _disabled: this.data.disabled == null ? disabled : this.data.disabled, - }; - if (borderless) { - data.borderless = true; - } - data.checked = this.data.checked || checkedFromParent; - if (this.data.checked) { - parent.updateValue(this.data); - } - if (this.data.checkAll) { - data.checked = valueSet.size > 0; - } - this.setData(data); - }, - }, - }; - this.options = { - multipleSlots: true, - }; - this.properties = Object.assign(Object.assign({}, Props), { theme: { - type: String, - value: 'default', - }, tId: { - type: String, - } }); - this.data = { - prefix, - classPrefix: name, - _disabled: false, - }; - this.observers = { - disabled(v) { - this.setData({ _disabled: v }); - }, - }; - this.controlledProps = [ - { - key: 'checked', - event: 'change', - }, - ]; - this.methods = { - handleTap(e) { - const { _disabled, readonly, contentDisabled } = this.data; - const { target } = e.currentTarget.dataset; - if (_disabled || readonly || (target === 'text' && contentDisabled)) - return; - const { value, label } = this.data; - const checked = !this.data.checked; - const parent = this.$parent; - if (parent) { - parent.updateValue(Object.assign(Object.assign({}, this.data), { checked, item: { label, value, checked } })); - } - else { - this._trigger('change', { context: { value, label }, checked }); - } - }, - setDisabled(disabled) { - this.setData({ - _disabled: this.data.disabled || disabled, - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-label`, + `${prefix}-class-icon`, + `${prefix}-class-content`, + `${prefix}-class-border`, + ] + this.behaviors = ['wx://form-field'] + this.relations = { + '../checkbox-group/checkbox-group': { + type: 'ancestor', + linked(parent) { + const {value, disabled, borderless} = parent.data + const valueSet = new Set(value) + const checkedFromParent = valueSet.has(this.data.value) + const data = { + _disabled: this.data.disabled == null ? disabled : this.data.disabled, + } + if (borderless) { + data.borderless = true + } + data.checked = this.data.checked || checkedFromParent + if (this.data.checked) { + parent.updateValue(this.data) + } + if (this.data.checkAll) { + data.checked = valueSet.size > 0 + } + this.setData(data) + }, + }, } -}; + this.options = { + multipleSlots: true, + } + this.properties = { + ...Props, + theme: { + type: String, + value: 'default', + }, + tId: { + type: String, + } + } + this.data = { + prefix, + classPrefix: name, + _disabled: false, + } + this.observers = { + disabled(v) { + this.setData({_disabled: v}) + }, + } + this.controlledProps = [ + { + key: 'checked', + event: 'change', + }, + ] + this.methods = { + handleTap(e) { + const {_disabled, readonly, contentDisabled} = this.data + const {target} = e.currentTarget.dataset + if (_disabled || readonly || (target === 'text' && contentDisabled)) return + const {value, label} = this.data + const checked = !this.data.checked + const parent = this.$parent + if (parent) { + parent.updateValue({...this.data, checked, item: {label, value, checked}}) + } else { + this._trigger('change', {context: {value, label}, checked}) + } + }, + setDisabled(disabled) { + this.setData({ + _disabled: this.data.disabled || disabled, + }) + }, + } + } +} CheckBox = __decorate([ - wxComponent() -], CheckBox); -export default CheckBox; + wxComponent() +], CheckBox) +export default CheckBox diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/props.js index b7192f0b..83993cf4 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/props.js @@ -1,67 +1,67 @@ const props = { - block: { - type: Boolean, - value: true, - }, - borderless: { - type: Boolean, - value: false, - }, - checkAll: { - type: Boolean, - value: false, - }, - checked: { - type: Boolean, - value: null, - }, - defaultChecked: { - type: Boolean, - value: false, - }, - content: { - type: String, - }, - contentDisabled: { - type: Boolean, - }, - disabled: { - type: null, - value: undefined, - }, - icon: { - type: null, - value: 'circle', - }, - indeterminate: { - type: Boolean, - value: false, - }, - label: { - type: String, - }, - maxContentRow: { - type: Number, - value: 5, - }, - maxLabelRow: { - type: Number, - value: 3, - }, - name: { - type: String, - value: '', - }, - placement: { - type: String, - value: 'left', - }, - readonly: { - type: Boolean, - value: false, - }, - value: { - type: null, - }, -}; -export default props; + block: { + type: Boolean, + value: true, + }, + borderless: { + type: Boolean, + value: false, + }, + checkAll: { + type: Boolean, + value: false, + }, + checked: { + type: Boolean, + value: null, + }, + defaultChecked: { + type: Boolean, + value: false, + }, + content: { + type: String, + }, + contentDisabled: { + type: Boolean, + }, + disabled: { + type: null, + value: undefined, + }, + icon: { + type: null, + value: 'circle', + }, + indeterminate: { + type: Boolean, + value: false, + }, + label: { + type: String, + }, + maxContentRow: { + type: Number, + value: 5, + }, + maxLabelRow: { + type: Number, + value: 3, + }, + name: { + type: String, + value: '', + }, + placement: { + type: String, + value: 'left', + }, + readonly: { + type: Boolean, + value: false, + }, + value: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/checkbox/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/bus.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/bus.js index 5a6c8898..ec2b18c9 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/bus.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/bus.js @@ -1,22 +1,24 @@ export default class Bus { - constructor() { - this.listeners = new Map(); - this.emitted = new Set(); + constructor() { + this.listeners = new Map() + this.emitted = new Set() + } + + on(evtName, listener) { + if (this.emitted.has(evtName)) { + listener() + return } - on(evtName, listener) { - if (this.emitted.has(evtName)) { - listener(); - return; - } - const target = this.listeners.get(evtName) || []; - target.push(listener); - this.listeners.set(evtName, target); - } - emit(evtName) { - const listeners = this.listeners.get(evtName); - if (listeners) { - listeners.forEach((func) => func()); - } - this.emitted.add(evtName); + const target = this.listeners.get(evtName) || [] + target.push(listener) + this.listeners.set(evtName, target) + } + + emit(evtName) { + const listeners = this.listeners.get(evtName) + if (listeners) { + listeners.forEach((func) => func()) } + this.emitted.add(evtName) + } } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/common.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/common.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/common.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/common.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/component.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/component.js index 4e01a69e..2d8e29c9 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/component.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/component.js @@ -1,5 +1,5 @@ const TComponent = (options) => { - options.options = Object.assign({ multipleSlots: true, addGlobalClass: true }, options.options); - return Component(options); -}; -export default TComponent; + options.options = {multipleSlots: true, addGlobalClass: true, ...options.options} + return Component(options) +} +export default TComponent diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/config.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/config.js index c0dfab2b..30db7900 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/config.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/config.js @@ -1,4 +1,4 @@ export default { - prefix: "t", -}; -export const prefix = "t"; + prefix: 't', +} +export const prefix = 't' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/index.js index 62fda1f7..74ab441d 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/index.js @@ -1,127 +1,124 @@ -import { getDateRect, isSameDate, getMonthDateRect, isValidDate, getDate } from '../date'; +import { + getDateRect, isSameDate, getMonthDateRect, isValidDate, getDate +} from '../date' + export default class TCalendar { - constructor(options = {}) { - this.type = 'single'; - Object.assign(this, options); - if (!this.minDate) - this.minDate = getDate(); - if (!this.maxDate) - this.maxDate = getDate(6); + constructor(options = {}) { + this.type = 'single' + Object.assign(this, options) + if (!this.minDate) this.minDate = getDate() + if (!this.maxDate) this.maxDate = getDate(6) + } + + getTrimValue() { + const {value, type} = this + const format = (val) => { + if (val instanceof Date) return val + if (typeof val === 'number') return new Date(val) + return new Date() } - getTrimValue() { - const { value, type } = this; - const format = (val) => { - if (val instanceof Date) - return val; - if (typeof val === 'number') - return new Date(val); - return new Date(); - }; - if (type === 'single' && isValidDate(value)) - return format(value); - if (type === 'multiple' || type === 'range') { - if (Array.isArray(value)) { - const isValid = value.every((item) => isValidDate(item)); - return isValid ? value.map((item) => format(item)) : []; - } - return []; - } + if (type === 'single' && isValidDate(value)) return format(value) + if (type === 'multiple' || type === 'range') { + if (Array.isArray(value)) { + const isValid = value.every((item) => isValidDate(item)) + return isValid ? value.map((item) => format(item)) : [] + } + return [] } - getDays(weekdays) { - const ans = []; - let i = this.firstDayOfWeek % 7; - while (ans.length < 7) { - ans.push(weekdays[i]); - i = (i + 1) % 7; - } - return ans; + } + + getDays(weekdays) { + const ans = [] + let i = this.firstDayOfWeek % 7 + while (ans.length < 7) { + ans.push(weekdays[i]) + i = (i + 1) % 7 } - getMonths() { - const ans = []; - const selectedDate = this.getTrimValue(); - const { minDate, maxDate, type, format } = this; - let { year: minYear, month: minMonth, time: minTime } = getDateRect(minDate); - const { year: maxYear, month: maxMonth, time: maxTime } = getDateRect(maxDate); - const calcType = (year, month, date) => { - const curDate = new Date(year, month, date, 23, 59, 59); - if (type === 'single' && selectedDate) { - if (isSameDate({ year, month, date }, selectedDate)) - return 'selected'; - } - if (type === 'multiple' && selectedDate) { - const hit = selectedDate.some((item) => isSameDate({ year, month, date }, item)); - if (hit) { - return 'selected'; - } - } - if (type === 'range' && selectedDate) { - if (Array.isArray(selectedDate)) { - const [startDate, endDate] = selectedDate; - if (startDate && isSameDate({ year, month, date }, startDate)) - return 'start'; - if (endDate && isSameDate({ year, month, date }, endDate)) - return 'end'; - if (startDate && endDate && curDate.getTime() > startDate.getTime() && curDate.getTime() < endDate.getTime()) - return 'centre'; - } - } - const minCurDate = new Date(year, month, date, 0, 0, 0); - if (curDate.getTime() < minTime || minCurDate.getTime() > maxTime) { - return 'disabled'; - } - return ''; - }; - while (minYear < maxYear || (minYear === maxYear && minMonth <= maxMonth)) { - const target = getMonthDateRect(new Date(minYear, minMonth, 1)); - const months = []; - for (let i = 1; i <= 31; i++) { - if (i > target.lastDate) - break; - const dateObj = { - date: new Date(minYear, minMonth, i), - day: i, - type: calcType(minYear, minMonth, i), - }; - months.push(format ? format(dateObj) : dateObj); - } - ans.push({ - year: minYear, - month: minMonth, - months, - weekdayOfFirstDay: target.weekdayOfFirstDay, - }); - const curDate = getDateRect(new Date(minYear, minMonth + 1, 1)); - minYear = curDate.year; - minMonth = curDate.month; + return ans + } + + getMonths() { + const ans = [] + const selectedDate = this.getTrimValue() + const { + minDate, maxDate, type, format + } = this + let {year: minYear, month: minMonth, time: minTime} = getDateRect(minDate) + const {year: maxYear, month: maxMonth, time: maxTime} = getDateRect(maxDate) + const calcType = (year, month, date) => { + const curDate = new Date(year, month, date, 23, 59, 59) + if (type === 'single' && selectedDate) { + if (isSameDate({year, month, date}, selectedDate)) return 'selected' + } + if (type === 'multiple' && selectedDate) { + const hit = selectedDate.some((item) => isSameDate({year, month, date}, item)) + if (hit) { + return 'selected' } - return ans; - } - select({ cellType, year, month, date }) { - const { type } = this; - const selectedDate = this.getTrimValue(); - if (cellType === 'disabled') - return; - const selected = new Date(year, month, date); - this.value = selected; - if (type === 'range' && Array.isArray(selectedDate)) { - if (selectedDate.length === 1 && selected > selectedDate[0]) { - this.value = [selectedDate[0], selected]; - } - else { - this.value = [selected]; - } + } + if (type === 'range' && selectedDate) { + if (Array.isArray(selectedDate)) { + const [startDate, endDate] = selectedDate + if (startDate && isSameDate({year, month, date}, startDate)) return 'start' + if (endDate && isSameDate({year, month, date}, endDate)) return 'end' + if (startDate && endDate && curDate.getTime() > startDate.getTime() && curDate.getTime() < endDate.getTime()) return 'centre' } - else if (type === 'multiple' && Array.isArray(selectedDate)) { - const newVal = [...selectedDate]; - const index = selectedDate.findIndex((item) => isSameDate(item, selected)); - if (index > -1) { - newVal.splice(index, 1); - } - else { - newVal.push(selected); - } - this.value = newVal; + } + const minCurDate = new Date(year, month, date, 0, 0, 0) + if (curDate.getTime() < minTime || minCurDate.getTime() > maxTime) { + return 'disabled' + } + return '' + } + while (minYear < maxYear || (minYear === maxYear && minMonth <= maxMonth)) { + const target = getMonthDateRect(new Date(minYear, minMonth, 1)) + const months = [] + for (let i = 1; i <= 31; i++) { + if (i > target.lastDate) break + const dateObj = { + date: new Date(minYear, minMonth, i), + day: i, + type: calcType(minYear, minMonth, i), } - return this.value; + months.push(format ? format(dateObj) : dateObj) + } + ans.push({ + year: minYear, + month: minMonth, + months, + weekdayOfFirstDay: target.weekdayOfFirstDay, + }) + const curDate = getDateRect(new Date(minYear, minMonth + 1, 1)) + minYear = curDate.year + minMonth = curDate.month + } + return ans + } + + select({ + cellType, year, month, date + }) { + const {type} = this + const selectedDate = this.getTrimValue() + if (cellType === 'disabled') return + const selected = new Date(year, month, date) + this.value = selected + if (type === 'range' && Array.isArray(selectedDate)) { + if (selectedDate.length === 1 && selected > selectedDate[0]) { + this.value = [selectedDate[0], selected] + } else { + this.value = [selected] + } + } else if (type === 'multiple' && Array.isArray(selectedDate)) { + const newVal = [...selectedDate] + const index = selectedDate.findIndex((item) => isSameDate(item, selected)) + if (index > -1) { + newVal.splice(index, 1) + } else { + newVal.push(selected) + } + this.value = newVal } + return this.value + } } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/calendar/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js index d6273beb..7532cbfd 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/cmyk.js @@ -1,57 +1,57 @@ export const rgb2cmyk = (red, green, blue) => { - let computedC = 0; - let computedM = 0; - let computedY = 0; - let computedK = 0; - const r = parseInt(`${red}`.replace(/\s/g, ''), 10); - const g = parseInt(`${green}`.replace(/\s/g, ''), 10); - const b = parseInt(`${blue}`.replace(/\s/g, ''), 10); - if (r === 0 && g === 0 && b === 0) { - computedK = 1; - return [0, 0, 0, 1]; - } - computedC = 1 - r / 255; - computedM = 1 - g / 255; - computedY = 1 - b / 255; - const minCMY = Math.min(computedC, Math.min(computedM, computedY)); - computedC = (computedC - minCMY) / (1 - minCMY); - computedM = (computedM - minCMY) / (1 - minCMY); - computedY = (computedY - minCMY) / (1 - minCMY); - computedK = minCMY; - return [computedC, computedM, computedY, computedK]; -}; + let computedC = 0 + let computedM = 0 + let computedY = 0 + let computedK = 0 + const r = parseInt(`${red}`.replace(/\s/g, ''), 10) + const g = parseInt(`${green}`.replace(/\s/g, ''), 10) + const b = parseInt(`${blue}`.replace(/\s/g, ''), 10) + if (r === 0 && g === 0 && b === 0) { + computedK = 1 + return [0, 0, 0, 1] + } + computedC = 1 - r / 255 + computedM = 1 - g / 255 + computedY = 1 - b / 255 + const minCMY = Math.min(computedC, Math.min(computedM, computedY)) + computedC = (computedC - minCMY) / (1 - minCMY) + computedM = (computedM - minCMY) / (1 - minCMY) + computedY = (computedY - minCMY) / (1 - minCMY) + computedK = minCMY + return [computedC, computedM, computedY, computedK] +} export const cmyk2rgb = (cyan, magenta, yellow, black) => { - let c = cyan / 100; - let m = magenta / 100; - let y = yellow / 100; - const k = black / 100; - c = c * (1 - k) + k; - m = m * (1 - k) + k; - y = y * (1 - k) + k; - let r = 1 - c; - let g = 1 - m; - let b = 1 - y; - r = Math.round(255 * r); - g = Math.round(255 * g); - b = Math.round(255 * b); - return { - r, - g, - b, - }; -}; -const REG_CMYK_STRING = /cmyk\((\d+%?),(\d+%?),(\d+%?),(\d+%?)\)/; -const toNumber = (str) => Math.max(0, Math.min(255, parseInt(str, 10))); + let c = cyan / 100 + let m = magenta / 100 + let y = yellow / 100 + const k = black / 100 + c = c * (1 - k) + k + m = m * (1 - k) + k + y = y * (1 - k) + k + let r = 1 - c + let g = 1 - m + let b = 1 - y + r = Math.round(255 * r) + g = Math.round(255 * g) + b = Math.round(255 * b) + return { + r, + g, + b, + } +} +const REG_CMYK_STRING = /cmyk\((\d+%?),(\d+%?),(\d+%?),(\d+%?)\)/ +const toNumber = (str) => Math.max(0, Math.min(255, parseInt(str, 10))) export const cmykInputToColor = (input) => { - if (/cmyk/i.test(input)) { - const str = input.replace(/\s/g, ''); - const match = str.match(REG_CMYK_STRING); - const c = toNumber(match[1]); - const m = toNumber(match[2]); - const y = toNumber(match[3]); - const k = toNumber(match[4]); - const { r, g, b } = cmyk2rgb(c, m, y, k); - return `rgb(${r}, ${g}, ${b})`; - } - return input; -}; + if (/cmyk/i.test(input)) { + const str = input.replace(/\s/g, '') + const match = str.match(REG_CMYK_STRING) + const c = toNumber(match[1]) + const m = toNumber(match[2]) + const y = toNumber(match[3]) + const k = toNumber(match[4]) + const {r, g, b} = cmyk2rgb(c, m, y, k) + return `rgb(${r}, ${g}, ${b})` + } + return input +} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/color.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/color.js index 847ec5bd..6c490a7a 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/color.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/color.js @@ -1,334 +1,393 @@ -import tinyColor from 'tinycolor2'; -import { cmykInputToColor, rgb2cmyk } from './cmyk'; -import { parseGradientString, isGradientColor } from './gradient'; -const mathRound = Math.round; -const hsv2rgba = (states) => tinyColor(states).toRgb(); -const hsv2hsva = (states) => tinyColor(states).toHsv(); -const hsv2hsla = (states) => tinyColor(states).toHsl(); +import tinyColor from 'tinycolor2' +import {cmykInputToColor, rgb2cmyk} from './cmyk' +import {parseGradientString, isGradientColor} from './gradient' + +const mathRound = Math.round +const hsv2rgba = (states) => tinyColor(states).toRgb() +const hsv2hsva = (states) => tinyColor(states).toHsv() +const hsv2hsla = (states) => tinyColor(states).toHsl() export const gradientColors2string = (object) => { - const { points, degree } = object; - const colorsStop = points - .sort((pA, pB) => pA.left - pB.left) - .map((p) => `${p.color} ${Math.round(p.left * 100) / 100}%`); - return `linear-gradient(${degree}deg,${colorsStop.join(',')})`; -}; -export const getColorWithoutAlpha = (color) => tinyColor(color).setAlpha(1).toHexString(); -export const genId = () => (1 + Math.random() * 4294967295).toString(16); + const {points, degree} = object + const colorsStop = points + .sort((pA, pB) => pA.left - pB.left) + .map((p) => `${p.color} ${Math.round(p.left * 100) / 100}%`) + return `linear-gradient(${degree}deg,${colorsStop.join(',')})` +} +export const getColorWithoutAlpha = (color) => tinyColor(color).setAlpha(1).toHexString() +export const genId = () => (1 + Math.random() * 4294967295).toString(16) export const genGradientPoint = (left, color) => ({ - id: genId(), - left, - color, -}); + id: genId(), + left, + color, +}) export class Color { - constructor(input) { - this.states = { - s: 100, - v: 100, - h: 100, - a: 1, - }; - this.gradientStates = { - colors: [], - degree: 0, - selectedId: null, - css: '', - }; - this.update(input); - } - update(input) { - var _a, _b; - const gradientColors = parseGradientString(input); - if (this.isGradient && !gradientColors) { - const colorHsv = tinyColor(input).toHsv(); - this.states = colorHsv; - this.updateCurrentGradientColor(); - return; - } - this.originColor = input; - this.isGradient = false; - let colorInput = input; - if (gradientColors) { - this.isGradient = true; - const object = gradientColors; - const points = object.points.map((c) => genGradientPoint(c.left, c.color)); - this.gradientStates = { - colors: points, - degree: object.degree, - selectedId: ((_a = points[0]) === null || _a === void 0 ? void 0 : _a.id) || null, - }; - this.gradientStates.css = this.linearGradient; - colorInput = (_b = this.gradientSelectedPoint) === null || _b === void 0 ? void 0 : _b.color; - } - this.updateStates(colorInput); - } - get saturation() { - return this.states.s; - } - set saturation(value) { - this.states.s = Math.max(0, Math.min(100, value)); - this.updateCurrentGradientColor(); - } - get value() { - return this.states.v; - } - set value(value) { - this.states.v = Math.max(0, Math.min(100, value)); - this.updateCurrentGradientColor(); - } - get hue() { - return this.states.h; - } - set hue(value) { - this.states.h = Math.max(0, Math.min(360, value)); - this.updateCurrentGradientColor(); - } - get alpha() { - return this.states.a; - } - set alpha(value) { - this.states.a = Math.max(0, Math.min(1, Math.round(value * 100) / 100)); - this.updateCurrentGradientColor(); - } - get rgb() { - const { r, g, b } = hsv2rgba(this.states); - return `rgb(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)})`; - } - get rgba() { - const { r, g, b, a } = hsv2rgba(this.states); - return `rgba(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)}, ${a})`; - } - get hsv() { - const { h, s, v } = this.getHsva(); - return `hsv(${h}, ${s}%, ${v}%)`; - } - get hsva() { - const { h, s, v, a } = this.getHsva(); - return `hsva(${h}, ${s}%, ${v}%, ${a})`; - } - get hsl() { - const { h, s, l } = this.getHsla(); - return `hsl(${h}, ${s}%, ${l}%)`; - } - get hsla() { - const { h, s, l, a } = this.getHsla(); - return `hsla(${h}, ${s}%, ${l}%, ${a})`; - } - get hex() { - return tinyColor(this.states).toHexString(); - } - get hex8() { - return tinyColor(this.states).toHex8String(); - } - get cmyk() { - const { c, m, y, k } = this.getCmyk(); - return `cmyk(${c}, ${m}, ${y}, ${k})`; - } - get css() { - if (this.isGradient) { - return this.linearGradient; - } - return this.rgba; - } - get linearGradient() { - const { gradientColors, gradientDegree } = this; - return gradientColors2string({ - points: gradientColors, - degree: gradientDegree, - }); - } - get gradientColors() { - return this.gradientStates.colors; - } - set gradientColors(colors) { - this.gradientStates.colors = colors; - this.gradientStates.css = this.linearGradient; - } - get gradientSelectedId() { - return this.gradientStates.selectedId; - } - set gradientSelectedId(id) { - var _a; - if (id === this.gradientSelectedId) { - return; - } - this.gradientStates.selectedId = id; - this.updateStates((_a = this.gradientSelectedPoint) === null || _a === void 0 ? void 0 : _a.color); - } - get gradientDegree() { - return this.gradientStates.degree; - } - set gradientDegree(degree) { - this.gradientStates.degree = Math.max(0, Math.min(360, degree)); - this.gradientStates.css = this.linearGradient; - } - get gradientSelectedPoint() { - const { gradientColors, gradientSelectedId } = this; - return gradientColors.find((color) => color.id === gradientSelectedId); - } - getFormatsColorMap() { - return { - HEX: this.hex, - CMYK: this.cmyk, - RGB: this.rgb, - RGBA: this.rgba, - HSL: this.hsl, - HSLA: this.hsla, - HSV: this.hsv, - HSVA: this.hsva, - CSS: this.css, - HEX8: this.hex8, - }; - } - updateCurrentGradientColor() { - const { isGradient, gradientColors, gradientSelectedId } = this; - const { length } = gradientColors; - const current = this.gradientSelectedPoint; - if (!isGradient || length === 0 || !current) { - return false; - } - const index = gradientColors.findIndex((color) => color.id === gradientSelectedId); - const newColor = Object.assign(Object.assign({}, current), { color: this.rgba }); - gradientColors.splice(index, 1, newColor); - this.gradientColors = gradientColors.slice(); - return this; - } - updateStates(input) { - const color = tinyColor(cmykInputToColor(input)); - const hsva = color.toHsv(); - this.states = hsva; - } - getRgba() { - const { r, g, b, a } = hsv2rgba(this.states); - return { - r: mathRound(r), - g: mathRound(g), - b: mathRound(b), - a, - }; - } - getCmyk() { - const { r, g, b } = this.getRgba(); - const [c, m, y, k] = rgb2cmyk(r, g, b); - return { - c: mathRound(c * 100), - m: mathRound(m * 100), - y: mathRound(y * 100), - k: mathRound(k * 100), - }; - } - getHsva() { - let { h, s, v, a } = hsv2hsva(this.states); - h = mathRound(h); - s = mathRound(s * 100); - v = mathRound(v * 100); - a *= 1; - return { - h, - s, - v, - a, - }; - } - getHsla() { - let { h, s, l, a } = hsv2hsla(this.states); - h = mathRound(h); - s = mathRound(s * 100); - l = mathRound(l * 100); - a *= 1; - return { - h, - s, - l, - a, - }; - } - equals(color) { - return tinyColor.equals(this.rgba, color); - } - static isValid(color) { - if (parseGradientString(color)) { - return true; - } - return tinyColor(color).isValid(); - } - static hsva2color(h, s, v, a) { - return tinyColor({ - h, - s, - v, - a, - }).toHsvString(); - } - static hsla2color(h, s, l, a) { - return tinyColor({ - h, - s, - l, - a, - }).toHslString(); - } - static rgba2color(r, g, b, a) { - return tinyColor({ - r, - g, - b, - a, - }).toHsvString(); - } - static hex2color(hex, a) { - const color = tinyColor(hex); - color.setAlpha(a); - return color.toHexString(); - } - static object2color(object, format) { - if (format === 'CMYK') { - const { c, m, y, k } = object; - return `cmyk(${c}, ${m}, ${y}, ${k})`; - } - const color = tinyColor(object, { - format, - }); - return color.toRgbString(); - } + constructor(input) { + this.states = { + s: 100, + v: 100, + h: 100, + a: 1, + } + this.gradientStates = { + colors: [], + degree: 0, + selectedId: null, + css: '', + } + this.update(input) + } + + update(input) { + let _a; let + _b + const gradientColors = parseGradientString(input) + if (this.isGradient && !gradientColors) { + const colorHsv = tinyColor(input).toHsv() + this.states = colorHsv + this.updateCurrentGradientColor() + return + } + this.originColor = input + this.isGradient = false + let colorInput = input + if (gradientColors) { + this.isGradient = true + const object = gradientColors + const points = object.points.map((c) => genGradientPoint(c.left, c.color)) + this.gradientStates = { + colors: points, + degree: object.degree, + selectedId: ((_a = points[0]) === null || _a === void 0 ? void 0 : _a.id) || null, + } + this.gradientStates.css = this.linearGradient + colorInput = (_b = this.gradientSelectedPoint) === null || _b === void 0 ? void 0 : _b.color + } + this.updateStates(colorInput) + } + + get saturation() { + return this.states.s + } + + set saturation(value) { + this.states.s = Math.max(0, Math.min(100, value)) + this.updateCurrentGradientColor() + } + + get value() { + return this.states.v + } + + set value(value) { + this.states.v = Math.max(0, Math.min(100, value)) + this.updateCurrentGradientColor() + } + + get hue() { + return this.states.h + } + + set hue(value) { + this.states.h = Math.max(0, Math.min(360, value)) + this.updateCurrentGradientColor() + } + + get alpha() { + return this.states.a + } + + set alpha(value) { + this.states.a = Math.max(0, Math.min(1, Math.round(value * 100) / 100)) + this.updateCurrentGradientColor() + } + + get rgb() { + const {r, g, b} = hsv2rgba(this.states) + return `rgb(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)})` + } + + get rgba() { + const { + r, g, b, a + } = hsv2rgba(this.states) + return `rgba(${mathRound(r)}, ${mathRound(g)}, ${mathRound(b)}, ${a})` + } + + get hsv() { + const {h, s, v} = this.getHsva() + return `hsv(${h}, ${s}%, ${v}%)` + } + + get hsva() { + const { + h, s, v, a + } = this.getHsva() + return `hsva(${h}, ${s}%, ${v}%, ${a})` + } + + get hsl() { + const {h, s, l} = this.getHsla() + return `hsl(${h}, ${s}%, ${l}%)` + } + + get hsla() { + const { + h, s, l, a + } = this.getHsla() + return `hsla(${h}, ${s}%, ${l}%, ${a})` + } + + get hex() { + return tinyColor(this.states).toHexString() + } + + get hex8() { + return tinyColor(this.states).toHex8String() + } + + get cmyk() { + const { + c, m, y, k + } = this.getCmyk() + return `cmyk(${c}, ${m}, ${y}, ${k})` + } + + get css() { + if (this.isGradient) { + return this.linearGradient + } + return this.rgba + } + + get linearGradient() { + const {gradientColors, gradientDegree} = this + return gradientColors2string({ + points: gradientColors, + degree: gradientDegree, + }) + } + + get gradientColors() { + return this.gradientStates.colors + } + + set gradientColors(colors) { + this.gradientStates.colors = colors + this.gradientStates.css = this.linearGradient + } + + get gradientSelectedId() { + return this.gradientStates.selectedId + } + + set gradientSelectedId(id) { + let _a + if (id === this.gradientSelectedId) { + return + } + this.gradientStates.selectedId = id + this.updateStates((_a = this.gradientSelectedPoint) === null || _a === void 0 ? void 0 : _a.color) + } + + get gradientDegree() { + return this.gradientStates.degree + } + + set gradientDegree(degree) { + this.gradientStates.degree = Math.max(0, Math.min(360, degree)) + this.gradientStates.css = this.linearGradient + } + + get gradientSelectedPoint() { + const {gradientColors, gradientSelectedId} = this + return gradientColors.find((color) => color.id === gradientSelectedId) + } + + getFormatsColorMap() { + return { + HEX: this.hex, + CMYK: this.cmyk, + RGB: this.rgb, + RGBA: this.rgba, + HSL: this.hsl, + HSLA: this.hsla, + HSV: this.hsv, + HSVA: this.hsva, + CSS: this.css, + HEX8: this.hex8, + } + } + + updateCurrentGradientColor() { + const {isGradient, gradientColors, gradientSelectedId} = this + const {length} = gradientColors + const current = this.gradientSelectedPoint + if (!isGradient || length === 0 || !current) { + return false + } + const index = gradientColors.findIndex((color) => color.id === gradientSelectedId) + const newColor = {...current, color: this.rgba} + gradientColors.splice(index, 1, newColor) + this.gradientColors = gradientColors.slice() + return this + } + + updateStates(input) { + const color = tinyColor(cmykInputToColor(input)) + const hsva = color.toHsv() + this.states = hsva + } + + getRgba() { + const { + r, g, b, a + } = hsv2rgba(this.states) + return { + r: mathRound(r), + g: mathRound(g), + b: mathRound(b), + a, + } + } + + getCmyk() { + const {r, g, b} = this.getRgba() + const [c, m, y, k] = rgb2cmyk(r, g, b) + return { + c: mathRound(c * 100), + m: mathRound(m * 100), + y: mathRound(y * 100), + k: mathRound(k * 100), + } + } + + getHsva() { + let { + h, s, v, a + } = hsv2hsva(this.states) + h = mathRound(h) + s = mathRound(s * 100) + v = mathRound(v * 100) + a *= 1 + return { + h, + s, + v, + a, + } + } + + getHsla() { + let { + h, s, l, a + } = hsv2hsla(this.states) + h = mathRound(h) + s = mathRound(s * 100) + l = mathRound(l * 100) + a *= 1 + return { + h, + s, + l, + a, + } + } + + equals(color) { + return tinyColor.equals(this.rgba, color) + } + + static isValid(color) { + if (parseGradientString(color)) { + return true + } + return tinyColor(color).isValid() + } + + static hsva2color(h, s, v, a) { + return tinyColor({ + h, + s, + v, + a, + }).toHsvString() + } + + static hsla2color(h, s, l, a) { + return tinyColor({ + h, + s, + l, + a, + }).toHslString() + } + + static rgba2color(r, g, b, a) { + return tinyColor({ + r, + g, + b, + a, + }).toHsvString() + } + + static hex2color(hex, a) { + const color = tinyColor(hex) + color.setAlpha(a) + return color.toHexString() + } + + static object2color(object, format) { + if (format === 'CMYK') { + const { + c, m, y, k + } = object + return `cmyk(${c}, ${m}, ${y}, ${k})` + } + const color = tinyColor(object, { + format, + }) + return color.toRgbString() + } } -Color.isGradientColor = (input) => !!isGradientColor(input); +Color.isGradientColor = (input) => !!isGradientColor(input) Color.compare = (color1, color2) => { - const isGradientColor1 = Color.isGradientColor(color1); - const isGradientColor2 = Color.isGradientColor(color2); - if (isGradientColor1 && isGradientColor2) { - const gradientColor1 = gradientColors2string(parseGradientString(color1)); - const gradientColor2 = gradientColors2string(parseGradientString(color2)); - return gradientColor1 === gradientColor2; - } - if (!isGradientColor1 && !isGradientColor2) { - return tinyColor.equals(color1, color2); - } - return false; -}; + const isGradientColor1 = Color.isGradientColor(color1) + const isGradientColor2 = Color.isGradientColor(color2) + if (isGradientColor1 && isGradientColor2) { + const gradientColor1 = gradientColors2string(parseGradientString(color1)) + const gradientColor2 = gradientColors2string(parseGradientString(color2)) + return gradientColor1 === gradientColor2 + } + if (!isGradientColor1 && !isGradientColor2) { + return tinyColor.equals(color1, color2) + } + return false +} const COLOR_OBJECT_OUTPUT_KEYS = [ - 'alpha', - 'css', - 'hex', - 'hex8', - 'hsl', - 'hsla', - 'hsv', - 'hsva', - 'rgb', - 'rgba', - 'saturation', - 'value', - 'isGradient', -]; + 'alpha', + 'css', + 'hex', + 'hex8', + 'hsl', + 'hsla', + 'hsv', + 'hsva', + 'rgb', + 'rgba', + 'saturation', + 'value', + 'isGradient', +] export const getColorObject = (color) => { - if (!color) { - return null; - } - const colorObject = Object.create(null); - COLOR_OBJECT_OUTPUT_KEYS.forEach((key) => (colorObject[key] = color[key])); - if (color.isGradient) { - colorObject.linearGradient = color.linearGradient; - } - return colorObject; -}; -export default Color; + if (!color) { + return null + } + const colorObject = Object.create(null) + COLOR_OBJECT_OUTPUT_KEYS.forEach((key) => (colorObject[key] = color[key])) + if (color.isGradient) { + colorObject.linearGradient = color.linearGradient + } + return colorObject +} +export default Color diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/gradient.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/gradient.js index 18eacb20..4f364bd4 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/gradient.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/gradient.js @@ -1,119 +1,119 @@ -import isString from 'lodash/isString'; -import isNull from 'lodash/isNull'; -import tinyColor from 'tinycolor2'; +import isString from 'lodash/isString' +import isNull from 'lodash/isNull' +import tinyColor from 'tinycolor2' + const combineRegExp = (regexpList, flags) => { - let source = ''; - for (let i = 0; i < regexpList.length; i++) { - if (isString(regexpList[i])) { - source += regexpList[i]; - } - else { - source += regexpList[i].source; - } + let source = '' + for (let i = 0; i < regexpList.length; i++) { + if (isString(regexpList[i])) { + source += regexpList[i] + } else { + source += regexpList[i].source } - return new RegExp(source, flags); -}; + } + return new RegExp(source, flags) +} const generateRegExp = () => { - const searchFlags = 'gi'; - const rAngle = /(?:[+-]?\d*\.?\d+)(?:deg|grad|rad|turn)/; - const rSideCornerCapture = /to\s+((?:(?:left|right|top|bottom)(?:\s+(?:top|bottom|left|right))?))/; - const rComma = /\s*,\s*/; - const rColorHex = /#(?:[a-f0-9]{6}|[a-f0-9]{3})/; - const rDigits3 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*\)/; - const rDigits4 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*,\s*\d*\.?\d+\)/; - const rValue = /(?:[+-]?\d*\.?\d+)(?:%|[a-z]+)?/; - const rKeyword = /[_a-z-][_a-z0-9-]*/; - const rColor = combineRegExp(['(?:', rColorHex, '|', '(?:rgb|hsl)', rDigits3, '|', '(?:rgba|hsla)', rDigits4, '|', rKeyword, ')'], ''); - const rColorStop = combineRegExp([rColor, '(?:\\s+', rValue, '(?:\\s+', rValue, ')?)?'], ''); - const rColorStopList = combineRegExp(['(?:', rColorStop, rComma, ')*', rColorStop], ''); - const rLineCapture = combineRegExp(['(?:(', rAngle, ')|', rSideCornerCapture, ')'], ''); - const rGradientSearch = combineRegExp(['(?:(', rLineCapture, ')', rComma, ')?(', rColorStopList, ')'], searchFlags); - const rColorStopSearch = combineRegExp(['\\s*(', rColor, ')', '(?:\\s+', '(', rValue, '))?', '(?:', rComma, '\\s*)?'], searchFlags); - return { - gradientSearch: rGradientSearch, - colorStopSearch: rColorStopSearch, - }; -}; + const searchFlags = 'gi' + const rAngle = /(?:[+-]?\d*\.?\d+)(?:deg|grad|rad|turn)/ + const rSideCornerCapture = /to\s+((?:(?:left|right|top|bottom)(?:\s+(?:top|bottom|left|right))?))/ + const rComma = /\s*,\s*/ + const rColorHex = /#(?:[a-f0-9]{6}|[a-f0-9]{3})/ + const rDigits3 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*\)/ + const rDigits4 = /\(\s*(?:\d{1,3}\s*,\s*){2}\d{1,3}\s*,\s*\d*\.?\d+\)/ + const rValue = /(?:[+-]?\d*\.?\d+)(?:%|[a-z]+)?/ + const rKeyword = /[_a-z-][_a-z0-9-]*/ + const rColor = combineRegExp(['(?:', rColorHex, '|', '(?:rgb|hsl)', rDigits3, '|', '(?:rgba|hsla)', rDigits4, '|', rKeyword, ')'], '') + const rColorStop = combineRegExp([rColor, '(?:\\s+', rValue, '(?:\\s+', rValue, ')?)?'], '') + const rColorStopList = combineRegExp(['(?:', rColorStop, rComma, ')*', rColorStop], '') + const rLineCapture = combineRegExp(['(?:(', rAngle, ')|', rSideCornerCapture, ')'], '') + const rGradientSearch = combineRegExp(['(?:(', rLineCapture, ')', rComma, ')?(', rColorStopList, ')'], searchFlags) + const rColorStopSearch = combineRegExp(['\\s*(', rColor, ')', '(?:\\s+', '(', rValue, '))?', '(?:', rComma, '\\s*)?'], searchFlags) + return { + gradientSearch: rGradientSearch, + colorStopSearch: rColorStopSearch, + } +} const parseGradient = (regExpLib, input) => { - let result; - let matchColorStop; - let stopResult; - regExpLib.gradientSearch.lastIndex = 0; - const matchGradient = regExpLib.gradientSearch.exec(input); - if (!isNull(matchGradient)) { - result = { - original: matchGradient[0], - colorStopList: [], - }; - if (matchGradient[1]) { - result.line = matchGradient[1]; - } - if (matchGradient[2]) { - result.angle = matchGradient[2]; - } - if (matchGradient[3]) { - result.sideCorner = matchGradient[3]; - } - regExpLib.colorStopSearch.lastIndex = 0; - matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]); - while (!isNull(matchColorStop)) { - stopResult = { - color: matchColorStop[1], - }; - if (matchColorStop[2]) { - stopResult.position = matchColorStop[2]; - } - result.colorStopList.push(stopResult); - matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]); - } + let result + let matchColorStop + let stopResult + regExpLib.gradientSearch.lastIndex = 0 + const matchGradient = regExpLib.gradientSearch.exec(input) + if (!isNull(matchGradient)) { + result = { + original: matchGradient[0], + colorStopList: [], } - return result; -}; -const REGEXP_LIB = generateRegExp(); -const REG_GRADIENT = /.*gradient\s*\(((?:\([^)]*\)|[^)(]*)*)\)/gim; -export const isGradientColor = (input) => { - REG_GRADIENT.lastIndex = 0; - return REG_GRADIENT.exec(input); -}; -const sideCornerDegreeMap = { - top: 0, - right: 90, - bottom: 180, - left: 270, - 'top left': 225, - 'left top': 225, - 'top right': 135, - 'right top': 135, - 'bottom left': 315, - 'left bottom': 315, - 'bottom right': 45, - 'right bottom': 45, -}; -export const parseGradientString = (input) => { - const match = isGradientColor(input); - if (!match) { - return false; + if (matchGradient[1]) { + result.line = matchGradient[1] + } + if (matchGradient[2]) { + result.angle = matchGradient[2] } - const gradientColors = { - points: [], - degree: 0, - }; - const result = parseGradient(REGEXP_LIB, match[1]); - if (result.original.trim() !== match[1].trim()) { - return false; + if (matchGradient[3]) { + result.sideCorner = matchGradient[3] } - const points = result.colorStopList.map(({ color, position }) => { - const point = Object.create(null); - point.color = tinyColor(color).toRgbString(); - point.left = parseFloat(position); - return point; - }); - gradientColors.points = points; - let degree = parseInt(result.angle, 10); - if (Number.isNaN(degree)) { - degree = sideCornerDegreeMap[result.sideCorner] || 90; + regExpLib.colorStopSearch.lastIndex = 0 + matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]) + while (!isNull(matchColorStop)) { + stopResult = { + color: matchColorStop[1], + } + if (matchColorStop[2]) { + stopResult.position = matchColorStop[2] + } + result.colorStopList.push(stopResult) + matchColorStop = regExpLib.colorStopSearch.exec(matchGradient[4]) } - gradientColors.degree = degree; - return gradientColors; -}; -export default parseGradientString; + } + return result +} +const REGEXP_LIB = generateRegExp() +const REG_GRADIENT = /.*gradient\s*\(((?:\([^)]*\)|[^)(]*)*)\)/gim +export const isGradientColor = (input) => { + REG_GRADIENT.lastIndex = 0 + return REG_GRADIENT.exec(input) +} +const sideCornerDegreeMap = { + top: 0, + right: 90, + bottom: 180, + left: 270, + 'top left': 225, + 'left top': 225, + 'top right': 135, + 'right top': 135, + 'bottom left': 315, + 'left bottom': 315, + 'bottom right': 45, + 'right bottom': 45, +} +export const parseGradientString = (input) => { + const match = isGradientColor(input) + if (!match) { + return false + } + const gradientColors = { + points: [], + degree: 0, + } + const result = parseGradient(REGEXP_LIB, match[1]) + if (result.original.trim() !== match[1].trim()) { + return false + } + const points = result.colorStopList.map(({color, position}) => { + const point = Object.create(null) + point.color = tinyColor(color).toRgbString() + point.left = parseFloat(position) + return point + }) + gradientColors.points = points + let degree = parseInt(result.angle, 10) + if (Number.isNaN(degree)) { + degree = sideCornerDegreeMap[result.sideCorner] || 90 + } + gradientColors.degree = degree + return gradientColors +} +export default parseGradientString diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/index.js index ad18475c..1ed542a9 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/shared/color-picker/index.js @@ -1,3 +1,3 @@ -export * from './cmyk'; -export * from './color'; -export * from './gradient'; +export * from './cmyk' +export * from './color' +export * from './gradient' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/control.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/control.js index 03c9e772..4bb6ee12 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/control.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/control.js @@ -1,40 +1,39 @@ const defaultOption = { - valueKey: 'value', - defaultValueKey: 'defaultValue', - changeEventName: 'change', - strict: true, -}; + valueKey: 'value', + defaultValueKey: 'defaultValue', + changeEventName: 'change', + strict: true, +} function useControl(option = {}) { - const { valueKey, defaultValueKey, changeEventName, strict } = Object.assign(Object.assign({}, defaultOption), option); - const props = this.properties || {}; - const value = props[valueKey]; - const defaultValue = props[strict ? defaultValueKey : valueKey]; - let controlled = false; - if (strict && typeof value !== 'undefined' && value !== null) { - controlled = true; - } - const set = (newVal, extObj, fn) => { - this.setData(Object.assign({ [`_${valueKey}`]: newVal }, extObj), fn); - }; - return { - controlled, - initValue: controlled ? value : defaultValue, - set, - get: () => { - return this.data[`_${valueKey}`]; - }, - change: (newVal, customChangeData, customUpdateFn) => { - this.triggerEvent(changeEventName, typeof customChangeData !== 'undefined' ? customChangeData : newVal); - if (controlled) { - return; - } - if (typeof customUpdateFn === 'function') { - customUpdateFn(); - } - else { - set(newVal); - } - }, - }; + const { + valueKey, defaultValueKey, changeEventName, strict + } = {...defaultOption, ...option} + const props = this.properties || {} + const value = props[valueKey] + const defaultValue = props[strict ? defaultValueKey : valueKey] + let controlled = false + if (strict && typeof value !== 'undefined' && value !== null) { + controlled = true + } + const set = (newVal, extObj, fn) => { + this.setData({[`_${valueKey}`]: newVal, ...extObj}, fn) + } + return { + controlled, + initValue: controlled ? value : defaultValue, + set, + get: () => this.data[`_${valueKey}`], + change: (newVal, customChangeData, customUpdateFn) => { + this.triggerEvent(changeEventName, typeof customChangeData !== 'undefined' ? customChangeData : newVal) + if (controlled) { + return + } + if (typeof customUpdateFn === 'function') { + customUpdateFn() + } else { + set(newVal) + } + }, + } } -export { useControl }; +export {useControl} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/flatTool.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/flatTool.js index 045abd77..27ad2833 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/flatTool.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/flatTool.js @@ -1,57 +1,48 @@ export const getPrototypeOf = function (obj) { - return Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.__proto__; -}; + return Object.getPrototypeOf ? Object.getPrototypeOf(obj) : obj.__proto__ +} export const isObject = function isObject(something) { - const type = typeof something; - return something !== null && (type === 'function' || type === 'object'); -}; + const type = typeof something + return something !== null && (type === 'function' || type === 'object') +} export const iterateInheritedPrototype = function iterateInheritedPrototype(callback, fromCtor, toCtor, includeToCtor = true) { - let proto = fromCtor.prototype || fromCtor; - const toProto = toCtor.prototype || toCtor; - while (proto) { - if (!includeToCtor && proto === toProto) - break; - if (callback(proto) === false) - break; - if (proto === toProto) - break; - proto = getPrototypeOf(proto); - } -}; + let proto = fromCtor.prototype || fromCtor + const toProto = toCtor.prototype || toCtor + while (proto) { + if (!includeToCtor && proto === toProto) break + if (callback(proto) === false) break + if (proto === toProto) break + proto = getPrototypeOf(proto) + } +} export const toObject = function toObject(something, options = {}) { - const obj = {}; - if (!isObject(something)) - return obj; - const excludes = options.excludes || ['constructor']; - const { enumerable = true, configurable = 0, writable = 0 } = options; - const defaultDesc = {}; - if (enumerable !== 0) - defaultDesc.enumerable = enumerable; - if (configurable !== 0) - defaultDesc.configurable = configurable; - if (writable !== 0) - defaultDesc.writable = writable; - iterateInheritedPrototype((proto) => { - Object.getOwnPropertyNames(proto).forEach((key) => { - if (excludes.indexOf(key) >= 0) - return; - if (Object.prototype.hasOwnProperty.call(obj, key)) - return; - const desc = Object.getOwnPropertyDescriptor(proto, key); - const fnKeys = ['get', 'set', 'value']; - fnKeys.forEach((k) => { - if (typeof desc[k] === 'function') { - const oldFn = desc[k]; - desc[k] = function (...args) { - return oldFn.apply(Object.prototype.hasOwnProperty.call(options, 'bindTo') ? options.bindTo : this, args); - }; - } - }); - Object.defineProperty(obj, key, Object.assign(Object.assign({}, desc), defaultDesc)); - }); - }, something, options.till || Object, false); - return obj; -}; + const obj = {} + if (!isObject(something)) return obj + const excludes = options.excludes || ['constructor'] + const {enumerable = true, configurable = 0, writable = 0} = options + const defaultDesc = {} + if (enumerable !== 0) defaultDesc.enumerable = enumerable + if (configurable !== 0) defaultDesc.configurable = configurable + if (writable !== 0) defaultDesc.writable = writable + iterateInheritedPrototype((proto) => { + Object.getOwnPropertyNames(proto).forEach((key) => { + if (excludes.indexOf(key) >= 0) return + if (Object.prototype.hasOwnProperty.call(obj, key)) return + const desc = Object.getOwnPropertyDescriptor(proto, key) + const fnKeys = ['get', 'set', 'value'] + fnKeys.forEach((k) => { + if (typeof desc[k] === 'function') { + const oldFn = desc[k] + desc[k] = function (...args) { + return oldFn.apply(Object.prototype.hasOwnProperty.call(options, 'bindTo') ? options.bindTo : this, args) + } + } + }) + Object.defineProperty(obj, key, {...desc, ...defaultDesc}) + }) + }, something, options.till || Object, false) + return obj +} export const isPlainObject = function isPlainObject(something) { - return Object.prototype.toString.call(something) === '[object Object]'; -}; + return Object.prototype.toString.call(something) === '[object Object]' +} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/index.js index 94e7ce12..9b7ff8b8 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/index.js @@ -1,4 +1,4 @@ -export * from './superComponent'; -export * from './flatTool'; -export * from './instantiationDecorator'; -export * from './control'; +export * from './superComponent' +export * from './flatTool' +export * from './instantiationDecorator' +export * from './control' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/instantiationDecorator.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/instantiationDecorator.js index d9b15b72..eabf691a 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/instantiationDecorator.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/instantiationDecorator.js @@ -1,139 +1,133 @@ -import { isPlainObject, toObject } from './flatTool'; -import { canUseVirtualHost } from '../version'; -const RawLifeCycles = ['Created', 'Attached', 'Ready', 'Moved', 'Detached', 'Error']; -const NativeLifeCycles = RawLifeCycles.map((k) => k.toLowerCase()); +import {isPlainObject, toObject} from './flatTool' +import {canUseVirtualHost} from '../version' + +const RawLifeCycles = ['Created', 'Attached', 'Ready', 'Moved', 'Detached', 'Error'] +const NativeLifeCycles = RawLifeCycles.map((k) => k.toLowerCase()) const ComponentNativeProps = [ - 'properties', - 'data', - 'observers', - 'methods', - 'behaviors', - ...NativeLifeCycles, - 'relations', - 'externalClasses', - 'options', - 'lifetimes', - 'pageLifeTimes', - 'definitionFilter', -]; + 'properties', + 'data', + 'observers', + 'methods', + 'behaviors', + ...NativeLifeCycles, + 'relations', + 'externalClasses', + 'options', + 'lifetimes', + 'pageLifeTimes', + 'definitionFilter', +] export const toComponent = function toComponent(options) { - const { relations, behaviors = [], externalClasses = [] } = options; - if (options.properties) { - Object.keys(options.properties).forEach((k) => { - let opt = options.properties[k]; - if (!isPlainObject(opt)) { - opt = { type: opt }; - } - options.properties[k] = opt; - }); - const ariaProps = [ - { key: 'ariaHidden', type: Boolean }, - { key: 'ariaRole', type: String }, - { key: 'ariaLabel', type: String }, - { key: 'ariaLabelledby', type: String }, - { key: 'ariaDescribedby', type: String }, - { key: 'ariaBusy', type: Boolean }, - ]; - ariaProps.forEach(({ key, type }) => { - options.properties[key] = { - type, - }; - }); - options.properties.style = { type: String, value: '' }; - options.properties.customStyle = { type: String, value: '' }; + const {relations, behaviors = [], externalClasses = []} = options + if (options.properties) { + Object.keys(options.properties).forEach((k) => { + let opt = options.properties[k] + if (!isPlainObject(opt)) { + opt = {type: opt} + } + options.properties[k] = opt + }) + const ariaProps = [ + {key: 'ariaHidden', type: Boolean}, + {key: 'ariaRole', type: String}, + {key: 'ariaLabel', type: String}, + {key: 'ariaLabelledby', type: String}, + {key: 'ariaDescribedby', type: String}, + {key: 'ariaBusy', type: Boolean}, + ] + ariaProps.forEach(({key, type}) => { + options.properties[key] = { + type, + } + }) + options.properties.style = {type: String, value: ''} + options.properties.customStyle = {type: String, value: ''} + } + if (!options.methods) options.methods = {} + if (!options.lifetimes) options.lifetimes = {} + const inits = {} + if (relations) { + const getRelations = (relation, path) => Behavior({ + created() { + Object.defineProperty(this, `$${relation}`, { + get: () => { + const nodes = this.getRelationNodes(path) || [] + return relation === 'parent' ? nodes[0] : nodes + }, + }) + }, + }) + const map = {} + Object.keys(relations).forEach((path) => { + const comp = relations[path] + const relation = ['parent', 'ancestor'].includes(comp.type) ? 'parent' : 'children' + const mixin = getRelations(relation, path) + map[relation] = mixin + }) + behaviors.push(...Object.keys(map).map((key) => map[key])) + } + options.behaviors = [...behaviors] + options.externalClasses = ['class', ...externalClasses] + Object.getOwnPropertyNames(options).forEach((k) => { + const desc = Object.getOwnPropertyDescriptor(options, k) + if (!desc) return + if (NativeLifeCycles.indexOf(k) < 0 && typeof desc.value === 'function') { + Object.defineProperty(options.methods, k, desc) + delete options[k] + } else if (ComponentNativeProps.indexOf(k) < 0) { + inits[k] = desc + } else if (NativeLifeCycles.indexOf(k) >= 0) { + options.lifetimes[k] = options[k] } - if (!options.methods) - options.methods = {}; - if (!options.lifetimes) - options.lifetimes = {}; - const inits = {}; - if (relations) { - const getRelations = (relation, path) => Behavior({ - created() { - Object.defineProperty(this, `$${relation}`, { - get: () => { - const nodes = this.getRelationNodes(path) || []; - return relation === 'parent' ? nodes[0] : nodes; - }, - }); - }, - }); - const map = {}; - Object.keys(relations).forEach((path) => { - const comp = relations[path]; - const relation = ['parent', 'ancestor'].includes(comp.type) ? 'parent' : 'children'; - const mixin = getRelations(relation, path); - map[relation] = mixin; - }); - behaviors.push(...Object.keys(map).map((key) => map[key])); + }) + if (Object.keys(inits).length) { + const oldCreated = options.lifetimes.created + const oldAttached = options.lifetimes.attached + const {controlledProps = []} = options + options.lifetimes.created = function (...args) { + Object.defineProperties(this, inits) + if (oldCreated) oldCreated.apply(this, args) } - options.behaviors = [...behaviors]; - options.externalClasses = ['class', ...externalClasses]; - Object.getOwnPropertyNames(options).forEach((k) => { - const desc = Object.getOwnPropertyDescriptor(options, k); - if (!desc) - return; - if (NativeLifeCycles.indexOf(k) < 0 && typeof desc.value === 'function') { - Object.defineProperty(options.methods, k, desc); - delete options[k]; + options.lifetimes.attached = function (...args) { + if (oldAttached) oldAttached.apply(this, args) + controlledProps.forEach(({key}) => { + const defaultKey = `default${key.replace(/^(\w)/, (m, m1) => m1.toUpperCase())}` + const props = this.properties + if (props[key] == null) { + this._selfControlled = true } - else if (ComponentNativeProps.indexOf(k) < 0) { - inits[k] = desc; + if (props[key] == null && props[defaultKey] != null) { + this.setData({ + [key]: props[defaultKey], + }) } - else if (NativeLifeCycles.indexOf(k) >= 0) { - options.lifetimes[k] = options[k]; + }) + } + options.methods._trigger = function (evtName, detail, opts) { + const target = controlledProps.find((item) => item.event == evtName) + if (target) { + const {key} = target + if (this._selfControlled) { + this.setData({ + [key]: detail[key], + }) } - }); - if (Object.keys(inits).length) { - const oldCreated = options.lifetimes.created; - const oldAttached = options.lifetimes.attached; - const { controlledProps = [] } = options; - options.lifetimes.created = function (...args) { - Object.defineProperties(this, inits); - if (oldCreated) - oldCreated.apply(this, args); - }; - options.lifetimes.attached = function (...args) { - if (oldAttached) - oldAttached.apply(this, args); - controlledProps.forEach(({ key }) => { - const defaultKey = `default${key.replace(/^(\w)/, (m, m1) => m1.toUpperCase())}`; - const props = this.properties; - if (props[key] == null) { - this._selfControlled = true; - } - if (props[key] == null && props[defaultKey] != null) { - this.setData({ - [key]: props[defaultKey], - }); - } - }); - }; - options.methods._trigger = function (evtName, detail, opts) { - const target = controlledProps.find((item) => item.event == evtName); - if (target) { - const { key } = target; - if (this._selfControlled) { - this.setData({ - [key]: detail[key], - }); - } - } - this.triggerEvent(evtName, detail, opts); - }; + } + this.triggerEvent(evtName, detail, opts) } - return options; -}; + } + return options +} export const wxComponent = function wxComponent() { - return function (constructor) { - class WxComponent extends constructor { - } - const current = new WxComponent(); - current.options = current.options || {}; - if (canUseVirtualHost()) { - current.options.virtualHost = true; - } - const obj = toComponent(toObject(current)); - Component(obj); - }; -}; + return function (constructor) { + class WxComponent extends constructor { + } + const current = new WxComponent() + current.options = current.options || {} + if (canUseVirtualHost()) { + current.options.virtualHost = true + } + const obj = toComponent(toObject(current)) + Component(obj) + } +} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/superComponent.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/superComponent.js index 3cb17dc7..b4e78cb4 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/superComponent.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/src/superComponent.js @@ -1,5 +1,5 @@ export class SuperComponent { - constructor() { - this.app = getApp(); - } + constructor() { + this.app = getApp() + } } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/utils.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/utils.js index 2ae1bb53..82b573e2 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/utils.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/utils.js @@ -1,252 +1,241 @@ -import { prefix } from './config'; -import { getWindowInfo, getAppBaseInfo, getDeviceInfo } from './wechat'; -export const systemInfo = getWindowInfo(); -export const appBaseInfo = getAppBaseInfo(); -export const deviceInfo = getDeviceInfo(); +import {prefix} from './config' +import {getWindowInfo, getAppBaseInfo, getDeviceInfo} from './wechat' + +export const systemInfo = getWindowInfo() +export const appBaseInfo = getAppBaseInfo() +export const deviceInfo = getDeviceInfo() export const debounce = function (func, wait = 500) { - let timerId; - return function (...rest) { - if (timerId) { - clearTimeout(timerId); - } - timerId = setTimeout(() => { - func.apply(this, rest); - }, wait); - }; -}; + let timerId + return function (...rest) { + if (timerId) { + clearTimeout(timerId) + } + timerId = setTimeout(() => { + func.apply(this, rest) + }, wait) + } +} export const throttle = (func, wait = 100, options = null) => { - let previous = 0; - let timerid = null; - if (!options) { - options = { - leading: true, - }; + let previous = 0 + let timerid = null + if (!options) { + options = { + leading: true, } - return function (...args) { - const now = Date.now(); - if (!previous && !options.leading) - previous = now; - const remaining = wait - (now - previous); - const context = this; - if (remaining <= 0) { - if (timerid) { - clearTimeout(timerid); - timerid = null; - } - previous = now; - func.apply(context, args); - } - }; -}; + } + return function (...args) { + const now = Date.now() + if (!previous && !options.leading) previous = now + const remaining = wait - (now - previous) + const context = this + if (remaining <= 0) { + if (timerid) { + clearTimeout(timerid) + timerid = null + } + previous = now + func.apply(context, args) + } + } +} export const classNames = function (...args) { - const hasOwn = {}.hasOwnProperty; - const classes = []; - args.forEach((arg) => { - if (!arg) - return; - const argType = typeof arg; - if (argType === 'string' || argType === 'number') { - classes.push(arg); + const hasOwn = {}.hasOwnProperty + const classes = [] + args.forEach((arg) => { + if (!arg) return + const argType = typeof arg + if (argType === 'string' || argType === 'number') { + classes.push(arg) + } else if (Array.isArray(arg) && arg.length) { + const inner = classNames(...arg) + if (inner) { + classes.push(inner) + } + } else if (argType === 'object') { + for (const key in arg) { + if (hasOwn.call(arg, key) && arg[key]) { + classes.push(key) } - else if (Array.isArray(arg) && arg.length) { - const inner = classNames(...arg); - if (inner) { - classes.push(inner); - } - } - else if (argType === 'object') { - for (const key in arg) { - if (hasOwn.call(arg, key) && arg[key]) { - classes.push(key); - } - } - } - }); - return classes.join(' '); -}; + } + } + }) + return classes.join(' ') +} export const styles = function (styleObj) { - return Object.keys(styleObj) - .map((styleKey) => `${styleKey}: ${styleObj[styleKey]}`) - .join('; '); -}; + return Object.keys(styleObj) + .map((styleKey) => `${styleKey}: ${styleObj[styleKey]}`) + .join('; ') +} export const getAnimationFrame = function (context, cb) { - return context - .createSelectorQuery() - .selectViewport() - .boundingClientRect() - .exec(() => { - cb(); - }); -}; + return context + .createSelectorQuery() + .selectViewport() + .boundingClientRect() + .exec(() => { + cb() + }) +} export const getRect = function (context, selector, needAll = false) { - return new Promise((resolve, reject) => { - context - .createSelectorQuery()[needAll ? 'selectAll' : 'select'](selector) - .boundingClientRect((rect) => { - if (rect) { - resolve(rect); - } - else { - reject(rect); - } - }) - .exec(); - }); -}; + return new Promise((resolve, reject) => { + context + .createSelectorQuery()[needAll ? 'selectAll' : 'select'](selector) + .boundingClientRect((rect) => { + if (rect) { + resolve(rect) + } else { + reject(rect) + } + }) + .exec() + }) +} export const isNumber = function (value) { - return /^\d+(\.\d+)?$/.test(value); -}; + return /^\d+(\.\d+)?$/.test(value) +} export const isNull = function (value) { - return value === null; -}; -export const isUndefined = (value) => typeof value === 'undefined'; + return value === null +} +export const isUndefined = (value) => typeof value === 'undefined' export const isDef = function (value) { - return !isUndefined(value) && !isNull(value); -}; + return !isUndefined(value) && !isNull(value) +} export const isIOS = function () { - var _a; - return !!(((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.system) === null || _a === void 0 ? void 0 : _a.toLowerCase().search('ios')) + 1); -}; + let _a + return !!(((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.system) === null || _a === void 0 ? void 0 : _a.toLowerCase().search('ios')) + 1) +} export const addUnit = function (value) { - if (!isDef(value)) { - return undefined; - } - value = String(value); - return isNumber(value) ? `${value}px` : value; -}; + if (!isDef(value)) { + return undefined + } + value = String(value) + return isNumber(value) ? `${value}px` : value +} export const getCharacterLength = (type, char, max) => { - const str = String(char !== null && char !== void 0 ? char : ''); - if (str.length === 0) { - return { - length: 0, - characters: '', - }; - } - if (type === 'maxcharacter') { - let len = 0; - for (let i = 0; i < str.length; i += 1) { - let currentStringLength = 0; - if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) { - currentStringLength = 2; - } - else { - currentStringLength = 1; - } - if (len + currentStringLength > max) { - return { - length: len, - characters: str.slice(0, i), - }; - } - len += currentStringLength; - } - return { - length: len, - characters: str, - }; + const str = String(char !== null && char !== void 0 ? char : '') + if (str.length === 0) { + return { + length: 0, + characters: '', } - else if (type === 'maxlength') { - const length = str.length > max ? max : str.length; + } + if (type === 'maxcharacter') { + let len = 0 + for (let i = 0; i < str.length; i += 1) { + let currentStringLength = 0 + if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) { + currentStringLength = 2 + } else { + currentStringLength = 1 + } + if (len + currentStringLength > max) { return { - length, - characters: str.slice(0, length), - }; + length: len, + characters: str.slice(0, i), + } + } + len += currentStringLength } return { - length: str.length, - characters: str, - }; -}; -export const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size)); -export const getInstance = function (context, selector) { - if (!context) { - const pages = getCurrentPages(); - const page = pages[pages.length - 1]; - context = page.$$basePage || page; + length: len, + characters: str, } - const instance = context ? context.selectComponent(selector) : null; - if (!instance) { - console.warn('未找到组件,请检查selector是否正确'); - return null; + } else if (type === 'maxlength') { + const length = str.length > max ? max : str.length + return { + length, + characters: str.slice(0, length), } - return instance; -}; + } + return { + length: str.length, + characters: str, + } +} +export const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)) +export const getInstance = function (context, selector) { + if (!context) { + const pages = getCurrentPages() + const page = pages[pages.length - 1] + context = page.$$basePage || page + } + const instance = context ? context.selectComponent(selector) : null + if (!instance) { + console.warn('未找到组件,请检查selector是否正确') + return null + } + return instance +} export const unitConvert = (value) => { - var _a; - if (typeof value === 'string') { - if (value.includes('rpx')) { - return (parseInt(value, 10) * ((_a = systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.screenWidth) !== null && _a !== void 0 ? _a : 750)) / 750; - } - return parseInt(value, 10); + let _a + if (typeof value === 'string') { + if (value.includes('rpx')) { + return (parseInt(value, 10) * ((_a = systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.screenWidth) !== null && _a !== void 0 ? _a : 750)) / 750 } - return value !== null && value !== void 0 ? value : 0; -}; + return parseInt(value, 10) + } + return value !== null && value !== void 0 ? value : 0 +} export const setIcon = (iconName, icon, defaultIcon) => { - if (icon) { - if (typeof icon === 'string') { - return { - [`${iconName}Name`]: icon, - [`${iconName}Data`]: {}, - }; - } - else if (typeof icon === 'object') { - return { - [`${iconName}Name`]: '', - [`${iconName}Data`]: icon, - }; - } - else { - return { - [`${iconName}Name`]: defaultIcon, - [`${iconName}Data`]: {}, - }; - } - } - return { + if (icon) { + if (typeof icon === 'string') { + return { + [`${iconName}Name`]: icon, + [`${iconName}Data`]: {}, + } + } else if (typeof icon === 'object') { + return { [`${iconName}Name`]: '', + [`${iconName}Data`]: icon, + } + } else { + return { + [`${iconName}Name`]: defaultIcon, [`${iconName}Data`]: {}, - }; -}; -export const isBool = (val) => typeof val === 'boolean'; -export const isObject = (val) => typeof val === 'object' && val != null; -export const isString = (val) => typeof val === 'string'; -export const toCamel = (str) => str.replace(/-(\w)/g, (match, m1) => m1.toUpperCase()); + } + } + } + return { + [`${iconName}Name`]: '', + [`${iconName}Data`]: {}, + } +} +export const isBool = (val) => typeof val === 'boolean' +export const isObject = (val) => typeof val === 'object' && val != null +export const isString = (val) => typeof val === 'string' +export const toCamel = (str) => str.replace(/-(\w)/g, (match, m1) => m1.toUpperCase()) export const getCurrentPage = function () { - const pages = getCurrentPages(); - return pages[pages.length - 1]; -}; + const pages = getCurrentPages() + return pages[pages.length - 1] +} export const uniqueFactory = (compName) => { - let number = 0; - return () => `${prefix}_${compName}_${number++}`; -}; + let number = 0 + return () => `${prefix}_${compName}_${number++}` +} export const calcIcon = (icon, defaultIcon) => { - if (icon && ((isBool(icon) && defaultIcon) || isString(icon))) { - return { name: isBool(icon) ? defaultIcon : icon }; - } - if (isObject(icon)) { - return icon; - } - return null; -}; + if (icon && ((isBool(icon) && defaultIcon) || isString(icon))) { + return {name: isBool(icon) ? defaultIcon : icon} + } + if (isObject(icon)) { + return icon + } + return null +} export const isOverSize = (size, sizeLimit) => { - var _a; - if (!sizeLimit) - return false; - const base = 1000; - const unitMap = { - B: 1, - KB: base, - MB: base * base, - GB: base * base * base, - }; - const computedSize = typeof sizeLimit === 'number' ? sizeLimit * base : (sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size) * unitMap[(_a = sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.unit) !== null && _a !== void 0 ? _a : 'KB']; - return size > computedSize; -}; -export const rpx2px = (rpx) => Math.floor((systemInfo.windowWidth * rpx) / 750); -export const nextTick = () => { - return new Promise((resolve) => { - wx.nextTick(() => { - resolve(); - }); - }); -}; + let _a + if (!sizeLimit) return false + const base = 1000 + const unitMap = { + B: 1, + KB: base, + MB: base * base, + GB: base * base * base, + } + const computedSize = typeof sizeLimit === 'number' ? sizeLimit * base : (sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size) * unitMap[(_a = sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.unit) !== null && _a !== void 0 ? _a : 'KB'] + return size > computedSize +} +export const rpx2px = (rpx) => Math.floor((systemInfo.windowWidth * rpx) / 750) +export const nextTick = () => new Promise((resolve) => { + wx.nextTick(() => { + resolve() + }) +}) diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/version.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/version.js index 86a45218..9b8630a1 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/version.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/version.js @@ -1,43 +1,43 @@ -import { getAppBaseInfo } from './wechat'; -let systemInfo; +import {getAppBaseInfo} from './wechat' + +let systemInfo function getSystemInfo() { - if (systemInfo == null) { - systemInfo = getAppBaseInfo(); - } - return systemInfo; + if (systemInfo == null) { + systemInfo = getAppBaseInfo() + } + return systemInfo } export function compareVersion(v1, v2) { - v1 = v1.split('.'); - v2 = v2.split('.'); - const len = Math.max(v1.length, v2.length); - while (v1.length < len) { - v1.push('0'); - } - while (v2.length < len) { - v2.push('0'); - } - for (let i = 0; i < len; i++) { - const num1 = parseInt(v1[i]); - const num2 = parseInt(v2[i]); - if (num1 > num2) { - return 1; - } - else if (num1 < num2) { - return -1; - } + v1 = v1.split('.') + v2 = v2.split('.') + const len = Math.max(v1.length, v2.length) + while (v1.length < len) { + v1.push('0') + } + while (v2.length < len) { + v2.push('0') + } + for (let i = 0; i < len; i++) { + const num1 = parseInt(v1[i]) + const num2 = parseInt(v2[i]) + if (num1 > num2) { + return 1 + } else if (num1 < num2) { + return -1 } - return 0; + } + return 0 } function judgeByVersion(version) { - const currentSDKVersion = getSystemInfo().SDKVersion; - return compareVersion(currentSDKVersion, version) >= 0; + const currentSDKVersion = getSystemInfo().SDKVersion + return compareVersion(currentSDKVersion, version) >= 0 } export function canIUseFormFieldButton() { - return judgeByVersion('2.10.3'); + return judgeByVersion('2.10.3') } export function canUseVirtualHost() { - return judgeByVersion('2.19.2'); + return judgeByVersion('2.19.2') } export function canUseProxyScrollView() { - return judgeByVersion('2.19.2'); + return judgeByVersion('2.19.2') } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/wechat.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/wechat.js index c776abf2..ab4e3d5e 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/common/wechat.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/common/wechat.js @@ -1,19 +1,11 @@ -export const getObserver = (context, selector) => { - return new Promise((resolve, reject) => { - context - .createIntersectionObserver(context) - .relativeToViewport() - .observe(selector, (res) => { - resolve(res); - }); - }); -}; -export const getWindowInfo = () => { - return wx.getWindowInfo ? wx.getWindowInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync(); -}; -export const getAppBaseInfo = () => { - return wx.getAppBaseInfo ? wx.getAppBaseInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync(); -}; -export const getDeviceInfo = () => { - return wx.getDeviceInfo ? wx.getDeviceInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync(); -}; +export const getObserver = (context, selector) => new Promise((resolve, reject) => { + context + .createIntersectionObserver(context) + .relativeToViewport() + .observe(selector, (res) => { + resolve(res) + }) +}) +export const getWindowInfo = () => (wx.getWindowInfo ? wx.getWindowInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync()) +export const getAppBaseInfo = () => (wx.getAppBaseInfo ? wx.getAppBaseInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync()) +export const getDeviceInfo = () => (wx.getDeviceInfo ? wx.getDeviceInfo() || wx.getSystemInfoSync() : wx.getSystemInfoSync()) diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/divider.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/divider.js index 7e3247de..d00ec6c3 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/divider.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/divider.js @@ -1,43 +1,46 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-divider`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-divider` let Divider = class Divider extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`]; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.observers = { - lineColor() { - this.setStyle(); - }, - }; - this.methods = { - setStyle() { - const { lineColor } = this.properties; - const dividerStyle = `${lineColor ? `border-color: ${lineColor};` : ''}`; - this.setData({ - dividerStyle, - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`] + this.options = { + multipleSlots: true, } -}; + this.properties = props + this.data = { + prefix, + classPrefix: name, + } + this.observers = { + lineColor() { + this.setStyle() + }, + } + this.methods = { + setStyle() { + const {lineColor} = this.properties + const dividerStyle = `${lineColor ? `border-color: ${lineColor};` : ''}` + this.setData({ + dividerStyle, + }) + }, + } + } +} Divider = __decorate([ - wxComponent() -], Divider); -export default Divider; + wxComponent() +], Divider) +export default Divider diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/props.js index 395a3aa3..987ecd24 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/props.js @@ -1,18 +1,18 @@ const props = { - align: { - type: String, - value: 'center', - }, - content: { - type: String, - }, - dashed: { - type: Boolean, - value: false, - }, - layout: { - type: String, - value: 'horizontal', - }, -}; -export default props; + align: { + type: String, + value: 'center', + }, + content: { + type: String, + }, + dashed: { + type: Boolean, + value: false, + }, + layout: { + type: String, + value: 'horizontal', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/divider/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/empty.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/empty.js index 7d99bf99..28fc4246 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/empty.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/empty.js @@ -1,36 +1,39 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import props from './props'; -import config from '../common/config'; -import { setIcon } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-empty`; +import {SuperComponent, wxComponent} from '../common/src/index' +import props from './props' +import config from '../common/config' +import {setIcon} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-empty` let default_1 = class extends SuperComponent { - constructor() { - super(...arguments); - this.options = { - multipleSlots: true, - }; - this.externalClasses = [`${prefix}-class`, `${prefix}-class-description`, `${prefix}-class-image`]; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - }; - this.observers = { - icon(icon) { - const obj = setIcon('icon', icon, ''); - this.setData(Object.assign({}, obj)); - }, - }; + constructor() { + super(...arguments) + this.options = { + multipleSlots: true, } -}; + this.externalClasses = [`${prefix}-class`, `${prefix}-class-description`, `${prefix}-class-image`] + this.properties = props + this.data = { + prefix, + classPrefix: name, + } + this.observers = { + icon(icon) { + const obj = setIcon('icon', icon, '') + this.setData({...obj}) + }, + } + } +} default_1 = __decorate([ - wxComponent() -], default_1); -export default default_1; + wxComponent() +], default_1) +export default default_1 diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/props.js index aa55217b..f4952d4b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/props.js @@ -1,15 +1,15 @@ const props = { - description: { - type: String, - }, - externalClasses: { - type: Array, - }, - icon: { - type: null, - }, - image: { - type: String, - }, -}; -export default props; + description: { + type: String, + }, + externalClasses: { + type: Array, + }, + icon: { + type: null, + }, + image: { + type: String, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/empty/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/icon.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/icon.js index 797cae00..635aba91 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/icon.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/icon.js @@ -1,71 +1,76 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { styles, addUnit, getRect } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-icon`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {styles, addUnit, getRect} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } + function rejected(value) { try { step(generator.throw(value)) } catch (e) { reject(e) } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } + step((generator = generator.apply(thisArg, _arguments || [])).next()) + }) +} + +const {prefix} = config +const name = `${prefix}-icon` let Icon = class Icon extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.properties = props; - this.data = { - componentPrefix: prefix, - classPrefix: name, - isImage: false, - iconStyle: undefined, - }; - this.observers = { - 'name, color, size, style'() { - this.setIconStyle(); - }, - }; - this.methods = { - onTap(event) { - this.triggerEvent('click', event.detail); - }, - setIconStyle() { - const { name, color, size, classPrefix } = this.data; - const isImage = name.indexOf('/') !== -1; - const sizeValue = addUnit(size); - const colorStyle = color ? { color: color } : {}; - const fontStyle = size ? { 'font-size': sizeValue } : {}; - const iconStyle = Object.assign(Object.assign({}, colorStyle), fontStyle); - this.setData({ isImage }, () => __awaiter(this, void 0, void 0, function* () { - if (isImage) { - let iconSize = sizeValue; - if (!iconSize) { - yield getRect(this, `.${classPrefix}`) - .then((res) => { - iconSize = addUnit(res === null || res === void 0 ? void 0 : res.height); - }) - .catch(() => { }); - } - iconStyle.width = iconSize; - iconStyle.height = iconSize; - } - this.setData({ iconStyle: `${styles(iconStyle)}` }); - })); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.properties = props + this.data = { + componentPrefix: prefix, + classPrefix: name, + isImage: false, + iconStyle: undefined, } -}; + this.observers = { + 'name, color, size, style': function () { + this.setIconStyle() + }, + } + this.methods = { + onTap(event) { + this.triggerEvent('click', event.detail) + }, + setIconStyle() { + const { + name, color, size, classPrefix + } = this.data + const isImage = name.indexOf('/') !== -1 + const sizeValue = addUnit(size) + const colorStyle = color ? {color} : {} + const fontStyle = size ? {'font-size': sizeValue} : {} + const iconStyle = {...colorStyle, ...fontStyle} + this.setData({isImage}, () => __awaiter(this, void 0, void 0, function* () { + if (isImage) { + let iconSize = sizeValue + if (!iconSize) { + yield getRect(this, `.${classPrefix}`) + .then((res) => { + iconSize = addUnit(res === null || res === void 0 ? void 0 : res.height) + }) + .catch(() => { }) + } + iconStyle.width = iconSize + iconStyle.height = iconSize + } + this.setData({iconStyle: `${styles(iconStyle)}`}) + })) + }, + } + } +} Icon = __decorate([ - wxComponent() -], Icon); -export default Icon; + wxComponent() +], Icon) +export default Icon diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/props.js index 4d0ffa25..a7ebfa6a 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/props.js @@ -1,19 +1,19 @@ const props = { - color: { - type: String, - value: '', - }, - name: { - type: String, - value: '', - required: true, - }, - prefix: { - type: String, - value: '', - }, - size: { - type: null, - }, -}; -export default props; + color: { + type: String, + value: '', + }, + name: { + type: String, + value: '', + required: true, + }, + prefix: { + type: String, + value: '', + }, + size: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/icon/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/image.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/image.js index 61cf6fd2..e9248258 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/image.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/image.js @@ -1,97 +1,98 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import ImageProps from './props'; -import config from '../common/config'; -import { addUnit, getRect, appBaseInfo } from '../common/utils'; -import { compareVersion } from '../common/version'; -const { prefix } = config; -const name = `${prefix}-image`; +import {SuperComponent, wxComponent} from '../common/src/index' +import ImageProps from './props' +import config from '../common/config' +import {addUnit, getRect, appBaseInfo} from '../common/utils' +import {compareVersion} from '../common/version' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-image` let Image = class Image extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-load`, `${prefix}-class-image`, `${prefix}-class-error`]; - this.options = { - multipleSlots: true, - }; - this.properties = ImageProps; - this.data = { - prefix, + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-load`, `${prefix}-class-image`, `${prefix}-class-error`] + this.options = { + multipleSlots: true, + } + this.properties = ImageProps + this.data = { + prefix, + isLoading: true, + isFailed: false, + innerStyle: '', + classPrefix: name, + } + this.preSrc = undefined + this.observers = { + src() { + if (this.preSrc === this.properties.src) return + this.update() + }, + 'width, height': function (width, height) { + this.calcSize(width, height) + }, + } + this.methods = { + onLoaded(e) { + const sdkVersion = appBaseInfo.SDKVersion + const {mode, tId} = this.properties + const isInCompatible = compareVersion(sdkVersion, '2.10.3') < 0 + if (mode === 'heightFix' && isInCompatible) { + const {height: picHeight, width: picWidth} = e.detail + getRect(this, `#${tId || 'image'}`).then((rect) => { + const {height} = rect + const resultWidth = ((height / picHeight) * picWidth).toFixed(2) + this.setData({innerStyle: `height: ${addUnit(height)}; width: ${resultWidth}px;`}) + }) + } + this.setData({ + isLoading: false, + isFailed: false, + }) + this.triggerEvent('load', e.detail) + }, + onLoadError(e) { + this.setData({ + isLoading: false, + isFailed: true, + }) + this.triggerEvent('error', e.detail) + }, + calcSize(width, height) { + let innerStyle = '' + if (width) { + innerStyle += `width: ${addUnit(width)};` + } + if (height) { + innerStyle += `height: ${addUnit(height)};` + } + this.setData({ + innerStyle, + }) + }, + update() { + const {src} = this.properties + this.preSrc = src + if (!src) { + this.onLoadError({errMsg: '图片链接为空'}) + } else { + this.setData({ isLoading: true, isFailed: false, - innerStyle: '', - classPrefix: name, - }; - this.preSrc = undefined; - this.observers = { - src() { - if (this.preSrc === this.properties.src) - return; - this.update(); - }, - 'width, height'(width, height) { - this.calcSize(width, height); - }, - }; - this.methods = { - onLoaded(e) { - const sdkVersion = appBaseInfo.SDKVersion; - const { mode, tId } = this.properties; - const isInCompatible = compareVersion(sdkVersion, '2.10.3') < 0; - if (mode === 'heightFix' && isInCompatible) { - const { height: picHeight, width: picWidth } = e.detail; - getRect(this, `#${tId || 'image'}`).then((rect) => { - const { height } = rect; - const resultWidth = ((height / picHeight) * picWidth).toFixed(2); - this.setData({ innerStyle: `height: ${addUnit(height)}; width: ${resultWidth}px;` }); - }); - } - this.setData({ - isLoading: false, - isFailed: false, - }); - this.triggerEvent('load', e.detail); - }, - onLoadError(e) { - this.setData({ - isLoading: false, - isFailed: true, - }); - this.triggerEvent('error', e.detail); - }, - calcSize(width, height) { - let innerStyle = ''; - if (width) { - innerStyle += `width: ${addUnit(width)};`; - } - if (height) { - innerStyle += `height: ${addUnit(height)};`; - } - this.setData({ - innerStyle, - }); - }, - update() { - const { src } = this.properties; - this.preSrc = src; - if (!src) { - this.onLoadError({ errMsg: '图片链接为空' }); - } - else { - this.setData({ - isLoading: true, - isFailed: false, - }); - } - }, - }; + }) + } + }, } -}; + } +} Image = __decorate([ - wxComponent() -], Image); -export default Image; + wxComponent() +], Image) +export default Image diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/index.js index 4fd39538..1f3ee0de 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/index.js @@ -1,2 +1,2 @@ -export * from './props'; -export * from './image'; +export * from './props' +export * from './image' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/props.js index b2a17dac..5c2b5ae1 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/props.js @@ -1,45 +1,45 @@ const props = { - error: { - type: String, - value: 'default', - }, - height: { - type: null, - }, - lazy: { - type: Boolean, - value: false, - }, - loading: { - type: String, - value: 'default', - }, - mode: { - type: String, - value: 'scaleToFill', - }, - shape: { - type: String, - value: 'square', - }, - showMenuByLongpress: { - type: Boolean, - value: false, - }, - src: { - type: String, - value: '', - }, - tId: { - type: String, - value: '', - }, - webp: { - type: Boolean, - value: false, - }, - width: { - type: null, - }, -}; -export default props; + error: { + type: String, + value: 'default', + }, + height: { + type: null, + }, + lazy: { + type: Boolean, + value: false, + }, + loading: { + type: String, + value: 'default', + }, + mode: { + type: String, + value: 'scaleToFill', + }, + shape: { + type: String, + value: 'square', + }, + showMenuByLongpress: { + type: Boolean, + value: false, + }, + src: { + type: String, + value: '', + }, + tId: { + type: String, + value: '', + }, + webp: { + type: Boolean, + value: false, + }, + width: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/image/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/image/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/index.js index 9af8cc5b..8bf2eb23 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/index.js @@ -1,4 +1,4 @@ -export { default as ActionSheet, ActionSheetTheme } from './action-sheet/index'; -export { default as Dialog } from './dialog/index'; -export { default as Message } from './message/index'; -export { default as Toast } from './toast/index'; +export {default as ActionSheet, ActionSheetTheme} from './action-sheet/index' +export {default as Dialog} from './dialog/index' +export {default as Message} from './message/index' +export {default as Toast} from './toast/index' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/indexes.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/indexes.js index aad4eeb2..ef6830cc 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/indexes.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/indexes.js @@ -1,236 +1,232 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { getRect, throttle, systemInfo } from '../common/utils'; -import pageScrollMixin from '../mixins/page-scroll'; -const { prefix } = config; -const name = `${prefix}-indexes`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {getRect, throttle, systemInfo} from '../common/utils' +import pageScrollMixin from '../mixins/page-scroll' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-indexes` let Indexes = class Indexes extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-sidebar`, `${prefix}-class-sidebar-item`]; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - _height: 0, - _indexList: [], - scrollTop: 0, - activeAnchor: null, - showTips: false, - }; - this.relations = { - '../indexes-anchor/indexes-anchor': { - type: 'child', - }, - }; - this.behaviors = [pageScrollMixin()]; - this.timer = null; - this.groupTop = []; - this.sidebar = null; - this.currentTouchAnchor = null; - this.observers = { - indexList(v) { - this.setIndexList(v); - this.setHeight(this.data._height); - }, - height(v) { - this.setHeight(v); - }, - }; - this.lifetimes = { - ready() { - this.timer = null; - this.groupTop = []; - this.sidebar = null; - if (this.data._height === 0) { - this.setHeight(); - } - if (this.data.indexList === null) { - this.setIndexList(); - } - }, - }; - this.methods = { - setHeight(height) { - if (!height) { - const { windowHeight } = systemInfo; - height = windowHeight; - } - this.setData({ - _height: height, - }, () => { - this.getAllRect(); - }); - }, - setIndexList(list) { - if (!list) { - const start = 'A'.charCodeAt(0); - const alphabet = []; - for (let i = start, end = start + 26; i < end; i += 1) { - alphabet.push(String.fromCharCode(i)); - } - this.setData({ _indexList: alphabet }); - } - else { - this.setData({ _indexList: list }); - } - }, - getAllRect() { - this.getAnchorsRect().then(() => { - this.groupTop.forEach((item, index) => { - const next = this.groupTop[index + 1]; - item.totalHeight = ((next === null || next === void 0 ? void 0 : next.top) || Infinity) - item.top; - }); - this.setAnchorOnScroll(0); - }); - this.getSidebarRect(); - }, - getAnchorsRect() { - return Promise.all(this.$children.map((child) => getRect(child, `.${name}-anchor`).then((rect) => { - this.groupTop.push({ - height: rect.height, - top: rect.top, - anchor: child.data.index, - }); - }))); - }, - getSidebarRect() { - getRect(this, `#id-${name}__bar`).then((rect) => { - const { top, height } = rect; - const { length } = this.data._indexList; - this.sidebar = { - top, - height, - itemHeight: (height - (length - 1) * 2) / length, - }; - }); - }, - toggleTips(flag) { - if (!flag) { - clearInterval(this.timer); - this.timer = setTimeout(() => { - this.setData({ - showTips: false, - }); - }, 300); - } - else { - this.setData({ - showTips: true, - }); - } - }, - setAnchorByIndex(index) { - const { _indexList, stickyOffset } = this.data; - const activeAnchor = _indexList[index]; - if (this.data.activeAnchor !== null && this.data.activeAnchor === activeAnchor) - return; - const target = this.groupTop.find((item) => item.anchor === activeAnchor); - if (target) { - this.currentTouchAnchor = activeAnchor; - const scrollTop = target.top - stickyOffset; - wx.pageScrollTo({ - scrollTop, - duration: 0, - }); - this.toggleTips(true); - this.triggerEvent('select', { index: activeAnchor }); - this.setData({ activeAnchor }); - } - }, - onClick(e) { - const { index } = e.currentTarget.dataset; - this.setAnchorByIndex(index); - }, - onTouchMove(e) { - this.onAnchorTouch(e); - }, - onTouchCancel() { - this.toggleTips(false); - }, - onTouchEnd(e) { - this.toggleTips(false); - this.onAnchorTouch(e); - }, - onAnchorTouch: throttle(function (e) { - const getAnchorIndex = (clientY) => { - const offsetY = clientY - this.sidebar.top; - if (offsetY <= 0) { - return 0; - } - if (offsetY > this.sidebar.height) { - return this.data._indexList.length - 1; - } - return Math.floor(offsetY / this.sidebar.itemHeight); - }; - const index = getAnchorIndex(e.changedTouches[0].clientY); - this.setAnchorByIndex(index); - }, 1000 / 30), - setAnchorOnScroll(scrollTop) { - if (!this.groupTop) { - return; - } - const { sticky, stickyOffset, activeAnchor } = this.data; - scrollTop += stickyOffset; - const curIndex = this.groupTop.findIndex((group) => scrollTop >= group.top - group.height && scrollTop <= group.top + group.totalHeight - group.height); - if (curIndex === -1) - return; - const curGroup = this.groupTop[curIndex]; - if (this.currentTouchAnchor !== null) { - this.triggerEvent('change', { index: curGroup.anchor }); - this.currentTouchAnchor = null; - } - else if (activeAnchor !== curGroup.anchor) { - this.triggerEvent('change', { index: curGroup.anchor }); - this.setData({ activeAnchor: curGroup.anchor }); - } - if (sticky) { - const offset = curGroup.top - scrollTop; - const betwixt = offset < curGroup.height && offset > 0 && scrollTop > stickyOffset; - this.$children.forEach((child, index) => { - if (index === curIndex) { - const sticky = scrollTop > stickyOffset; - const anchorStyle = `transform: translate3d(0, ${betwixt ? offset : 0}px, 0); top: ${stickyOffset}px`; - if (anchorStyle !== child.data.anchorStyle || sticky !== child.data.sticky) { - child.setData({ - sticky, - active: true, - style: `height: ${curGroup.height}px`, - anchorStyle, - }); - } - } - else if (index + 1 === curIndex) { - const anchorStyle = `transform: translate3d(0, ${betwixt ? offset - curGroup.height : 0}px, 0); top: ${stickyOffset}px`; - if (anchorStyle !== child.data.anchorStyle) { - child.setData({ - sticky: true, - active: true, - style: `height: ${curGroup.height}px`, - anchorStyle, - }); - } - } - else { - child.setData({ active: false, sticky: false, anchorStyle: '' }); - } - }); - } - }, - onScroll({ scrollTop }) { - this.setAnchorOnScroll(scrollTop); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-sidebar`, `${prefix}-class-sidebar-item`] + this.properties = props + this.data = { + prefix, + classPrefix: name, + _height: 0, + _indexList: [], + scrollTop: 0, + activeAnchor: null, + showTips: false, } -}; + this.relations = { + '../indexes-anchor/indexes-anchor': { + type: 'child', + }, + } + this.behaviors = [pageScrollMixin()] + this.timer = null + this.groupTop = [] + this.sidebar = null + this.currentTouchAnchor = null + this.observers = { + indexList(v) { + this.setIndexList(v) + this.setHeight(this.data._height) + }, + height(v) { + this.setHeight(v) + }, + } + this.lifetimes = { + ready() { + this.timer = null + this.groupTop = [] + this.sidebar = null + if (this.data._height === 0) { + this.setHeight() + } + if (this.data.indexList === null) { + this.setIndexList() + } + }, + } + this.methods = { + setHeight(height) { + if (!height) { + const {windowHeight} = systemInfo + height = windowHeight + } + this.setData({ + _height: height, + }, () => { + this.getAllRect() + }) + }, + setIndexList(list) { + if (!list) { + const start = 'A'.charCodeAt(0) + const alphabet = [] + for (let i = start, end = start + 26; i < end; i += 1) { + alphabet.push(String.fromCharCode(i)) + } + this.setData({_indexList: alphabet}) + } else { + this.setData({_indexList: list}) + } + }, + getAllRect() { + this.getAnchorsRect().then(() => { + this.groupTop.forEach((item, index) => { + const next = this.groupTop[index + 1] + item.totalHeight = ((next === null || next === void 0 ? void 0 : next.top) || Infinity) - item.top + }) + this.setAnchorOnScroll(0) + }) + this.getSidebarRect() + }, + getAnchorsRect() { + return Promise.all(this.$children.map((child) => getRect(child, `.${name}-anchor`).then((rect) => { + this.groupTop.push({ + height: rect.height, + top: rect.top, + anchor: child.data.index, + }) + }))) + }, + getSidebarRect() { + getRect(this, `#id-${name}__bar`).then((rect) => { + const {top, height} = rect + const {length} = this.data._indexList + this.sidebar = { + top, + height, + itemHeight: (height - (length - 1) * 2) / length, + } + }) + }, + toggleTips(flag) { + if (!flag) { + clearInterval(this.timer) + this.timer = setTimeout(() => { + this.setData({ + showTips: false, + }) + }, 300) + } else { + this.setData({ + showTips: true, + }) + } + }, + setAnchorByIndex(index) { + const {_indexList, stickyOffset} = this.data + const activeAnchor = _indexList[index] + if (this.data.activeAnchor !== null && this.data.activeAnchor === activeAnchor) return + const target = this.groupTop.find((item) => item.anchor === activeAnchor) + if (target) { + this.currentTouchAnchor = activeAnchor + const scrollTop = target.top - stickyOffset + wx.pageScrollTo({ + scrollTop, + duration: 0, + }) + this.toggleTips(true) + this.triggerEvent('select', {index: activeAnchor}) + this.setData({activeAnchor}) + } + }, + onClick(e) { + const {index} = e.currentTarget.dataset + this.setAnchorByIndex(index) + }, + onTouchMove(e) { + this.onAnchorTouch(e) + }, + onTouchCancel() { + this.toggleTips(false) + }, + onTouchEnd(e) { + this.toggleTips(false) + this.onAnchorTouch(e) + }, + onAnchorTouch: throttle(function (e) { + const getAnchorIndex = (clientY) => { + const offsetY = clientY - this.sidebar.top + if (offsetY <= 0) { + return 0 + } + if (offsetY > this.sidebar.height) { + return this.data._indexList.length - 1 + } + return Math.floor(offsetY / this.sidebar.itemHeight) + } + const index = getAnchorIndex(e.changedTouches[0].clientY) + this.setAnchorByIndex(index) + }, 1000 / 30), + setAnchorOnScroll(scrollTop) { + if (!this.groupTop) { + return + } + const {sticky, stickyOffset, activeAnchor} = this.data + scrollTop += stickyOffset + const curIndex = this.groupTop.findIndex((group) => scrollTop >= group.top - group.height && scrollTop <= group.top + group.totalHeight - group.height) + if (curIndex === -1) return + const curGroup = this.groupTop[curIndex] + if (this.currentTouchAnchor !== null) { + this.triggerEvent('change', {index: curGroup.anchor}) + this.currentTouchAnchor = null + } else if (activeAnchor !== curGroup.anchor) { + this.triggerEvent('change', {index: curGroup.anchor}) + this.setData({activeAnchor: curGroup.anchor}) + } + if (sticky) { + const offset = curGroup.top - scrollTop + const betwixt = offset < curGroup.height && offset > 0 && scrollTop > stickyOffset + this.$children.forEach((child, index) => { + if (index === curIndex) { + const sticky = scrollTop > stickyOffset + const anchorStyle = `transform: translate3d(0, ${betwixt ? offset : 0}px, 0); top: ${stickyOffset}px` + if (anchorStyle !== child.data.anchorStyle || sticky !== child.data.sticky) { + child.setData({ + sticky, + active: true, + style: `height: ${curGroup.height}px`, + anchorStyle, + }) + } + } else if (index + 1 === curIndex) { + const anchorStyle = `transform: translate3d(0, ${betwixt ? offset - curGroup.height : 0}px, 0); top: ${stickyOffset}px` + if (anchorStyle !== child.data.anchorStyle) { + child.setData({ + sticky: true, + active: true, + style: `height: ${curGroup.height}px`, + anchorStyle, + }) + } + } else { + child.setData({active: false, sticky: false, anchorStyle: ''}) + } + }) + } + }, + onScroll({scrollTop}) { + this.setAnchorOnScroll(scrollTop) + }, + } + } +} Indexes = __decorate([ - wxComponent() -], Indexes); -export default Indexes; + wxComponent() +], Indexes) +export default Indexes diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/props.js index 2ad93eec..5595e07e 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/props.js @@ -1,14 +1,14 @@ const props = { - indexList: { - type: null, - }, - sticky: { - type: Boolean, - value: true, - }, - stickyOffset: { - type: Number, - value: 0, - }, -}; -export default props; + indexList: { + type: null, + }, + sticky: { + type: Boolean, + value: true, + }, + stickyOffset: { + type: Number, + value: 0, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/indexes/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/index.js index 2806bd66..075515f6 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/index.js @@ -1,3 +1,3 @@ -export * from './props'; -export * from './type'; -export * from './loading'; +export * from './props' +export * from './type' +export * from './loading' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/loading.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/loading.js index f59a423d..2a5dd7fa 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/loading.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/loading.js @@ -1,61 +1,63 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-loading`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-loading` let Loading = class Loading extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-text`, `${prefix}-class-indicator`]; - this.data = { - prefix, - classPrefix: name, - show: true, - }; - this.options = { - multipleSlots: true, - }; - this.properties = Object.assign({}, props); - this.timer = null; - this.observers = { - loading(cur) { - const { delay } = this.properties; - if (this.timer) { - clearTimeout(this.timer); - } - if (cur) { - if (delay) { - this.timer = setTimeout(() => { - this.setData({ show: cur }); - this.timer = null; - }, delay); - } - else { - this.setData({ show: cur }); - } - } - else { - this.setData({ show: cur }); - } - }, - }; - this.lifetimes = { - detached() { - clearTimeout(this.timer); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-text`, `${prefix}-class-indicator`] + this.data = { + prefix, + classPrefix: name, + show: true, } - refreshPage() { - this.triggerEvent('reload'); + this.options = { + multipleSlots: true, } -}; + this.properties = {...props} + this.timer = null + this.observers = { + loading(cur) { + const {delay} = this.properties + if (this.timer) { + clearTimeout(this.timer) + } + if (cur) { + if (delay) { + this.timer = setTimeout(() => { + this.setData({show: cur}) + this.timer = null + }, delay) + } else { + this.setData({show: cur}) + } + } else { + this.setData({show: cur}) + } + }, + } + this.lifetimes = { + detached() { + clearTimeout(this.timer) + }, + } + } + + refreshPage() { + this.triggerEvent('reload') + } +} Loading = __decorate([ - wxComponent() -], Loading); -export default Loading; + wxComponent() +], Loading) +export default Loading diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/props.js index 15579d40..64873c8f 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/props.js @@ -1,52 +1,52 @@ const props = { - delay: { - type: Number, - value: 0, - }, - duration: { - type: Number, - value: 800, - }, - fullscreen: { - type: Boolean, - value: false, - }, - indicator: { - type: Boolean, - value: true, - }, - inheritColor: { - type: Boolean, - value: false, - }, - layout: { - type: String, - value: 'horizontal', - }, - loading: { - type: Boolean, - value: true, - }, - pause: { - type: Boolean, - value: false, - }, - progress: { - type: Number, - }, - reverse: { - type: Boolean, - }, - size: { - type: String, - value: '20px', - }, - text: { - type: String, - }, - theme: { - type: String, - value: 'circular', - }, -}; -export default props; + delay: { + type: Number, + value: 0, + }, + duration: { + type: Number, + value: 800, + }, + fullscreen: { + type: Boolean, + value: false, + }, + indicator: { + type: Boolean, + value: true, + }, + inheritColor: { + type: Boolean, + value: false, + }, + layout: { + type: String, + value: 'horizontal', + }, + loading: { + type: Boolean, + value: true, + }, + pause: { + type: Boolean, + value: false, + }, + progress: { + type: Number, + }, + reverse: { + type: Boolean, + }, + size: { + type: String, + value: '20px', + }, + text: { + type: String, + }, + theme: { + type: String, + value: 'circular', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/loading/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/page-scroll.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/page-scroll.js index 1d0dcba8..4217ce35 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/page-scroll.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/page-scroll.js @@ -1,41 +1,36 @@ -import { getCurrentPage } from '../common/utils'; +import {getCurrentPage} from '../common/utils' + const onPageScroll = function (event) { - const page = getCurrentPage(); - if (!page) - return; - const { pageScroller } = page; - pageScroller === null || pageScroller === void 0 ? void 0 : pageScroller.forEach((scroller) => { - if (typeof scroller === 'function') { - scroller(event); - } - }); -}; -export default (funcName = 'onScroll') => { - return Behavior({ - attached() { - var _a; - const page = getCurrentPage(); - if (!page) - return; - const bindScroller = (_a = this[funcName]) === null || _a === void 0 ? void 0 : _a.bind(this); - if (bindScroller) { - this._pageScroller = bindScroller; - } - if (Array.isArray(page.pageScroller)) { - page.pageScroller.push(bindScroller); - } - else { - page.pageScroller = - typeof page.onPageScroll === 'function' ? [page.onPageScroll.bind(page), bindScroller] : [bindScroller]; - } - page.onPageScroll = onPageScroll; - }, - detached() { - var _a; - const page = getCurrentPage(); - if (!page) - return; - page.pageScroller = ((_a = page.pageScroller) === null || _a === void 0 ? void 0 : _a.filter((item) => item !== this._pageScroller)) || []; - }, - }); -}; + const page = getCurrentPage() + if (!page) return + const {pageScroller} = page + pageScroller === null || pageScroller === void 0 ? void 0 : pageScroller.forEach((scroller) => { + if (typeof scroller === 'function') { + scroller(event) + } + }) +} +export default (funcName = 'onScroll') => Behavior({ + attached() { + let _a + const page = getCurrentPage() + if (!page) return + const bindScroller = (_a = this[funcName]) === null || _a === void 0 ? void 0 : _a.bind(this) + if (bindScroller) { + this._pageScroller = bindScroller + } + if (Array.isArray(page.pageScroller)) { + page.pageScroller.push(bindScroller) + } else { + page.pageScroller = + typeof page.onPageScroll === 'function' ? [page.onPageScroll.bind(page), bindScroller] : [bindScroller] + } + page.onPageScroll = onPageScroll + }, + detached() { + let _a + const page = getCurrentPage() + if (!page) return + page.pageScroller = ((_a = page.pageScroller) === null || _a === void 0 ? void 0 : _a.filter((item) => item !== this._pageScroller)) || [] + }, +}) diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/theme-change.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/theme-change.js index 70e44edf..cada70e1 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/theme-change.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/theme-change.js @@ -1,23 +1,24 @@ -import { appBaseInfo } from '../common/utils'; +import {appBaseInfo} from '../common/utils' + const themeChangeBehavior = Behavior({ - data: { - theme: 'light', + data: { + theme: 'light', + }, + attached() { + this._initTheme() + }, + methods: { + _initTheme() { + const that = this + that.setData({ + theme: appBaseInfo.theme, + }) + wx.onThemeChange((res) => { + that.setData({ + theme: res.theme, + }) + }) }, - attached() { - this._initTheme(); - }, - methods: { - _initTheme() { - const that = this; - that.setData({ - theme: appBaseInfo.theme, - }); - wx.onThemeChange((res) => { - that.setData({ - theme: res.theme, - }); - }); - }, - }, -}); -export default themeChangeBehavior; + }, +}) +export default themeChangeBehavior diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/touch.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/touch.js index cbabccc0..49a6f981 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/touch.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/touch.js @@ -1,35 +1,35 @@ -const MinDistance = 10; +const MinDistance = 10 const getDirection = (x, y) => { - if (x > y && x > MinDistance) { - return 'horizontal'; - } - if (y > x && y > MinDistance) { - return 'vertical'; - } - return ''; -}; + if (x > y && x > MinDistance) { + return 'horizontal' + } + if (y > x && y > MinDistance) { + return 'vertical' + } + return '' +} export default Behavior({ - methods: { - resetTouchStatus() { - this.direction = ''; - this.deltaX = 0; - this.deltaY = 0; - this.offsetX = 0; - this.offsetY = 0; - }, - touchStart(event) { - this.resetTouchStatus(); - const [touch] = event.touches; - this.startX = touch.clientX; - this.startY = touch.clientY; - }, - touchMove(event) { - const [touch] = event.touches; - this.deltaX = touch.clientX - this.startX; - this.deltaY = touch.clientY - this.startY; - this.offsetX = Math.abs(this.deltaX); - this.offsetY = Math.abs(this.deltaY); - this.direction = getDirection(this.offsetX, this.offsetY); - }, + methods: { + resetTouchStatus() { + this.direction = '' + this.deltaX = 0 + this.deltaY = 0 + this.offsetX = 0 + this.offsetY = 0 }, -}); + touchStart(event) { + this.resetTouchStatus() + const [touch] = event.touches + this.startX = touch.clientX + this.startY = touch.clientY + }, + touchMove(event) { + const [touch] = event.touches + this.deltaX = touch.clientX - this.startX + this.deltaY = touch.clientY - this.startY + this.offsetX = Math.abs(this.deltaX) + this.offsetY = Math.abs(this.deltaY) + this.direction = getDirection(this.offsetX, this.offsetY) + }, + }, +}) diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/transition.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/transition.js index ee5215ae..ac115365 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/transition.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/transition.js @@ -1,123 +1,123 @@ -import config from '../common/config'; -const { prefix } = config; +import config from '../common/config' + +const {prefix} = config export default function transition() { - return Behavior({ - properties: { - visible: { - type: Boolean, - value: null, - observer: 'watchVisible', - }, - appear: Boolean, - name: { - type: String, - value: 'fade', - }, - durations: { - type: Number, - optionalTypes: [Array], - }, - }, - data: { - transitionClass: '', - transitionDurations: 300, - className: '', + return Behavior({ + properties: { + visible: { + type: Boolean, + value: null, + observer: 'watchVisible', + }, + appear: Boolean, + name: { + type: String, + value: 'fade', + }, + durations: { + type: Number, + optionalTypes: [Array], + }, + }, + data: { + transitionClass: '', + transitionDurations: 300, + className: '', + realVisible: false, + }, + created() { + this.status = '' + this.transitionT = 0 + }, + attached() { + this.durations = this.getDurations() + if (this.data.visible) { + this.enter() + } + this.inited = true + }, + detached() { + clearTimeout(this.transitionT) + }, + methods: { + watchVisible(curr, prev) { + if (this.inited && curr !== prev) { + curr ? this.enter() : this.leave() + } + }, + getDurations() { + const {durations} = this.data + if (Array.isArray(durations)) { + return durations.map((item) => Number(item)) + } + return [Number(durations), Number(durations)] + }, + enter() { + const {name} = this.data + const [duration] = this.durations + this.status = 'entering' + this.setData({ + realVisible: true, + transitionClass: `${prefix}-${name}-enter ${prefix}-${name}-enter-active`, + }) + setTimeout(() => { + this.setData({ + transitionClass: `${prefix}-${name}-enter-active ${prefix}-${name}-enter-to`, + }) + }, 30) + if (typeof duration === 'number' && duration > 0) { + this.transitionT = setTimeout(this.entered.bind(this), duration + 30) + } + }, + entered() { + this.customDuration = false + clearTimeout(this.transitionT) + this.status = 'entered' + this.setData({ + transitionClass: '', + }) + }, + leave() { + const {name} = this.data + const [, duration] = this.durations + this.status = 'leaving' + this.setData({ + transitionClass: `${prefix}-${name}-leave ${prefix}-${name}-leave-active`, + }) + clearTimeout(this.transitionT) + setTimeout(() => { + this.setData({ + transitionClass: `${prefix}-${name}-leave-active ${prefix}-${name}-leave-to`, + }) + }, 30) + if (typeof duration === 'number' && duration > 0) { + this.customDuration = true + this.transitionT = setTimeout(this.leaved.bind(this), duration + 30) + } + }, + leaved() { + this.customDuration = false + this.triggerEvent('leaved') + clearTimeout(this.transitionT) + this.status = 'leaved' + this.setData({ + transitionClass: '', + }) + }, + onTransitionEnd() { + if (this.customDuration) { + return + } + clearTimeout(this.transitionT) + if (this.status === 'entering' && this.data.visible) { + this.entered() + } else if (this.status === 'leaving' && !this.data.visible) { + this.leaved() + this.setData({ realVisible: false, - }, - created() { - this.status = ''; - this.transitionT = 0; - }, - attached() { - this.durations = this.getDurations(); - if (this.data.visible) { - this.enter(); - } - this.inited = true; - }, - detached() { - clearTimeout(this.transitionT); - }, - methods: { - watchVisible(curr, prev) { - if (this.inited && curr !== prev) { - curr ? this.enter() : this.leave(); - } - }, - getDurations() { - const { durations } = this.data; - if (Array.isArray(durations)) { - return durations.map((item) => Number(item)); - } - return [Number(durations), Number(durations)]; - }, - enter() { - const { name } = this.data; - const [duration] = this.durations; - this.status = 'entering'; - this.setData({ - realVisible: true, - transitionClass: `${prefix}-${name}-enter ${prefix}-${name}-enter-active`, - }); - setTimeout(() => { - this.setData({ - transitionClass: `${prefix}-${name}-enter-active ${prefix}-${name}-enter-to`, - }); - }, 30); - if (typeof duration === 'number' && duration > 0) { - this.transitionT = setTimeout(this.entered.bind(this), duration + 30); - } - }, - entered() { - this.customDuration = false; - clearTimeout(this.transitionT); - this.status = 'entered'; - this.setData({ - transitionClass: '', - }); - }, - leave() { - const { name } = this.data; - const [, duration] = this.durations; - this.status = 'leaving'; - this.setData({ - transitionClass: `${prefix}-${name}-leave ${prefix}-${name}-leave-active`, - }); - clearTimeout(this.transitionT); - setTimeout(() => { - this.setData({ - transitionClass: `${prefix}-${name}-leave-active ${prefix}-${name}-leave-to`, - }); - }, 30); - if (typeof duration === 'number' && duration > 0) { - this.customDuration = true; - this.transitionT = setTimeout(this.leaved.bind(this), duration + 30); - } - }, - leaved() { - this.customDuration = false; - this.triggerEvent('leaved'); - clearTimeout(this.transitionT); - this.status = 'leaved'; - this.setData({ - transitionClass: '', - }); - }, - onTransitionEnd() { - if (this.customDuration) { - return; - } - clearTimeout(this.transitionT); - if (this.status === 'entering' && this.data.visible) { - this.entered(); - } - else if (this.status === 'leaving' && !this.data.visible) { - this.leaved(); - this.setData({ - realVisible: false, - }); - } - }, - }, - }); + }) + } + }, + }, + }) } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/using-custom-navbar.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/using-custom-navbar.js index e9bf8e3c..7c247cf3 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/using-custom-navbar.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/mixins/using-custom-navbar.js @@ -1,34 +1,35 @@ -import { systemInfo } from '../common/utils'; +import {systemInfo} from '../common/utils' + const useCustomNavbarBehavior = Behavior({ - properties: { - usingCustomNavbar: { - type: Boolean, - value: false, - }, - customNavbarHeight: { - type: Number, - value: 0, - }, + properties: { + usingCustomNavbar: { + type: Boolean, + value: false, }, - data: { - distanceTop: 0, + customNavbarHeight: { + type: Number, + value: 0, }, - lifetimes: { - attached() { - if (this.properties.usingCustomNavbar) { - this.calculateCustomNavbarDistanceTop(); - } - }, + }, + data: { + distanceTop: 0, + }, + lifetimes: { + attached() { + if (this.properties.usingCustomNavbar) { + this.calculateCustomNavbarDistanceTop() + } }, - methods: { - calculateCustomNavbarDistanceTop() { - const { statusBarHeight } = systemInfo; - const menuButton = wx.getMenuButtonBoundingClientRect(); - const distance = menuButton.top + menuButton.bottom - statusBarHeight; - this.setData({ - distanceTop: Math.max(distance, this.properties.customNavbarHeight + statusBarHeight), - }); - }, + }, + methods: { + calculateCustomNavbarDistanceTop() { + const {statusBarHeight} = systemInfo + const menuButton = wx.getMenuButtonBoundingClientRect() + const distance = menuButton.top + menuButton.bottom - statusBarHeight + this.setData({ + distanceTop: Math.max(distance, this.properties.customNavbarHeight + statusBarHeight), + }) }, -}); -export default useCustomNavbarBehavior; + }, +}) +export default useCustomNavbarBehavior diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/navbar.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/navbar.js index 4d54b117..f609a6ac 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/navbar.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/navbar.js @@ -1,186 +1,187 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import { getRect, systemInfo } from '../common/utils'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-navbar`; +import {SuperComponent, wxComponent} from '../common/src/index' +import {getRect, systemInfo} from '../common/utils' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-navbar` let Navbar = class Navbar extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-placeholder`, - `${prefix}-class-content`, - `${prefix}-class-title`, - `${prefix}-class-left`, - `${prefix}-class-center`, - `${prefix}-class-left-icon`, - `${prefix}-class-home-icon`, - `${prefix}-class-capsule`, - `${prefix}-class-nav-btn`, - ]; - this.timer = null; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.observers = { - visible(visible) { - const { animation } = this.properties; - const visibleClass = `${name}${visible ? '--visible' : '--hide'}`; - this.setData({ - visibleClass: `${visibleClass}${animation ? '-animation' : ''}`, - }); - if (this.timer) { - clearTimeout(this.timer); - } - if (animation) { - this.timer = setTimeout(() => { - this.setData({ - visibleClass, - }); - }, 300); - } - }, - 'title,titleMaxLength'() { - const { title } = this.properties; - const titleMaxLength = this.properties.titleMaxLength || Number.MAX_SAFE_INTEGER; - let temp = title.slice(0, titleMaxLength); - if (titleMaxLength < title.length) - temp += '...'; - this.setData({ - showTitle: temp, - }); - }, - }; - this.data = { - prefix, - classPrefix: name, - boxStyle: '', - showTitle: '', - hideLeft: false, - hideCenter: false, - _menuRect: null, - _leftRect: null, - _boxStyle: {}, - }; - this.methods = { - initStyle() { - this.getMenuRect(); - const { _menuRect, _leftRect } = this.data; - if (!_menuRect || !_leftRect || !systemInfo) - return; - const _boxStyle = { - '--td-navbar-padding-top': `${systemInfo.statusBarHeight}px`, - '--td-navbar-right': `${systemInfo.windowWidth - _menuRect.left}px`, - '--td-navbar-left-max-width': `${_menuRect.left}px`, - '--td-navbar-capsule-height': `${_menuRect.height}px`, - '--td-navbar-capsule-width': `${_menuRect.width}px`, - '--td-navbar-height': `${(_menuRect.top - systemInfo.statusBarHeight) * 2 + _menuRect.height}px`, - }; - this.calcCenterStyle(_leftRect, _menuRect, _boxStyle); - }, - calcCenterStyle(leftRect, menuRect, defaultStyle) { - const maxSpacing = Math.max(leftRect.right, systemInfo.windowWidth - menuRect.left); - const _boxStyle = Object.assign(Object.assign({}, defaultStyle), { '--td-navbar-center-left': `${maxSpacing}px`, '--td-navbar-center-width': `${Math.max(menuRect.left - maxSpacing, 0)}px` }); - const boxStyle = Object.entries(_boxStyle) - .map(([k, v]) => `${k}: ${v}`) - .join('; '); - this.setData({ - boxStyle, - _boxStyle, - }); - }, - getLeftRect() { - getRect(this, `.${name}__left`).then((res) => { - if (res.right > this.data._leftRect.right) { - this.calcCenterStyle(res, this.data._menuRect, this.data._boxStyle); - } - }); - }, - getMenuRect() { - if (wx.getMenuButtonBoundingClientRect) { - const rect = wx.getMenuButtonBoundingClientRect(); - this.setData({ - _menuRect: rect, - _leftRect: { - right: systemInfo.windowWidth - rect.left, - }, - }); - } - }, - onMenuButtonBoundingClientRectWeightChange() { - if (wx.onMenuButtonBoundingClientRectWeightChange) { - wx.onMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)); - } + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-placeholder`, + `${prefix}-class-content`, + `${prefix}-class-title`, + `${prefix}-class-left`, + `${prefix}-class-center`, + `${prefix}-class-left-icon`, + `${prefix}-class-home-icon`, + `${prefix}-class-capsule`, + `${prefix}-class-nav-btn`, + ] + this.timer = null + this.options = { + multipleSlots: true, + } + this.properties = props + this.observers = { + visible(visible) { + const {animation} = this.properties + const visibleClass = `${name}${visible ? '--visible' : '--hide'}` + this.setData({ + visibleClass: `${visibleClass}${animation ? '-animation' : ''}`, + }) + if (this.timer) { + clearTimeout(this.timer) + } + if (animation) { + this.timer = setTimeout(() => { + this.setData({ + visibleClass, + }) + }, 300) + } + }, + 'title,titleMaxLength': function () { + const {title} = this.properties + const titleMaxLength = this.properties.titleMaxLength || Number.MAX_SAFE_INTEGER + let temp = title.slice(0, titleMaxLength) + if (titleMaxLength < title.length) temp += '...' + this.setData({ + showTitle: temp, + }) + }, + } + this.data = { + prefix, + classPrefix: name, + boxStyle: '', + showTitle: '', + hideLeft: false, + hideCenter: false, + _menuRect: null, + _leftRect: null, + _boxStyle: {}, + } + this.methods = { + initStyle() { + this.getMenuRect() + const {_menuRect, _leftRect} = this.data + if (!_menuRect || !_leftRect || !systemInfo) return + const _boxStyle = { + '--td-navbar-padding-top': `${systemInfo.statusBarHeight}px`, + '--td-navbar-right': `${systemInfo.windowWidth - _menuRect.left}px`, + '--td-navbar-left-max-width': `${_menuRect.left}px`, + '--td-navbar-capsule-height': `${_menuRect.height}px`, + '--td-navbar-capsule-width': `${_menuRect.width}px`, + '--td-navbar-height': `${(_menuRect.top - systemInfo.statusBarHeight) * 2 + _menuRect.height}px`, + } + this.calcCenterStyle(_leftRect, _menuRect, _boxStyle) + }, + calcCenterStyle(leftRect, menuRect, defaultStyle) { + const maxSpacing = Math.max(leftRect.right, systemInfo.windowWidth - menuRect.left) + const _boxStyle = {...defaultStyle, '--td-navbar-center-left': `${maxSpacing}px`, '--td-navbar-center-width': `${Math.max(menuRect.left - maxSpacing, 0)}px`} + const boxStyle = Object.entries(_boxStyle) + .map(([k, v]) => `${k}: ${v}`) + .join('; ') + this.setData({ + boxStyle, + _boxStyle, + }) + }, + getLeftRect() { + getRect(this, `.${name}__left`).then((res) => { + if (res.right > this.data._leftRect.right) { + this.calcCenterStyle(res, this.data._menuRect, this.data._boxStyle) + } + }) + }, + getMenuRect() { + if (wx.getMenuButtonBoundingClientRect) { + const rect = wx.getMenuButtonBoundingClientRect() + this.setData({ + _menuRect: rect, + _leftRect: { + right: systemInfo.windowWidth - rect.left, }, - offMenuButtonBoundingClientRectWeightChange() { - if (wx.offMenuButtonBoundingClientRectWeightChange) { - wx.offMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)); - } + }) + } + }, + onMenuButtonBoundingClientRectWeightChange() { + if (wx.onMenuButtonBoundingClientRectWeightChange) { + wx.onMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)) + } + }, + offMenuButtonBoundingClientRectWeightChange() { + if (wx.offMenuButtonBoundingClientRectWeightChange) { + wx.offMenuButtonBoundingClientRectWeightChange((res) => this.queryElements(res)) + } + }, + queryElements(capsuleRect) { + Promise.all([ + getRect(this, `.${this.data.classPrefix}__left`), + getRect(this, `.${this.data.classPrefix}__center`), + ]).then(([leftRect, centerRect]) => { + if (Math.round(leftRect.right) > capsuleRect.left) { + this.setData({ + hideLeft: true, + hideCenter: true, + }) + } else if (Math.round(centerRect.right) > capsuleRect.left) { + this.setData({ + hideLeft: false, + hideCenter: true, + }) + } else { + this.setData({ + hideLeft: false, + hideCenter: false, + }) + } + }) + }, + goBack() { + const {delta} = this.data + const that = this + this.triggerEvent('go-back') + if (delta > 0) { + wx.navigateBack({ + delta, + fail(e) { + that.triggerEvent('fail', e) }, - queryElements(capsuleRect) { - Promise.all([ - getRect(this, `.${this.data.classPrefix}__left`), - getRect(this, `.${this.data.classPrefix}__center`), - ]).then(([leftRect, centerRect]) => { - if (Math.round(leftRect.right) > capsuleRect.left) { - this.setData({ - hideLeft: true, - hideCenter: true, - }); - } - else if (Math.round(centerRect.right) > capsuleRect.left) { - this.setData({ - hideLeft: false, - hideCenter: true, - }); - } - else { - this.setData({ - hideLeft: false, - hideCenter: false, - }); - } - }); + complete(e) { + that.triggerEvent('complete', e) }, - goBack() { - const { delta } = this.data; - const that = this; - this.triggerEvent('go-back'); - if (delta > 0) { - wx.navigateBack({ - delta, - fail(e) { - that.triggerEvent('fail', e); - }, - complete(e) { - that.triggerEvent('complete', e); - }, - success(e) { - that.triggerEvent('success', e); - }, - }); - } + success(e) { + that.triggerEvent('success', e) }, - }; - } - attached() { - this.initStyle(); - this.getLeftRect(); - this.onMenuButtonBoundingClientRectWeightChange(); - } - detached() { - this.offMenuButtonBoundingClientRectWeightChange(); + }) + } + }, } -}; + } + + attached() { + this.initStyle() + this.getLeftRect() + this.onMenuButtonBoundingClientRectWeightChange() + } + + detached() { + this.offMenuButtonBoundingClientRectWeightChange() + } +} Navbar = __decorate([ - wxComponent() -], Navbar); -export default Navbar; + wxComponent() +], Navbar) +export default Navbar diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/props.js index 3906316e..cb208aac 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/props.js @@ -1,29 +1,29 @@ const props = { - animation: { - type: Boolean, - value: true, - }, - delta: { - type: Number, - value: 1, - }, - fixed: { - type: Boolean, - value: true, - }, - leftArrow: { - type: Boolean, - value: false, - }, - title: { - type: String, - }, - titleMaxLength: { - type: Number, - }, - visible: { - type: Boolean, - value: true, - }, -}; -export default props; + animation: { + type: Boolean, + value: true, + }, + delta: { + type: Number, + value: 1, + }, + fixed: { + type: Boolean, + value: true, + }, + leftArrow: { + type: Boolean, + value: false, + }, + title: { + type: String, + }, + titleMaxLength: { + type: Number, + }, + visible: { + type: Boolean, + value: true, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/navbar/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/progress.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/progress.js index fae98d5c..5226399b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/progress.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/progress.js @@ -1,71 +1,75 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -import { getBackgroundColor } from './utils'; -import { unitConvert, deviceInfo } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-progress`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' +import {getBackgroundColor} from './utils' +import {unitConvert, deviceInfo} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-progress` let Progress = class Progress extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-bar`, `${prefix}-class-label`]; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - colorBar: '', - heightBar: '', - computedStatus: '', - computedProgress: 0, - isIOS: false, - }; - this.observers = { - percentage(percentage) { - percentage = Math.max(0, Math.min(percentage, 100)); - this.setData({ - computedStatus: percentage === 100 ? 'success' : '', - computedProgress: percentage, - }); - }, - color(color) { - this.setData({ - colorBar: getBackgroundColor(color), - colorCircle: typeof color === 'object' ? '' : color, - }); - }, - strokeWidth(strokeWidth) { - if (!strokeWidth) { - return ''; - } - this.setData({ - heightBar: unitConvert(strokeWidth), - }); - }, - trackColor(trackColor) { - this.setData({ - bgColorBar: trackColor, - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-bar`, `${prefix}-class-label`] + this.options = { + multipleSlots: true, } - attached() { - var _a; - const isIOS = !!(((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.system) === null || _a === void 0 ? void 0 : _a.toLowerCase().search('ios')) + 1); + this.properties = props + this.data = { + prefix, + classPrefix: name, + colorBar: '', + heightBar: '', + computedStatus: '', + computedProgress: 0, + isIOS: false, + } + this.observers = { + percentage(percentage) { + percentage = Math.max(0, Math.min(percentage, 100)) + this.setData({ + computedStatus: percentage === 100 ? 'success' : '', + computedProgress: percentage, + }) + }, + color(color) { + this.setData({ + colorBar: getBackgroundColor(color), + colorCircle: typeof color === 'object' ? '' : color, + }) + }, + strokeWidth(strokeWidth) { + if (!strokeWidth) { + return '' + } + this.setData({ + heightBar: unitConvert(strokeWidth), + }) + }, + trackColor(trackColor) { this.setData({ - isIOS, - }); + bgColorBar: trackColor, + }) + }, } -}; + } + + attached() { + let _a + const isIOS = !!(((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.system) === null || _a === void 0 ? void 0 : _a.toLowerCase().search('ios')) + 1) + this.setData({ + isIOS, + }) + } +} Progress = __decorate([ - wxComponent() -], Progress); -export default Progress; + wxComponent() +], Progress) +export default Progress diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/props.js index 406b7bcd..740213c5 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/props.js @@ -1,33 +1,33 @@ const props = { - color: { - type: null, - value: '', - }, - label: { - type: null, - value: true, - }, - percentage: { - type: Number, - value: 0, - }, - status: { - type: String, - }, - strokeWidth: { - type: null, - }, - style: { - type: String, - value: '', - }, - theme: { - type: String, - value: 'line', - }, - trackColor: { - type: String, - value: '', - }, -}; -export default props; + color: { + type: null, + value: '', + }, + label: { + type: null, + value: true, + }, + percentage: { + type: Number, + value: 0, + }, + status: { + type: String, + }, + strokeWidth: { + type: null, + }, + style: { + type: String, + value: '', + }, + theme: { + type: String, + value: 'line', + }, + trackColor: { + type: String, + value: '', + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/utils.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/utils.js index 455982cd..c0592034 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/utils.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/progress/utils.js @@ -1,30 +1,30 @@ -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -export function getBackgroundColor(color) { - if (typeof color === 'string') { - return color; - } - if (Array.isArray(color)) { - if (color[0] && color[0][0] === '#') { - color.unshift('90deg'); - } - return `linear-gradient( ${color.join(',')} )`; +const __rest = (this && this.__rest) || function (s, e) { + const t = {} + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p] } + if (s != null && typeof Object.getOwnPropertySymbols === 'function') { + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]] } - const { from, to, direction = 'to right' } = color, rest = __rest(color, ["from", "to", "direction"]); - let keys = Object.keys(rest); - if (keys.length) { - keys = keys.sort((a, b) => parseFloat(a.substr(0, a.length - 1)) - parseFloat(b.substr(0, b.length - 1))); - const tempArr = keys.map((key) => `${rest[key]} ${key}`); - return `linear-gradient(${direction}, ${tempArr.join(',')})`; + } + return t +} +export function getBackgroundColor(color) { + if (typeof color === 'string') { + return color + } + if (Array.isArray(color)) { + if (color[0] && color[0][0] === '#') { + color.unshift('90deg') } - return `linear-gradient(${direction}, ${from}, ${to})`; + return `linear-gradient( ${color.join(',')} )` + } + const {from, to, direction = 'to right'} = color; const + rest = __rest(color, ['from', 'to', 'direction']) + let keys = Object.keys(rest) + if (keys.length) { + keys = keys.sort((a, b) => parseFloat(a.substr(0, a.length - 1)) - parseFloat(b.substr(0, b.length - 1))) + const tempArr = keys.map((key) => `${rest[key]} ${key}`) + return `linear-gradient(${direction}, ${tempArr.join(',')})` + } + return `linear-gradient(${direction}, ${from}, ${to})` } diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/props.js index 3de9e57f..c4ecfbe3 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/props.js @@ -1,40 +1,40 @@ const props = { - allowUncheck: { - type: Boolean, - value: false, - }, - borderless: { - type: Boolean, - value: false, - }, - disabled: { - type: null, - value: undefined, - }, - icon: { - type: null, - value: 'circle', - }, - keys: { - type: Object, - }, - name: { - type: String, - value: '', - }, - options: { - type: Array, - }, - placement: { - type: String, - value: 'left', - }, - value: { - type: null, - value: null, - }, - defaultValue: { - type: null, - }, -}; -export default props; + allowUncheck: { + type: Boolean, + value: false, + }, + borderless: { + type: Boolean, + value: false, + }, + disabled: { + type: null, + value: undefined, + }, + icon: { + type: null, + value: 'circle', + }, + keys: { + type: Object, + }, + name: { + type: String, + value: '', + }, + options: { + type: Array, + }, + placement: { + type: String, + value: 'left', + }, + value: { + type: null, + value: null, + }, + defaultValue: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/radio-group.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/radio-group.js index c142af47..a4e5c031 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/radio-group.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/radio-group.js @@ -1,117 +1,123 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import config from '../common/config'; -import { SuperComponent, wxComponent } from '../common/src/index'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-radio-group`; +import config from '../common/config' +import {SuperComponent, wxComponent} from '../common/src/index' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-radio-group` let RadioGroup = class RadioGroup extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.data = { - prefix, - classPrefix: name, + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.data = { + prefix, + classPrefix: name, + radioOptions: [], + } + this.relations = { + '../radio/radio': { + type: 'descendant', + linked(target) { + const {value, disabled} = this.data + target.setData({ + checked: value === target.data.value, + }) + target.setDisabled(disabled) + }, + }, + } + this.properties = props + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.observers = { + value(v) { + this.getChildren().forEach((item) => { + item.setData({ + checked: v === item.data.value, + }) + }) + }, + options() { + this.initWithOptions() + }, + disabled(v) { + let _a + if ((_a = this.data.options) === null || _a === void 0 ? void 0 : _a.length) { + this.initWithOptions() + return + } + this.getChildren().forEach((item) => { + item.setDisabled(v) + }) + }, + } + this.methods = { + getChildren() { + let items = this.$children + if (!(items === null || items === void 0 ? void 0 : items.length)) { + items = this.selectAllComponents(`.${prefix}-radio-option`) + } + return items + }, + updateValue(value) { + this._trigger('change', {value}) + }, + handleRadioChange(e) { + const {checked} = e.detail + const {value, index, allowUncheck} = e.target.dataset + this._trigger('change', checked === false && allowUncheck ? {value: null, index} : {value, index}) + }, + initWithOptions() { + const { + options, value, keys, disabled + } = this.data + if (!(options === null || options === void 0 ? void 0 : options.length) || !Array.isArray(options)) { + this.setData({ radioOptions: [], - }; - this.relations = { - '../radio/radio': { - type: 'descendant', - linked(target) { - const { value, disabled } = this.data; - target.setData({ - checked: value === target.data.value, - }); - target.setDisabled(disabled); - }, - }, - }; - this.properties = props; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.observers = { - value(v) { - this.getChildren().forEach((item) => { - item.setData({ - checked: v === item.data.value, - }); - }); - }, - options() { - this.initWithOptions(); - }, - disabled(v) { - var _a; - if ((_a = this.data.options) === null || _a === void 0 ? void 0 : _a.length) { - this.initWithOptions(); - return; - } - this.getChildren().forEach((item) => { - item.setDisabled(v); - }); - }, - }; - this.methods = { - getChildren() { - let items = this.$children; - if (!(items === null || items === void 0 ? void 0 : items.length)) { - items = this.selectAllComponents(`.${prefix}-radio-option`); - } - return items; - }, - updateValue(value) { - this._trigger('change', { value }); - }, - handleRadioChange(e) { - const { checked } = e.detail; - const { value, index, allowUncheck } = e.target.dataset; - this._trigger('change', checked === false && allowUncheck ? { value: null, index } : { value, index }); - }, - initWithOptions() { - const { options, value, keys, disabled } = this.data; - if (!(options === null || options === void 0 ? void 0 : options.length) || !Array.isArray(options)) { - this.setData({ - radioOptions: [], - }); - return; - } - const optionsValue = []; - try { - options.forEach((element) => { - var _a, _b, _c; - const typeName = typeof element; - if (typeName === 'number' || typeName === 'string') { - optionsValue.push({ - label: `${element}`, - value: element, - checked: value === element, - disabled, - }); - } - else if (typeName === 'object') { - optionsValue.push(Object.assign(Object.assign({}, element), { label: element[(_a = keys === null || keys === void 0 ? void 0 : keys.label) !== null && _a !== void 0 ? _a : 'label'], value: element[(_b = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _b !== void 0 ? _b : 'value'], checked: value === element[(_c = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _c !== void 0 ? _c : 'value'], disabled: element.disabled || disabled })); - } - }); - this.setData({ - radioOptions: optionsValue, - }); - } - catch (error) { - console.error('error', error); - } - }, - }; + }) + return + } + const optionsValue = [] + try { + options.forEach((element) => { + let _a; let _b; let + _c + const typeName = typeof element + if (typeName === 'number' || typeName === 'string') { + optionsValue.push({ + label: `${element}`, + value: element, + checked: value === element, + disabled, + }) + } else if (typeName === 'object') { + optionsValue.push({ + ...element, label: element[(_a = keys === null || keys === void 0 ? void 0 : keys.label) !== null && _a !== void 0 ? _a : 'label'], value: element[(_b = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _b !== void 0 ? _b : 'value'], checked: value === element[(_c = keys === null || keys === void 0 ? void 0 : keys.value) !== null && _c !== void 0 ? _c : 'value'], disabled: element.disabled || disabled + }) + } + }) + this.setData({ + radioOptions: optionsValue, + }) + } catch (error) { + console.error('error', error) + } + }, } -}; + } +} RadioGroup = __decorate([ - wxComponent() -], RadioGroup); -export default RadioGroup; + wxComponent() +], RadioGroup) +export default RadioGroup diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio-group/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/props.js index 545afe27..414d9995 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/props.js @@ -1,61 +1,61 @@ const props = { - allowUncheck: { - type: Boolean, - value: false, - }, - block: { - type: Boolean, - value: true, - }, - checked: { - type: Boolean, - value: null, - }, - defaultChecked: { - type: Boolean, - value: false, - }, - content: { - type: String, - }, - contentDisabled: { - type: Boolean, - value: false, - }, - disabled: { - type: null, - value: undefined, - }, - icon: { - type: null, - value: 'circle', - }, - label: { - type: String, - }, - maxContentRow: { - type: Number, - value: 5, - }, - maxLabelRow: { - type: Number, - value: 3, - }, - name: { - type: String, - value: '', - }, - placement: { - type: String, - value: 'left', - }, - readonly: { - type: Boolean, - value: false, - }, - value: { - type: null, - value: false, - }, -}; -export default props; + allowUncheck: { + type: Boolean, + value: false, + }, + block: { + type: Boolean, + value: true, + }, + checked: { + type: Boolean, + value: null, + }, + defaultChecked: { + type: Boolean, + value: false, + }, + content: { + type: String, + }, + contentDisabled: { + type: Boolean, + value: false, + }, + disabled: { + type: null, + value: undefined, + }, + icon: { + type: null, + value: 'circle', + }, + label: { + type: String, + }, + maxContentRow: { + type: Number, + value: 5, + }, + maxLabelRow: { + type: Number, + value: 3, + }, + name: { + type: String, + value: '', + }, + placement: { + type: String, + value: 'left', + }, + readonly: { + type: Boolean, + value: false, + }, + value: { + type: null, + value: false, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/radio.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/radio.js index 5dcd7b1a..467d7d29 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/radio.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/radio.js @@ -1,109 +1,115 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import config from '../common/config'; -import { SuperComponent, wxComponent } from '../common/src/index'; -import Props from './props'; -const { prefix } = config; -const name = `${prefix}-radio`; +import config from '../common/config' +import {SuperComponent, wxComponent} from '../common/src/index' +import Props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-radio` let Radio = class Radio extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-label`, - `${prefix}-class-icon`, - `${prefix}-class-content`, - `${prefix}-class-border`, - ]; - this.behaviors = ['wx://form-field']; - this.relations = { - '../radio-group/radio-group': { - type: 'ancestor', - linked(parent) { - if (parent.data.borderless) { - this.setData({ borderless: true }); - } - }, - }, - }; - this.options = { - multipleSlots: true, - }; - this.lifetimes = { - attached() { - this.init(); - }, - }; - this.properties = Object.assign(Object.assign({}, Props), { borderless: { - type: Boolean, - value: false, - }, tId: { - type: String, - } }); - this.controlledProps = [ - { - key: 'checked', - event: 'change', - }, - ]; - this.data = { - prefix, - classPrefix: name, - customIcon: false, - slotIcon: false, - optionLinked: false, - iconVal: [], - _placement: '', - _disabled: false, - }; - this.observers = { - disabled(v) { - this.setData({ _disabled: v }); - }, - }; - this.methods = { - handleTap(e) { - const { _disabled, readonly, contentDisabled } = this.data; - const { target } = e.currentTarget.dataset; - if (_disabled || readonly || (target === 'text' && contentDisabled)) - return; - this.doChange(); - }, - doChange() { - var _a; - const { value, checked, allowUncheck } = this.data; - const isAllowUncheck = Boolean(allowUncheck || ((_a = this.$parent) === null || _a === void 0 ? void 0 : _a.data.allowUncheck)); - if (this.$parent) { - this.$parent.updateValue(checked && isAllowUncheck ? null : value); - } - else { - this._trigger('change', { checked: isAllowUncheck ? !checked : true }); - } - }, - init() { - var _a, _b, _c, _d, _e, _f; - const { icon } = this.data; - const isIdArr = Array.isArray(((_a = this.$parent) === null || _a === void 0 ? void 0 : _a.icon) || icon); - this.setData({ - customIcon: isIdArr, - slotIcon: icon === 'slot', - iconVal: isIdArr ? ((_b = this.$parent) === null || _b === void 0 ? void 0 : _b.icon) || icon : [], - _placement: (_f = (_c = this.data.placement) !== null && _c !== void 0 ? _c : (_e = (_d = this.$parent) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.placement) !== null && _f !== void 0 ? _f : 'left', - }); - }, - setDisabled(disabled) { - this.setData({ - _disabled: this.data.disabled || disabled, - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-label`, + `${prefix}-class-icon`, + `${prefix}-class-content`, + `${prefix}-class-border`, + ] + this.behaviors = ['wx://form-field'] + this.relations = { + '../radio-group/radio-group': { + type: 'ancestor', + linked(parent) { + if (parent.data.borderless) { + this.setData({borderless: true}) + } + }, + }, } -}; + this.options = { + multipleSlots: true, + } + this.lifetimes = { + attached() { + this.init() + }, + } + this.properties = { + ...Props, + borderless: { + type: Boolean, + value: false, + }, + tId: { + type: String, + } + } + this.controlledProps = [ + { + key: 'checked', + event: 'change', + }, + ] + this.data = { + prefix, + classPrefix: name, + customIcon: false, + slotIcon: false, + optionLinked: false, + iconVal: [], + _placement: '', + _disabled: false, + } + this.observers = { + disabled(v) { + this.setData({_disabled: v}) + }, + } + this.methods = { + handleTap(e) { + const {_disabled, readonly, contentDisabled} = this.data + const {target} = e.currentTarget.dataset + if (_disabled || readonly || (target === 'text' && contentDisabled)) return + this.doChange() + }, + doChange() { + let _a + const {value, checked, allowUncheck} = this.data + const isAllowUncheck = Boolean(allowUncheck || ((_a = this.$parent) === null || _a === void 0 ? void 0 : _a.data.allowUncheck)) + if (this.$parent) { + this.$parent.updateValue(checked && isAllowUncheck ? null : value) + } else { + this._trigger('change', {checked: isAllowUncheck ? !checked : true}) + } + }, + init() { + let _a; let _b; let _c; let _d; let _e; let + _f + const {icon} = this.data + const isIdArr = Array.isArray(((_a = this.$parent) === null || _a === void 0 ? void 0 : _a.icon) || icon) + this.setData({ + customIcon: isIdArr, + slotIcon: icon === 'slot', + iconVal: isIdArr ? ((_b = this.$parent) === null || _b === void 0 ? void 0 : _b.icon) || icon : [], + _placement: (_f = (_c = this.data.placement) !== null && _c !== void 0 ? _c : (_e = (_d = this.$parent) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.placement) !== null && _f !== void 0 ? _f : 'left', + }) + }, + setDisabled(disabled) { + this.setData({ + _disabled: this.data.disabled || disabled, + }) + }, + } + } +} Radio = __decorate([ - wxComponent() -], Radio); -export default Radio; + wxComponent() +], Radio) +export default Radio diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/radio/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/props.js index 291e43d5..18376de8 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/props.js @@ -1,51 +1,51 @@ const props = { - disabled: { - type: null, - value: undefined, - }, - label: { - type: null, - value: false, - }, - marks: { - type: null, - value: {}, - }, - max: { - type: Number, - value: 100, - }, - min: { - type: Number, - value: 0, - }, - range: { - type: Boolean, - value: false, - }, - showExtremeValue: { - type: Boolean, - value: false, - }, - step: { - type: Number, - value: 1, - }, - theme: { - type: String, - value: 'default', - }, - value: { - type: null, - value: null, - }, - defaultValue: { - type: null, - value: 0, - }, - vertical: { - type: Boolean, - value: false, - }, -}; -export default props; + disabled: { + type: null, + value: undefined, + }, + label: { + type: null, + value: false, + }, + marks: { + type: null, + value: {}, + }, + max: { + type: Number, + value: 100, + }, + min: { + type: Number, + value: 0, + }, + range: { + type: Boolean, + value: false, + }, + showExtremeValue: { + type: Boolean, + value: false, + }, + step: { + type: Number, + value: 1, + }, + theme: { + type: String, + value: 'default', + }, + value: { + type: null, + value: null, + }, + defaultValue: { + type: null, + value: 0, + }, + vertical: { + type: Boolean, + value: false, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/slider.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/slider.js index 65e1e5a5..1e218c01 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/slider.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/slider.js @@ -1,408 +1,417 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import config from '../common/config'; -import { trimSingleValue, trimValue } from './tool'; -import props from './props'; -import { getRect } from '../common/utils'; -import Bus from '../common/bus'; -const { prefix } = config; -const name = `${prefix}-slider`; +import {SuperComponent, wxComponent} from '../common/src/index' +import config from '../common/config' +import {trimSingleValue, trimValue} from './tool' +import props from './props' +import {getRect} from '../common/utils' +import Bus from '../common/bus' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } + function rejected(value) { try { step(generator.throw(value)) } catch (e) { reject(e) } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } + step((generator = generator.apply(thisArg, _arguments || [])).next()) + }) +} + +const {prefix} = config +const name = `${prefix}-slider` let Slider = class Slider extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-bar`, - `${prefix}-class-bar-active`, - `${prefix}-class-bar-disabled`, - `${prefix}-class-cursor`, - ]; - this.options = { - pureDataPattern: /^__/, - }; - this.properties = props; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.data = { - sliderStyles: '', - classPrefix: name, - initialLeft: null, - initialRight: null, - activeLeft: 0, - activeRight: 0, - maxRange: 0, - lineLeft: 0, - lineRight: 0, - dotTopValue: [0, 0], - _value: 0, - blockSize: 20, - isScale: false, - scaleArray: [], - scaleTextArray: [], - prefix, - isVisibleToScreenReader: false, - identifier: [-1, -1], - __inited: false, - }; - this.observers = { - value(newValue) { - this.handlePropsChange(newValue); - }, - _value(newValue) { - this.bus.on('initial', () => this.renderLine(newValue)); - this.toggleA11yTips(); - }, - marks(val) { - this.bus.on('initial', () => this.handleMark(val)); - }, - }; - this.lifetimes = { - created() { - this.bus = new Bus(); - }, - attached() { - const { value } = this.properties; - if (!value) - this.handlePropsChange(0); - this.init(); - this.injectPageScroll(); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-bar`, + `${prefix}-class-bar-active`, + `${prefix}-class-bar-disabled`, + `${prefix}-class-cursor`, + ] + this.options = { + pureDataPattern: /^__/, } - injectPageScroll() { - const { range, vertical } = this.properties; - if (!range || !vertical) - return; - const pages = getCurrentPages() || []; - let curPage = null; - if (pages && pages.length - 1 >= 0) { - curPage = pages[pages.length - 1]; - } - if (!curPage) - return; - const originPageScroll = curPage === null || curPage === void 0 ? void 0 : curPage.onPageScroll; - curPage.onPageScroll = (rest) => { - originPageScroll === null || originPageScroll === void 0 ? void 0 : originPageScroll.call(this, rest); - this.observerScrollTop(rest); - }; + this.properties = props + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.data = { + sliderStyles: '', + classPrefix: name, + initialLeft: null, + initialRight: null, + activeLeft: 0, + activeRight: 0, + maxRange: 0, + lineLeft: 0, + lineRight: 0, + dotTopValue: [0, 0], + _value: 0, + blockSize: 20, + isScale: false, + scaleArray: [], + scaleTextArray: [], + prefix, + isVisibleToScreenReader: false, + identifier: [-1, -1], + __inited: false, } - observerScrollTop(rest) { - const { scrollTop } = rest || {}; - this.pageScrollTop = scrollTop; + this.observers = { + value(newValue) { + this.handlePropsChange(newValue) + }, + _value(newValue) { + this.bus.on('initial', () => this.renderLine(newValue)) + this.toggleA11yTips() + }, + marks(val) { + this.bus.on('initial', () => this.handleMark(val)) + }, } - toggleA11yTips() { - this.setData({ - isVisibleToScreenReader: true, - }); - setTimeout(() => { - this.setData({ - isVisibleToScreenReader: false, - }); - }, 2000); + this.lifetimes = { + created() { + this.bus = new Bus() + }, + attached() { + const {value} = this.properties + if (!value) this.handlePropsChange(0) + this.init() + this.injectPageScroll() + }, } - renderLine(val) { - const { min, max, range } = this.properties; - const { maxRange } = this.data; - if (range) { - const left = (maxRange * (val[0] - Number(min))) / (Number(max) - Number(min)); - const right = (maxRange * (Number(max) - val[1])) / (Number(max) - Number(min)); - this.setLineStyle(left, right); - } - else { - this.setSingleBarWidth(val); - } + } + + injectPageScroll() { + const {range, vertical} = this.properties + if (!range || !vertical) return + const pages = getCurrentPages() || [] + let curPage = null + if (pages && pages.length - 1 >= 0) { + curPage = pages[pages.length - 1] } - triggerValue(value) { - if (this.preval === value) - return; - this.preval = value; - this._trigger('change', { - value: trimValue(value, this.properties), - }); + if (!curPage) return + const originPageScroll = curPage === null || curPage === void 0 ? void 0 : curPage.onPageScroll + curPage.onPageScroll = (rest) => { + originPageScroll === null || originPageScroll === void 0 ? void 0 : originPageScroll.call(this, rest) + this.observerScrollTop(rest) } - handlePropsChange(newValue) { - const value = trimValue(newValue, this.properties); - const setValueAndTrigger = () => { - this.setData({ - _value: value, - }); - }; - if (this.data.maxRange === 0) { - this.init().then(setValueAndTrigger); - return; - } - setValueAndTrigger(); + } + + observerScrollTop(rest) { + const {scrollTop} = rest || {} + this.pageScrollTop = scrollTop + } + + toggleA11yTips() { + this.setData({ + isVisibleToScreenReader: true, + }) + setTimeout(() => { + this.setData({ + isVisibleToScreenReader: false, + }) + }, 2000) + } + + renderLine(val) { + const {min, max, range} = this.properties + const {maxRange} = this.data + if (range) { + const left = (maxRange * (val[0] - Number(min))) / (Number(max) - Number(min)) + const right = (maxRange * (Number(max) - val[1])) / (Number(max) - Number(min)) + this.setLineStyle(left, right) + } else { + this.setSingleBarWidth(val) } - handleMark(marks) { - const calcPos = (arr) => { - const { max, theme } = this.properties; - const { blockSize, maxRange } = this.data; - const margin = theme === 'capsule' ? blockSize / 2 : 0; - return arr.map((item) => ({ - val: item, - left: Math.round((item / Number(max)) * maxRange) + margin, - })); - }; - if ((marks === null || marks === void 0 ? void 0 : marks.length) && Array.isArray(marks)) { - this.setData({ - isScale: true, - scaleArray: calcPos(marks), - scaleTextArray: [], - }); - } - if (Object.prototype.toString.call(marks) === '[object Object]') { - const scaleArray = Object.keys(marks).map((item) => Number(item)); - const scaleTextArray = scaleArray.map((item) => marks[item]); - this.setData({ - isScale: scaleArray.length > 0, - scaleArray: calcPos(scaleArray), - scaleTextArray, - }); - } + } + + triggerValue(value) { + if (this.preval === value) return + this.preval = value + this._trigger('change', { + value: trimValue(value, this.properties), + }) + } + + handlePropsChange(newValue) { + const value = trimValue(newValue, this.properties) + const setValueAndTrigger = () => { + this.setData({ + _value: value, + }) } - setSingleBarWidth(value) { - const { max, min, theme } = this.properties; - const { maxRange, blockSize } = this.data; - const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0; - const percentage = (Number(value) - Number(min)) / (Number(max) - Number(min)); - const width = percentage * maxRange + halfBlock; - this.setData({ - lineBarWidth: `${width}px`, - }); + if (this.data.maxRange === 0) { + this.init().then(setValueAndTrigger) + return } - init() { - return __awaiter(this, void 0, void 0, function* () { - if (this.data.__inited) - return; - const line = yield getRect(this, '#sliderLine'); - const { blockSize } = this.data; - const { theme, vertical } = this.properties; - const halfBlock = Number(blockSize) / 2; - const { top, bottom, right, left } = line; - let maxRange = vertical ? bottom - top : right - left; - let initialLeft = vertical ? top : left; - let initialRight = vertical ? bottom : right; - if (initialLeft === 0 && initialRight === 0) - return; - if (theme === 'capsule') { - maxRange = maxRange - Number(blockSize) - 6; - initialLeft -= halfBlock; - initialRight -= halfBlock; - } - this.setData({ - maxRange, - initialLeft, - initialRight, - __inited: true, - }); - this.bus.emit('initial'); - }); + setValueAndTrigger() + } + + handleMark(marks) { + const calcPos = (arr) => { + const {max, theme} = this.properties + const {blockSize, maxRange} = this.data + const margin = theme === 'capsule' ? blockSize / 2 : 0 + return arr.map((item) => ({ + val: item, + left: Math.round((item / Number(max)) * maxRange) + margin, + })) } - stepValue(value) { - const { step, min, max } = this.properties; - const decimal = String(step).indexOf('.') > -1 ? String(step).length - String(step).indexOf('.') - 1 : 0; - const closestStep = trimSingleValue(Number((Math.round(value / Number(step)) * Number(step)).toFixed(decimal)), Number(min), Number(max)); - return closestStep; + if ((marks === null || marks === void 0 ? void 0 : marks.length) && Array.isArray(marks)) { + this.setData({ + isScale: true, + scaleArray: calcPos(marks), + scaleTextArray: [], + }) } - onSingleLineTap(e) { - const { disabled } = this.properties; - if (disabled) - return; - const isSingleLineTap = this.data.identifier[0] === -1; - if (isSingleLineTap) { - const [touch] = e.changedTouches; - this.data.identifier[0] = touch.identifier; - } - const value = this.getSingleChangeValue(e); - if (isSingleLineTap) { - this.data.identifier[0] = -1; - } - this.triggerValue(value); + if (Object.prototype.toString.call(marks) === '[object Object]') { + const scaleArray = Object.keys(marks).map((item) => Number(item)) + const scaleTextArray = scaleArray.map((item) => marks[item]) + this.setData({ + isScale: scaleArray.length > 0, + scaleArray: calcPos(scaleArray), + scaleTextArray, + }) } - getSingleChangeValue(e) { - const { min, max, theme, vertical } = this.properties; - const { initialLeft, maxRange, blockSize } = this.data; - const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[0]); - const pagePosition = this.getPagePosition(touch); - let offset = 0; - if (theme === 'capsule') { - offset = Number(blockSize); - if (vertical) { - offset *= 2; - } - offset += 6; - } - else if (vertical) { - offset = Number(blockSize); - } - const currentLeft = pagePosition - initialLeft - offset; - let value = 0; - if (currentLeft <= 0) { - value = Number(min); - } - else if (currentLeft >= maxRange) { - value = Number(max); - } - else { - value = (currentLeft / maxRange) * (Number(max) - Number(min)) + Number(min); - } - return this.stepValue(value); + } + + setSingleBarWidth(value) { + const {max, min, theme} = this.properties + const {maxRange, blockSize} = this.data + const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0 + const percentage = (Number(value) - Number(min)) / (Number(max) - Number(min)) + const width = percentage * maxRange + halfBlock + this.setData({ + lineBarWidth: `${width}px`, + }) + } + + init() { + return __awaiter(this, void 0, void 0, function* () { + if (this.data.__inited) return + const line = yield getRect(this, '#sliderLine') + const {blockSize} = this.data + const {theme, vertical} = this.properties + const halfBlock = Number(blockSize) / 2 + const { + top, bottom, right, left + } = line + let maxRange = vertical ? bottom - top : right - left + let initialLeft = vertical ? top : left + let initialRight = vertical ? bottom : right + if (initialLeft === 0 && initialRight === 0) return + if (theme === 'capsule') { + maxRange = maxRange - Number(blockSize) - 6 + initialLeft -= halfBlock + initialRight -= halfBlock + } + this.setData({ + maxRange, + initialLeft, + initialRight, + __inited: true, + }) + this.bus.emit('initial') + }) + } + + stepValue(value) { + const {step, min, max} = this.properties + const decimal = String(step).indexOf('.') > -1 ? String(step).length - String(step).indexOf('.') - 1 : 0 + const closestStep = trimSingleValue(Number((Math.round(value / Number(step)) * Number(step)).toFixed(decimal)), Number(min), Number(max)) + return closestStep + } + + onSingleLineTap(e) { + const {disabled} = this.properties + if (disabled) return + const isSingleLineTap = this.data.identifier[0] === -1 + if (isSingleLineTap) { + const [touch] = e.changedTouches + this.data.identifier[0] = touch.identifier } - convertPosToValue(posValue, dir) { - const { maxRange } = this.data; - const { max, min } = this.properties; - return dir === 0 - ? (posValue / maxRange) * (Number(max) - Number(min)) + Number(min) - : Number(max) - (posValue / maxRange) * (Number(max) - Number(min)); + const value = this.getSingleChangeValue(e) + if (isSingleLineTap) { + this.data.identifier[0] = -1 } - onLineTap(e) { - const { disabled, theme, vertical } = this.properties; - const { initialLeft, initialRight, maxRange, blockSize } = this.data; - if (disabled) - return; - const [touch] = e.changedTouches; - const pagePosition = this.getPagePosition(touch); - const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0; - const currentLeft = pagePosition - initialLeft; - const currentRight = -(pagePosition - initialRight); - if (currentLeft < 0 || currentRight > maxRange + Number(blockSize)) - return; - Promise.all([getRect(this, '#leftDot'), getRect(this, '#rightDot')]).then(([leftDot, rightDot]) => { - const pageScrollTop = this.pageScrollTop || 0; - const leftDotPosition = vertical ? leftDot.top + pageScrollTop : leftDot.left; - const distanceLeft = Math.abs(pagePosition - leftDotPosition - halfBlock); - const rightDotPosition = vertical ? rightDot.top + pageScrollTop : rightDot.left; - const distanceRight = Math.abs(rightDotPosition - pagePosition + halfBlock); - const isMoveLeft = distanceLeft < distanceRight; - let offset = 0; - if (theme === 'capsule') { - offset = Number(blockSize); - if (vertical) { - offset *= 2; - } - offset += 6; - } - else if (vertical) { - offset = Number(blockSize); - } - if (isMoveLeft) { - const left = pagePosition - initialLeft - offset; - const leftValue = this.convertPosToValue(left, 0); - this.triggerValue([this.stepValue(leftValue), this.data._value[1]]); - } - else { - let right = -(pagePosition - initialRight); - if (vertical) { - right += offset / 2; - } - const rightValue = this.convertPosToValue(right, 1); - this.triggerValue([this.data._value[0], this.stepValue(rightValue)]); - } - }); + this.triggerValue(value) + } + + getSingleChangeValue(e) { + const { + min, max, theme, vertical + } = this.properties + const {initialLeft, maxRange, blockSize} = this.data + const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[0]) + const pagePosition = this.getPagePosition(touch) + let offset = 0 + if (theme === 'capsule') { + offset = Number(blockSize) + if (vertical) { + offset *= 2 + } + offset += 6 + } else if (vertical) { + offset = Number(blockSize) } - onTouchStart(e) { - this.triggerEvent('dragstart', { e }); - const [touch] = e.changedTouches; - if (e.currentTarget.id === 'rightDot') { - this.data.identifier[1] = touch.identifier; - } - else { - this.data.identifier[0] = touch.identifier; - } + const currentLeft = pagePosition - initialLeft - offset + let value = 0 + if (currentLeft <= 0) { + value = Number(min) + } else if (currentLeft >= maxRange) { + value = Number(max) + } else { + value = (currentLeft / maxRange) * (Number(max) - Number(min)) + Number(min) } - onTouchMoveLeft(e) { - const { disabled, theme, vertical } = this.properties; - const { initialLeft, _value, blockSize } = this.data; - if (disabled) - return; - const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[0]); - const pagePosition = this.getPagePosition(touch); - let offset = 0; - if (theme === 'capsule') { - offset += Number(blockSize); - } + return this.stepValue(value) + } + + convertPosToValue(posValue, dir) { + const {maxRange} = this.data + const {max, min} = this.properties + return dir === 0 + ? (posValue / maxRange) * (Number(max) - Number(min)) + Number(min) + : Number(max) - (posValue / maxRange) * (Number(max) - Number(min)) + } + + onLineTap(e) { + const {disabled, theme, vertical} = this.properties + const { + initialLeft, initialRight, maxRange, blockSize + } = this.data + if (disabled) return + const [touch] = e.changedTouches + const pagePosition = this.getPagePosition(touch) + const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0 + const currentLeft = pagePosition - initialLeft + const currentRight = -(pagePosition - initialRight) + if (currentLeft < 0 || currentRight > maxRange + Number(blockSize)) return + Promise.all([getRect(this, '#leftDot'), getRect(this, '#rightDot')]).then(([leftDot, rightDot]) => { + const pageScrollTop = this.pageScrollTop || 0 + const leftDotPosition = vertical ? leftDot.top + pageScrollTop : leftDot.left + const distanceLeft = Math.abs(pagePosition - leftDotPosition - halfBlock) + const rightDotPosition = vertical ? rightDot.top + pageScrollTop : rightDot.left + const distanceRight = Math.abs(rightDotPosition - pagePosition + halfBlock) + const isMoveLeft = distanceLeft < distanceRight + let offset = 0 + if (theme === 'capsule') { + offset = Number(blockSize) if (vertical) { - offset += Number(blockSize) + 6; + offset *= 2 } - const currentLeft = pagePosition - initialLeft - offset; - const newData = [..._value]; - const leftValue = this.convertPosToValue(currentLeft, 0); - newData[0] = this.stepValue(leftValue); - this.triggerValue(newData); - } - onTouchMoveRight(e) { - const { disabled, vertical } = this.properties; - const { initialRight, _value, blockSize } = this.data; - if (disabled) - return; - const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[1]); - const pagePosition = this.getPagePosition(touch); - let offset = 0; + offset += 6 + } else if (vertical) { + offset = Number(blockSize) + } + if (isMoveLeft) { + const left = pagePosition - initialLeft - offset + const leftValue = this.convertPosToValue(left, 0) + this.triggerValue([this.stepValue(leftValue), this.data._value[1]]) + } else { + let right = -(pagePosition - initialRight) if (vertical) { - offset += Number(blockSize) / 2 + 6; + right += offset / 2 } - const currentRight = -(pagePosition - initialRight - offset); - const newData = [..._value]; - const rightValue = this.convertPosToValue(currentRight, 1); - newData[1] = this.stepValue(rightValue); - this.triggerValue(newData); + const rightValue = this.convertPosToValue(right, 1) + this.triggerValue([this.data._value[0], this.stepValue(rightValue)]) + } + }) + } + + onTouchStart(e) { + this.triggerEvent('dragstart', {e}) + const [touch] = e.changedTouches + if (e.currentTarget.id === 'rightDot') { + this.data.identifier[1] = touch.identifier + } else { + this.data.identifier[0] = touch.identifier } - setLineStyle(left, right) { - const { theme } = this.properties; - const { blockSize, maxRange } = this.data; - const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0; - const [a, b] = this.data._value; - const cut = (v) => parseInt(v, 10); - this.setData({ - dotTopValue: [a, b], - }); - if (left + right <= maxRange) { - this.setData({ - lineLeft: cut(left + halfBlock), - lineRight: cut(right + halfBlock), - }); - } - else { - this.setData({ - lineLeft: cut(maxRange + halfBlock - right), - lineRight: cut(maxRange - left + halfBlock * 1.5), - }); - } + } + + onTouchMoveLeft(e) { + const {disabled, theme, vertical} = this.properties + const {initialLeft, _value, blockSize} = this.data + if (disabled) return + const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[0]) + const pagePosition = this.getPagePosition(touch) + let offset = 0 + if (theme === 'capsule') { + offset += Number(blockSize) } - onTouchEnd(e) { - this.triggerEvent('dragend', { e, value: this.data._value }); - if (e.currentTarget.id === 'rightDot') { - this.data.identifier[1] = -1; - } - else { - this.data.identifier[0] = -1; - } + if (vertical) { + offset += Number(blockSize) + 6 + } + const currentLeft = pagePosition - initialLeft - offset + const newData = [..._value] + const leftValue = this.convertPosToValue(currentLeft, 0) + newData[0] = this.stepValue(leftValue) + this.triggerValue(newData) + } + + onTouchMoveRight(e) { + const {disabled, vertical} = this.properties + const {initialRight, _value, blockSize} = this.data + if (disabled) return + const touch = e.changedTouches.find((item) => item.identifier === this.data.identifier[1]) + const pagePosition = this.getPagePosition(touch) + let offset = 0 + if (vertical) { + offset += Number(blockSize) / 2 + 6 + } + const currentRight = -(pagePosition - initialRight - offset) + const newData = [..._value] + const rightValue = this.convertPosToValue(currentRight, 1) + newData[1] = this.stepValue(rightValue) + this.triggerValue(newData) + } + + setLineStyle(left, right) { + const {theme} = this.properties + const {blockSize, maxRange} = this.data + const halfBlock = theme === 'capsule' ? Number(blockSize) / 2 : 0 + const [a, b] = this.data._value + const cut = (v) => parseInt(v, 10) + this.setData({ + dotTopValue: [a, b], + }) + if (left + right <= maxRange) { + this.setData({ + lineLeft: cut(left + halfBlock), + lineRight: cut(right + halfBlock), + }) + } else { + this.setData({ + lineLeft: cut(maxRange + halfBlock - right), + lineRight: cut(maxRange - left + halfBlock * 1.5), + }) } - getPagePosition(touch) { - const { pageX, pageY } = touch; - const { vertical } = this.properties; - return vertical ? pageY : pageX; + } + + onTouchEnd(e) { + this.triggerEvent('dragend', {e, value: this.data._value}) + if (e.currentTarget.id === 'rightDot') { + this.data.identifier[1] = -1 + } else { + this.data.identifier[0] = -1 } -}; + } + + getPagePosition(touch) { + const {pageX, pageY} = touch + const {vertical} = this.properties + return vertical ? pageY : pageX + } +} Slider = __decorate([ - wxComponent() -], Slider); -export default Slider; + wxComponent() +], Slider) +export default Slider diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/tool.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/tool.js index 671ab5d0..a9948ff5 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/tool.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/tool.js @@ -1,23 +1,23 @@ export const trimSingleValue = (value, min, max) => { - if (value < min) { - return min; - } - if (value > max) { - return max; - } - return value; -}; + if (value < min) { + return min + } + if (value > max) { + return max + } + return value +} export const trimValue = (value, props) => { - const { min, max, range } = props; - if (range && Array.isArray(value)) { - value[0] = trimSingleValue(value[0], min, max); - value[1] = trimSingleValue(value[1], min, max); - return value[0] <= value[1] ? value : [value[1], value[0]]; - } - if (range) { - return [min, max]; - } - if (!range) { - return trimSingleValue(value, min, max); - } -}; + const {min, max, range} = props + if (range && Array.isArray(value)) { + value[0] = trimSingleValue(value[0], min, max) + value[1] = trimSingleValue(value[1], min, max) + return value[0] <= value[1] ? value : [value[1], value[0]] + } + if (range) { + return [min, max] + } + if (!range) { + return trimSingleValue(value, min, max) + } +} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/slider/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/index.js index a6df66d3..0e23830f 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/index.js @@ -1,3 +1,3 @@ -export * from './props'; -export * from './type'; -export * from './sticky'; +export * from './props' +export * from './type' +export * from './sticky' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/props.js index 6dcdf7c0..7005f1f3 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/props.js @@ -1,18 +1,18 @@ const props = { - container: { - type: null, - }, - disabled: { - type: Boolean, - value: false, - }, - offsetTop: { - type: null, - value: 0, - }, - zIndex: { - type: Number, - value: 99, - }, -}; -export default props; + container: { + type: null, + }, + disabled: { + type: Boolean, + value: false, + }, + offsetTop: { + type: null, + value: 0, + }, + zIndex: { + type: Number, + value: 99, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/sticky.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/sticky.js index a71da333..679d4a61 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/sticky.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/sticky.js @@ -1,116 +1,115 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import props from './props'; -import config from '../common/config'; -import pageScrollMixin from '../mixins/page-scroll'; -import { getRect } from '../common/utils'; -const { prefix } = config; -const name = `${prefix}-sticky`; -const ContainerClass = `.${name}`; +import {SuperComponent, wxComponent} from '../common/src/index' +import props from './props' +import config from '../common/config' +import pageScrollMixin from '../mixins/page-scroll' +import {getRect} from '../common/utils' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-sticky` +const ContainerClass = `.${name}` let Sticky = class Sticky extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`]; - this.properties = props; - this.behaviors = [pageScrollMixin()]; - this.observers = { - 'offsetTop, disabled, container'() { - this.onScroll(); - }, - }; - this.data = { - prefix, - classPrefix: name, - containerStyle: '', - contentStyle: '', - }; - this.methods = { - onScroll(event) { - const { scrollTop } = event || {}; - const { container, offsetTop, disabled } = this.properties; - if (disabled) { - this.setDataAfterDiff({ - isFixed: false, - transform: 0, - }); - return; - } - this.scrollTop = scrollTop || this.scrollTop; - if (typeof container === 'function') { - Promise.all([getRect(this, ContainerClass), this.getContainerRect()]).then(([root, container]) => { - if (!root || !container) - return; - if (offsetTop + root.height > container.height + container.top) { - this.setDataAfterDiff({ - isFixed: false, - transform: container.height - root.height, - }); - } - else if (offsetTop >= root.top) { - this.setDataAfterDiff({ - isFixed: true, - height: root.height, - transform: 0, - }); - } - else { - this.setDataAfterDiff({ isFixed: false, transform: 0 }); - } - }); - return; - } - getRect(this, ContainerClass).then((root) => { - if (!root) - return; - if (offsetTop >= root.top) { - this.setDataAfterDiff({ isFixed: true, height: root.height }); - this.transform = 0; - } - else { - this.setDataAfterDiff({ isFixed: false }); - } - }); - }, - setDataAfterDiff(data) { - const { offsetTop } = this.properties; - const { containerStyle: prevContainerStyle, contentStyle: prevContentStyle } = this.data; - const { isFixed, height, transform } = data; - wx.nextTick(() => { - let containerStyle = ''; - let contentStyle = ''; - if (isFixed) { - containerStyle += `height:${height}px;`; - contentStyle += `position:fixed;top:${offsetTop}px;left:0;right:0;`; - } - if (transform) { - const translate = `translate3d(0, ${transform}px, 0)`; - contentStyle += `-webkit-transform:${translate};transform:${translate};`; - } - if (prevContainerStyle !== containerStyle || prevContentStyle !== contentStyle) { - this.setData({ containerStyle, contentStyle }); - } - this.triggerEvent('scroll', { - scrollTop: this.scrollTop, - isFixed, - }); - }); - }, - getContainerRect() { - const nodesRef = this.properties.container(); - return new Promise((resolve) => nodesRef.boundingClientRect(resolve).exec()); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`, `${prefix}-class-content`] + this.properties = props + this.behaviors = [pageScrollMixin()] + this.observers = { + 'offsetTop, disabled, container': function () { + this.onScroll() + }, } - ready() { - this.onScroll(); + this.data = { + prefix, + classPrefix: name, + containerStyle: '', + contentStyle: '', } -}; + this.methods = { + onScroll(event) { + const {scrollTop} = event || {} + const {container, offsetTop, disabled} = this.properties + if (disabled) { + this.setDataAfterDiff({ + isFixed: false, + transform: 0, + }) + return + } + this.scrollTop = scrollTop || this.scrollTop + if (typeof container === 'function') { + Promise.all([getRect(this, ContainerClass), this.getContainerRect()]).then(([root, container]) => { + if (!root || !container) return + if (offsetTop + root.height > container.height + container.top) { + this.setDataAfterDiff({ + isFixed: false, + transform: container.height - root.height, + }) + } else if (offsetTop >= root.top) { + this.setDataAfterDiff({ + isFixed: true, + height: root.height, + transform: 0, + }) + } else { + this.setDataAfterDiff({isFixed: false, transform: 0}) + } + }) + return + } + getRect(this, ContainerClass).then((root) => { + if (!root) return + if (offsetTop >= root.top) { + this.setDataAfterDiff({isFixed: true, height: root.height}) + this.transform = 0 + } else { + this.setDataAfterDiff({isFixed: false}) + } + }) + }, + setDataAfterDiff(data) { + const {offsetTop} = this.properties + const {containerStyle: prevContainerStyle, contentStyle: prevContentStyle} = this.data + const {isFixed, height, transform} = data + wx.nextTick(() => { + let containerStyle = '' + let contentStyle = '' + if (isFixed) { + containerStyle += `height:${height}px;` + contentStyle += `position:fixed;top:${offsetTop}px;left:0;right:0;` + } + if (transform) { + const translate = `translate3d(0, ${transform}px, 0)` + contentStyle += `-webkit-transform:${translate};transform:${translate};` + } + if (prevContainerStyle !== containerStyle || prevContentStyle !== contentStyle) { + this.setData({containerStyle, contentStyle}) + } + this.triggerEvent('scroll', { + scrollTop: this.scrollTop, + isFixed, + }) + }) + }, + getContainerRect() { + const nodesRef = this.properties.container() + return new Promise((resolve) => nodesRef.boundingClientRect(resolve).exec()) + }, + } + } + + ready() { + this.onScroll() + } +} Sticky = __decorate([ - wxComponent() -], Sticky); -export default Sticky; + wxComponent() +], Sticky) +export default Sticky diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/sticky/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/props.js index c50b1288..63fe3159 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/props.js @@ -1,35 +1,35 @@ const props = { - customValue: { - type: Array, - value: [true, false], - }, - disabled: { - type: null, - value: undefined, - }, - icon: { - type: Array, - value: [], - }, - label: { - type: Array, - value: [], - }, - loading: { - type: Boolean, - value: false, - }, - size: { - type: String, - value: 'medium', - }, - value: { - type: null, - value: null, - }, - defaultValue: { - type: null, - value: null, - }, -}; -export default props; + customValue: { + type: Array, + value: [true, false], + }, + disabled: { + type: null, + value: undefined, + }, + icon: { + type: Array, + value: [], + }, + label: { + type: Array, + value: [], + }, + loading: { + type: Boolean, + value: false, + }, + size: { + type: String, + value: 'medium', + }, + value: { + type: null, + value: null, + }, + defaultValue: { + type: null, + value: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/switch.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/switch.js index 8f9277e2..5736beeb 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/switch.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/switch.js @@ -1,53 +1,57 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { wxComponent, SuperComponent } from '../common/src/index'; -import config from '../common/config'; -import props from './props'; -const { prefix } = config; -const name = `${prefix}-switch`; +import {wxComponent, SuperComponent} from '../common/src/index' +import config from '../common/config' +import props from './props' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-switch` let Switch = class Switch extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = ['t-class', 't-class-label', 't-class-body', 't-class-dot']; - this.behaviors = ['wx://form-field']; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - checked: false, - }; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.observers = { - value(val) { - const [activeValue] = this.data.customValue; - this.setData({ - checked: val === activeValue, - }); - }, - }; - this.methods = { - handleSwitch() { - const { loading, disabled, value, customValue } = this.data; - const [activeValue, inactiveValue] = customValue; - if (loading || disabled) - return; - this._trigger('change', { - value: value === activeValue ? inactiveValue : activeValue, - }); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = ['t-class', 't-class-label', 't-class-body', 't-class-dot'] + this.behaviors = ['wx://form-field'] + this.properties = props + this.data = { + prefix, + classPrefix: name, + checked: false, } -}; + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.observers = { + value(val) { + const [activeValue] = this.data.customValue + this.setData({ + checked: val === activeValue, + }) + }, + } + this.methods = { + handleSwitch() { + const { + loading, disabled, value, customValue + } = this.data + const [activeValue, inactiveValue] = customValue + if (loading || disabled) return + this._trigger('change', { + value: value === activeValue ? inactiveValue : activeValue, + }) + }, + } + } +} Switch = __decorate([ - wxComponent() -], Switch); -export default Switch; + wxComponent() +], Switch) +export default Switch diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/switch/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/props.js index 36216ca4..da797663 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/props.js @@ -1,23 +1,23 @@ const props = { - badgeProps: { - type: Object, - }, - disabled: { - type: Boolean, - value: false, - }, - icon: { - type: null, - }, - label: { - type: String, - value: '', - }, - panel: { - type: String, - }, - value: { - type: null, - }, -}; -export default props; + badgeProps: { + type: Object, + }, + disabled: { + type: Boolean, + value: false, + }, + icon: { + type: null, + }, + label: { + type: String, + value: '', + }, + panel: { + type: String, + }, + value: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/tab-panel.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/tab-panel.js index 22d5c3d0..4367207e 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/tab-panel.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/tab-panel.js @@ -1,62 +1,69 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import props from './props'; -import config from '../common/config'; -const { prefix } = config; -const name = `${prefix}-tab-panel`; +import {SuperComponent, wxComponent} from '../common/src/index' +import props from './props' +import config from '../common/config' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} + +const {prefix} = config +const name = `${prefix}-tab-panel` let TabPanel = class TabPanel extends SuperComponent { - constructor() { - super(...arguments); - this.externalClasses = [`${prefix}-class`]; - this.relations = { - '../tabs/tabs': { - type: 'ancestor', - }, - }; - this.options = { - multipleSlots: true, - }; - this.properties = props; - this.data = { - prefix, - classPrefix: name, - active: false, - hide: true, - id: '', - }; - this.observers = { - 'label, badgeProps, disabled, icon, panel, value'() { - this.update(); - }, - }; + constructor() { + super(...arguments) + this.externalClasses = [`${prefix}-class`] + this.relations = { + '../tabs/tabs': { + type: 'ancestor', + }, } - setId(id) { - this.setData({ id }); + this.options = { + multipleSlots: true, } - getComputedName() { - if (this.properties.value != null) { - return `${this.properties.value}`; - } - return `${this.index}`; + this.properties = props + this.data = { + prefix, + classPrefix: name, + active: false, + hide: true, + id: '', } - update() { - var _a; - (_a = this.$parent) === null || _a === void 0 ? void 0 : _a.updateTabs(); + this.observers = { + 'label, badgeProps, disabled, icon, panel, value': function () { + this.update() + }, } - render(active, parent) { - this.initialized = this.initialized || active; - this.setData({ - active, - hide: !parent.data.animation && !active, - }); + } + + setId(id) { + this.setData({id}) + } + + getComputedName() { + if (this.properties.value != null) { + return `${this.properties.value}` } -}; + return `${this.index}` + } + + update() { + let _a; + (_a = this.$parent) === null || _a === void 0 ? void 0 : _a.updateTabs() + } + + render(active, parent) { + this.initialized = this.initialized || active + this.setData({ + active, + hide: !parent.data.animation && !active, + }) + } +} TabPanel = __decorate([ - wxComponent() -], TabPanel); -export default TabPanel; + wxComponent() +], TabPanel) +export default TabPanel diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tab-panel/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/index.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/index.js index 2f91d158..38b9309e 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/index.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/index.js @@ -1,3 +1,3 @@ -export * from './tabs'; -export * from './type'; -export * from './props'; +export * from './tabs' +export * from './type' +export * from './props' diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/props.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/props.js index 9caa438a..53e4c308 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/props.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/props.js @@ -1,43 +1,43 @@ const props = { - animation: { - type: Object, - }, - externalClasses: { - type: Array, - }, - showBottomLine: { - type: Boolean, - value: true, - }, - spaceEvenly: { - type: Boolean, - value: true, - }, - split: { - type: Boolean, - value: true, - }, - sticky: { - type: Boolean, - value: false, - }, - stickyProps: { - type: Object, - }, - swipeable: { - type: Boolean, - value: true, - }, - theme: { - type: String, - value: 'line', - }, - value: { - type: null, - value: null, - }, - defaultValue: { - type: null, - }, -}; -export default props; + animation: { + type: Object, + }, + externalClasses: { + type: Array, + }, + showBottomLine: { + type: Boolean, + value: true, + }, + spaceEvenly: { + type: Boolean, + value: true, + }, + split: { + type: Boolean, + value: true, + }, + sticky: { + type: Boolean, + value: false, + }, + stickyProps: { + type: Object, + }, + swipeable: { + type: Boolean, + value: true, + }, + theme: { + type: String, + value: 'line', + }, + value: { + type: null, + value: null, + }, + defaultValue: { + type: null, + }, +} +export default props diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/tabs.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/tabs.js index 25efd5ab..f8590b27 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/tabs.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/tabs.js @@ -1,287 +1,280 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -import { SuperComponent, wxComponent } from '../common/src/index'; -import props from './props'; -import config from '../common/config'; -import touch from '../mixins/touch'; -import { getRect, uniqueFactory } from '../common/utils'; -import { getObserver } from '../common/wechat'; -const { prefix } = config; -const name = `${prefix}-tabs`; -const getUniqueID = uniqueFactory('tabs'); +import {SuperComponent, wxComponent} from '../common/src/index' +import props from './props' +import config from '../common/config' +import touch from '../mixins/touch' +import {getRect, uniqueFactory} from '../common/utils' +import {getObserver} from '../common/wechat' + +const __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + const c = arguments.length; let r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc; let + d + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') r = Reflect.decorate(decorators, target, key, desc) + else for (let i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r + return c > 3 && r && Object.defineProperty(target, key, r), r +} +const __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value) }) } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)) } catch (e) { reject(e) } } + function rejected(value) { try { step(generator.throw(value)) } catch (e) { reject(e) } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected) } + step((generator = generator.apply(thisArg, _arguments || [])).next()) + }) +} + +const {prefix} = config +const name = `${prefix}-tabs` +const getUniqueID = uniqueFactory('tabs') let Tabs = class Tabs extends SuperComponent { - constructor() { - super(...arguments); - this.options = { - pureDataPattern: /^currentLabels$/, - }; - this.behaviors = [touch]; - this.externalClasses = [ - `${prefix}-class`, - `${prefix}-class-item`, - `${prefix}-class-active`, - `${prefix}-class-track`, - `${prefix}-class-content`, - ]; - this.relations = { - '../tab-panel/tab-panel': { - type: 'descendant', - linked(target) { - this.children.push(target); - this.initChildId(); - target.index = this.children.length - 1; - this.updateTabs(); - }, - unlinked(target) { - this.children = this.children.filter((item) => item.index !== target.index); - this.updateTabs(() => this.setTrack()); - this.initChildId(); - }, - }, - }; - this.properties = props; - this.controlledProps = [ - { - key: 'value', - event: 'change', - }, - ]; - this.observers = { - value(name) { - if (name !== this.getCurrentName()) { - this.setCurrentIndexByName(name); - } - }, - }; - this.data = { - prefix, - classPrefix: name, - tabs: [], - currentLabels: [], - currentIndex: -1, - trackStyle: '', - offset: 0, - scrollLeft: 0, - tabID: '', - placement: 'top', - }; - this.lifetimes = { - created() { - this.children = this.children || []; - }, - attached() { - wx.nextTick(() => { - this.setTrack(); - }); - getRect(this, `.${name}`).then((rect) => { - this.containerWidth = rect.width; - }); - this.setData({ - tabID: getUniqueID(), - }); - }, - }; - this.methods = { - onScroll(e) { - const { scrollLeft } = e.detail; - this.setData({ - scrollLeft, - }); - }, - updateTabs(cb) { - const { children } = this; - const tabs = children.map((child) => child.data); - tabs.forEach((item) => { - if (typeof item.icon === 'string') { - item.icon = { name: item.icon }; - } - }); - this.setData({ tabs }, cb); - this.setCurrentIndexByName(this.properties.value); - }, - setCurrentIndexByName(name) { - const { children } = this; - const index = children.findIndex((child) => child.getComputedName() === `${name}`); - if (index > -1) { - this.setCurrentIndex(index); - } - }, - setCurrentIndex(index) { - if (index <= -1 || index >= this.children.length) - return; - const Labels = []; - this.children.forEach((child, idx) => { - const isActive = index === idx; - if (isActive !== child.data.active || !child.initialized) { - child.render(isActive, this); - } - Labels.push(child.data.label); - }); - const { currentIndex, currentLabels } = this.data; - if (currentIndex === index && currentLabels.join('') === Labels.join('')) - return; - this.setData({ - currentIndex: index, - currentLabels: Labels, - }, () => { - this.setTrack(); - }); - }, - getCurrentName() { - if (this.children) { - const activeTab = this.children[this.data.currentIndex]; - if (activeTab) { - return activeTab.getComputedName(); - } - } - }, - calcScrollOffset(containerWidth, targetLeft, targetWidth, offset) { - return offset + targetLeft - (1 / 2) * containerWidth + targetWidth / 2; - }, - getTabHeight() { - return getRect(this, `.${name}`); - }, - getTrackSize() { - return new Promise((resolve, reject) => { - if (this.trackWidth) { - resolve(this.trackWidth); - return; - } - getRect(this, `.${prefix}-tabs__track`) - .then((res) => { - if (res) { - this.trackWidth = res.width; - resolve(this.trackWidth); - } - }) - .catch(reject); - }); - }, - setTrack() { - return __awaiter(this, void 0, void 0, function* () { - const { children } = this; - if (!children) - return; - const { currentIndex } = this.data; - if (currentIndex <= -1) - return; - try { - const res = yield getRect(this, `.${prefix}-tabs__item`, true); - const rect = res[currentIndex]; - if (!rect) - return; - let count = 0; - let distance = 0; - let totalSize = 0; - res.forEach((item) => { - if (count < currentIndex) { - distance += item.width; - count += 1; - } - totalSize += item.width; - }); - if (this.containerWidth) { - const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.data.scrollLeft); - const maxOffset = totalSize - this.containerWidth; - this.setData({ - offset: Math.min(Math.max(offset, 0), maxOffset), - }); - } - else if (!this._hasObserved) { - this._hasObserved = true; - getObserver(this, `.${name}`).then(() => this.setTrack()); - } - if (this.data.theme === 'line') { - const trackLineWidth = yield this.getTrackSize(); - distance += (rect.width - trackLineWidth) / 2; - } - this.setData({ - trackStyle: `-webkit-transform: translateX(${distance}px); + constructor() { + super(...arguments) + this.options = { + pureDataPattern: /^currentLabels$/, + } + this.behaviors = [touch] + this.externalClasses = [ + `${prefix}-class`, + `${prefix}-class-item`, + `${prefix}-class-active`, + `${prefix}-class-track`, + `${prefix}-class-content`, + ] + this.relations = { + '../tab-panel/tab-panel': { + type: 'descendant', + linked(target) { + this.children.push(target) + this.initChildId() + target.index = this.children.length - 1 + this.updateTabs() + }, + unlinked(target) { + this.children = this.children.filter((item) => item.index !== target.index) + this.updateTabs(() => this.setTrack()) + this.initChildId() + }, + }, + } + this.properties = props + this.controlledProps = [ + { + key: 'value', + event: 'change', + }, + ] + this.observers = { + value(name) { + if (name !== this.getCurrentName()) { + this.setCurrentIndexByName(name) + } + }, + } + this.data = { + prefix, + classPrefix: name, + tabs: [], + currentLabels: [], + currentIndex: -1, + trackStyle: '', + offset: 0, + scrollLeft: 0, + tabID: '', + placement: 'top', + } + this.lifetimes = { + created() { + this.children = this.children || [] + }, + attached() { + wx.nextTick(() => { + this.setTrack() + }) + getRect(this, `.${name}`).then((rect) => { + this.containerWidth = rect.width + }) + this.setData({ + tabID: getUniqueID(), + }) + }, + } + this.methods = { + onScroll(e) { + const {scrollLeft} = e.detail + this.setData({ + scrollLeft, + }) + }, + updateTabs(cb) { + const {children} = this + const tabs = children.map((child) => child.data) + tabs.forEach((item) => { + if (typeof item.icon === 'string') { + item.icon = {name: item.icon} + } + }) + this.setData({tabs}, cb) + this.setCurrentIndexByName(this.properties.value) + }, + setCurrentIndexByName(name) { + const {children} = this + const index = children.findIndex((child) => child.getComputedName() === `${name}`) + if (index > -1) { + this.setCurrentIndex(index) + } + }, + setCurrentIndex(index) { + if (index <= -1 || index >= this.children.length) return + const Labels = [] + this.children.forEach((child, idx) => { + const isActive = index === idx + if (isActive !== child.data.active || !child.initialized) { + child.render(isActive, this) + } + Labels.push(child.data.label) + }) + const {currentIndex, currentLabels} = this.data + if (currentIndex === index && currentLabels.join('') === Labels.join('')) return + this.setData({ + currentIndex: index, + currentLabels: Labels, + }, () => { + this.setTrack() + }) + }, + getCurrentName() { + if (this.children) { + const activeTab = this.children[this.data.currentIndex] + if (activeTab) { + return activeTab.getComputedName() + } + } + }, + calcScrollOffset(containerWidth, targetLeft, targetWidth, offset) { + return offset + targetLeft - (1 / 2) * containerWidth + targetWidth / 2 + }, + getTabHeight() { + return getRect(this, `.${name}`) + }, + getTrackSize() { + return new Promise((resolve, reject) => { + if (this.trackWidth) { + resolve(this.trackWidth) + return + } + getRect(this, `.${prefix}-tabs__track`) + .then((res) => { + if (res) { + this.trackWidth = res.width + resolve(this.trackWidth) + } + }) + .catch(reject) + }) + }, + setTrack() { + return __awaiter(this, void 0, void 0, function* () { + const {children} = this + if (!children) return + const {currentIndex} = this.data + if (currentIndex <= -1) return + try { + const res = yield getRect(this, `.${prefix}-tabs__item`, true) + const rect = res[currentIndex] + if (!rect) return + let count = 0 + let distance = 0 + let totalSize = 0 + res.forEach((item) => { + if (count < currentIndex) { + distance += item.width + count += 1 + } + totalSize += item.width + }) + if (this.containerWidth) { + const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.data.scrollLeft) + const maxOffset = totalSize - this.containerWidth + this.setData({ + offset: Math.min(Math.max(offset, 0), maxOffset), + }) + } else if (!this._hasObserved) { + this._hasObserved = true + getObserver(this, `.${name}`).then(() => this.setTrack()) + } + if (this.data.theme === 'line') { + const trackLineWidth = yield this.getTrackSize() + distance += (rect.width - trackLineWidth) / 2 + } + this.setData({ + trackStyle: `-webkit-transform: translateX(${distance}px); transform: translateX(${distance}px); `, - }); - } - catch (err) { - this.triggerEvent('error', err); - } - }); - }, - onTabTap(event) { - const { index } = event.currentTarget.dataset; - this.changeIndex(index); - }, - onTouchStart(event) { - if (!this.properties.swipeable) - return; - this.touchStart(event); - }, - onTouchMove(event) { - if (!this.properties.swipeable) - return; - this.touchMove(event); - }, - onTouchEnd() { - if (!this.properties.swipeable) - return; - const { direction, deltaX, offsetX } = this; - const minSwipeDistance = 50; - if (direction === 'horizontal' && offsetX >= minSwipeDistance) { - const index = this.getAvailableTabIndex(deltaX); - if (index !== -1) { - this.changeIndex(index); - } - } - }, - onTouchScroll(event) { - this._trigger('scroll', event.detail); - }, - changeIndex(index) { - const currentTab = this.data.tabs[index]; - const { value, label } = currentTab; - if (!(currentTab === null || currentTab === void 0 ? void 0 : currentTab.disabled) && index !== this.data.currentIndex) { - this._trigger('change', { value, label }); - } - this._trigger('click', { value, label }); - }, - getAvailableTabIndex(deltaX) { - const step = deltaX > 0 ? -1 : 1; - const { currentIndex, tabs } = this.data; - const len = tabs.length; - for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) { - const newIndex = currentIndex + i; - if (newIndex >= 0 && newIndex < len && tabs[newIndex]) { - if (!tabs[newIndex].disabled) { - return newIndex; - } - } - else { - return currentIndex; - } - } - return -1; - }, - }; - } - initChildId() { - this.children.forEach((item, index) => { - item.setId(`${this.data.tabID}_panel_${index}`); - }); + }) + } catch (err) { + this.triggerEvent('error', err) + } + }) + }, + onTabTap(event) { + const {index} = event.currentTarget.dataset + this.changeIndex(index) + }, + onTouchStart(event) { + if (!this.properties.swipeable) return + this.touchStart(event) + }, + onTouchMove(event) { + if (!this.properties.swipeable) return + this.touchMove(event) + }, + onTouchEnd() { + if (!this.properties.swipeable) return + const {direction, deltaX, offsetX} = this + const minSwipeDistance = 50 + if (direction === 'horizontal' && offsetX >= minSwipeDistance) { + const index = this.getAvailableTabIndex(deltaX) + if (index !== -1) { + this.changeIndex(index) + } + } + }, + onTouchScroll(event) { + this._trigger('scroll', event.detail) + }, + changeIndex(index) { + const currentTab = this.data.tabs[index] + const {value, label} = currentTab + if (!(currentTab === null || currentTab === void 0 ? void 0 : currentTab.disabled) && index !== this.data.currentIndex) { + this._trigger('change', {value, label}) + } + this._trigger('click', {value, label}) + }, + getAvailableTabIndex(deltaX) { + const step = deltaX > 0 ? -1 : 1 + const {currentIndex, tabs} = this.data + const len = tabs.length + for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) { + const newIndex = currentIndex + i + if (newIndex >= 0 && newIndex < len && tabs[newIndex]) { + if (!tabs[newIndex].disabled) { + return newIndex + } + } else { + return currentIndex + } + } + return -1 + }, } -}; + } + + initChildId() { + this.children.forEach((item, index) => { + item.setId(`${this.data.tabID}_panel_${index}`) + }) + } +} Tabs = __decorate([ - wxComponent() -], Tabs); -export default Tabs; + wxComponent() +], Tabs) +export default Tabs diff --git a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/type.js b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/type.js index cb0ff5c3..336ce12b 100644 --- a/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/type.js +++ b/miniprogram/packageChatTool/components/tdesign-miniprogram/tabs/type.js @@ -1 +1 @@ -export {}; +export {} diff --git a/miniprogram/packageChatTool/pages/activity_create/index.js b/miniprogram/packageChatTool/pages/activity_create/index.js index 26834fc5..8e2ba99d 100644 --- a/miniprogram/packageChatTool/pages/activity_create/index.js +++ b/miniprogram/packageChatTool/pages/activity_create/index.js @@ -1,5 +1,5 @@ // pages/activity_create/index.js -import { getChatToolInfo } from '../../util' +import {getChatToolInfo} from '../../util' // const defaultShareImage = 'https://p9.itc.cn/q_70/images03/20211124/d7dce66b866c4ccd805190a4925ff707.png' @@ -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) @@ -167,7 +167,7 @@ Page({ chooseParticipant() { const that = this - const { limitNumber, number } = this.data + const {limitNumber, number} = this.data wx.selectGroupMembers({ maxSelectCount: limitNumber ? number : -1, success(res) { @@ -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..feecc996 100644 --- a/miniprogram/packageChatTool/pages/activity_detail/index.js +++ b/miniprogram/packageChatTool/pages/activity_detail/index.js @@ -1,5 +1,5 @@ // pages/activity_create/index.js -import { getChatToolInfo } from '../../util' +import {getChatToolInfo} from '../../util' const roleType = ['unkown', 'owner', 'participant', 'nonParticipant'] @@ -54,7 +54,7 @@ Page({ }, onBack() { - wx.navigateBack({ delta: 1 }) + wx.navigateBack({delta: 1}) }, onRefresh() { @@ -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) } }) }, @@ -96,7 +95,7 @@ Page({ const notSignIn = participant.filter(i => !signIn.includes(i)) - const { groupOpenID, roomid, openid } = groupInfo + const {groupOpenID, roomid, openid} = groupInfo const percent = participant.length ? Math.ceil(signIn.length / participant.length * 100) : 0 const isOwner = creator === openid @@ -155,7 +154,6 @@ Page({ console.info('fetchActivity fail: ', err) }) }) - }, onTabsChange(e) { @@ -166,7 +164,7 @@ Page({ }, notifyNotSignIn() { - const { activityId, notSignIn, activityInfo } = this.data + const {activityId, notSignIn, activityInfo} = this.data if (!activityInfo._id) return wx.notifyGroupMembers({ @@ -182,8 +180,8 @@ Page({ signIn() { const that = this - const { signIn, activityInfo, groupInfo } = this.data - const { roomid, groupOpenID } = groupInfo + const {signIn, activityInfo, groupInfo} = this.data + const {roomid, groupOpenID} = groupInfo if (signIn.includes(groupOpenID)) { wx.showToast({ @@ -203,7 +201,7 @@ Page({ } }).then(resp => { if (resp.result.success) { - const { signIn } = activityInfo + const {signIn} = activityInfo signIn.push(groupOpenID) that.refreshData(activityInfo, groupInfo, false) that.updateChatToolMsg({ @@ -245,7 +243,7 @@ Page({ }, updateChatToolMsg(params = {}) { - const { targetState, parameterList } = params + const {targetState, parameterList} = params // const templateId = '2A84254B945674A2F88CE4970782C402795EB607' // 参与 const templateId = '4A68CBB88A92B0A9311848DBA1E94A199B166463' // 完成 @@ -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, @@ -308,7 +306,7 @@ Page({ }, share() { - const { activityInfo, activityId } = this.data + const {activityInfo, activityId} = this.data if (!activityInfo._id) return wx.cloud.downloadFile({ @@ -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..b5a6a27b 100644 --- a/miniprogram/packageCloud/pages/database/crud/crud.js +++ b/miniprogram/packageCloud/pages/database/crud/crud.js @@ -28,7 +28,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/database/db-permission/db-permission.js b/miniprogram/packageCloud/pages/database/db-permission/db-permission.js index 97cf0750..b6cb047f 100644 --- a/miniprogram/packageCloud/pages/database/db-permission/db-permission.js +++ b/miniprogram/packageCloud/pages/database/db-permission/db-permission.js @@ -47,7 +47,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/database/server-date/server-date.js b/miniprogram/packageCloud/pages/database/server-date/server-date.js index 3401e762..85045c2e 100644 --- a/miniprogram/packageCloud/pages/database/server-date/server-date.js +++ b/miniprogram/packageCloud/pages/database/server-date/server-date.js @@ -31,7 +31,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..5ad38ccd 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,7 +49,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js b/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js index bd2d37f7..cc6f2cbe 100644 --- a/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js +++ b/miniprogram/packageCloud/pages/scf/scf-database/scf-database.js @@ -26,7 +26,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js b/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js index c45b0aaf..51f36a51 100644 --- a/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js +++ b/miniprogram/packageCloud/pages/scf/scf-openapi/scf-openapi.js @@ -26,7 +26,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js b/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js index d123ecdf..365b08c9 100644 --- a/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js +++ b/miniprogram/packageCloud/pages/scf/scf-storage/scf-storage.js @@ -27,7 +27,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..3c4411f7 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 @@ -20,7 +20,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js b/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js index 06f75a94..5836134f 100644 --- a/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js +++ b/miniprogram/packageCloud/pages/storage/delete-file/delete-file.js @@ -23,7 +23,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/storage/download-file/download-file.js b/miniprogram/packageCloud/pages/storage/download-file/download-file.js index c9aa920d..ac524d1f 100644 --- a/miniprogram/packageCloud/pages/storage/download-file/download-file.js +++ b/miniprogram/packageCloud/pages/storage/download-file/download-file.js @@ -27,7 +27,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { 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..6442bc3d 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,7 +28,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js b/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js index 682227ee..5b62ab19 100644 --- a/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js +++ b/miniprogram/packageCloud/pages/storage/upload-file/upload-file.js @@ -24,7 +24,7 @@ Page({ }, onLoad(options) { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js b/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js index 1ee8c6e1..e71f47e9 100644 --- a/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js +++ b/miniprogram/packageCloud/pages/user/user-authentication/user-authentication.js @@ -43,7 +43,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js b/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js index 07616752..6b74d91e 100644 --- a/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js +++ b/miniprogram/packageComponent/pages/canvas/canvas-2d/canvas-2d.js @@ -135,7 +135,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageComponent/pages/canvas/canvas/canvas.js b/miniprogram/packageComponent/pages/canvas/canvas/canvas.js index b671fd4e..653d8640 100644 --- a/miniprogram/packageComponent/pages/canvas/canvas/canvas.js +++ b/miniprogram/packageComponent/pages/canvas/canvas/canvas.js @@ -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..bda521b8 100644 --- a/miniprogram/packageComponent/pages/canvas/webgl/webgl.js +++ b/miniprogram/packageComponent/pages/canvas/webgl/webgl.js @@ -129,7 +129,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageComponent/pages/content/icon/icon.js b/miniprogram/packageComponent/pages/content/icon/icon.js index 11c19901..67ef8516 100644 --- a/miniprogram/packageComponent/pages/content/icon/icon.js +++ b/miniprogram/packageComponent/pages/content/icon/icon.js @@ -15,7 +15,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageComponent/pages/content/progress/progress.js b/miniprogram/packageComponent/pages/content/progress/progress.js index 679b7190..ce9001a7 100644 --- a/miniprogram/packageComponent/pages/content/progress/progress.js +++ b/miniprogram/packageComponent/pages/content/progress/progress.js @@ -15,7 +15,7 @@ Page({ }, onLoad() { this.setData({ - theme: wx.getSystemInfoSync().theme || 'light' + theme: getApp().globalData.theme || 'light' }) if (wx.onThemeChange) { diff --git a/miniprogram/packageComponent/pages/content/progress/progress.json b/miniprogram/packageComponent/pages/content/progress/progress.json index ebb652bd..91527d10 100644 --- a/miniprogram/packageComponent/pages/content/progress/progress.json +++ b/miniprogram/packageComponent/pages/content/progress/progress.json @@ -1,4 +1,5 @@ { "navigationBarTitleText": "progress", - "navigationStyle": "custom" + "navigationStyle": "default", + "renderer": "webview" } diff --git a/miniprogram/packageComponent/pages/content/progress/progress.wxml b/miniprogram/packageComponent/pages/content/progress/progress.wxml index 15cf1fc4..f9e2388d 100644 --- a/miniprogram/packageComponent/pages/content/progress/progress.wxml +++ b/miniprogram/packageComponent/pages/content/progress/progress.wxml @@ -3,7 +3,6 @@