Repository: googlemaps/js-three Branch: main Commit: 19874f82388d Files: 42 Total size: 98.9 KB Directory structure: gitextract_evmxhh3o/ ├── .babelrc ├── .eslintignore ├── .eslintrc.json ├── .github/ │ ├── CODEOWNERS │ ├── bundlewatch.config.json │ ├── dependabot.yml │ ├── sync-repo-settings.yaml │ └── workflows/ │ ├── bundlewatch.yml │ ├── codeql.yml │ ├── dependabot.yml │ ├── docs.yml │ ├── e2e.yml │ ├── package.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── .prettierrc ├── .releaserc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── e2e/ │ └── README.md ├── examples/ │ ├── anchor.ts │ ├── basic.ts │ ├── config.ts │ ├── hemispheres.ts │ ├── orientation.ts │ └── raycasting.ts ├── jest.config.js ├── package.json ├── rollup.config.examples.js ├── rollup.config.js ├── src/ │ ├── __tests__/ │ │ ├── __utils__/ │ │ │ └── createWebGlContext.ts │ │ ├── three.test.ts │ │ └── util.test.ts │ ├── index.ts │ ├── three.ts │ └── util.ts ├── tsconfig.examples.json ├── tsconfig.json └── typedoc.cjs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc ================================================ { "presets": [ [ "@babel/env", { "targets": { "browsers": "ie>=11, > 0.25%, not dead" }, "corejs": "3.6", "useBuiltIns": "usage" } ] ] } ================================================ FILE: .eslintignore ================================================ bazel-* coverage/ dist/ docs/ lib/ node_modules/ public/ ================================================ FILE: .eslintrc.json ================================================ { "extends": ["eslint:recommended", "plugin:prettier/recommended"], "parserOptions": { "ecmaVersion": 12, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "plugins": ["jest"], "rules": { "no-var": 2, "prefer-arrow-callback": 2 }, "overrides": [ { "files": ["*.ts", "*.tsx"], "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": ["plugin:@typescript-eslint/recommended"], "rules": { "@typescript-eslint/ban-ts-comment": 0, "@typescript-eslint/ban-types": 1, "@typescript-eslint/no-empty-function": 1, "@typescript-eslint/member-ordering": 1, "@typescript-eslint/explicit-member-accessibility": [ 1, { "accessibility": "explicit", "overrides": { "accessors": "explicit", "constructors": "no-public", "methods": "explicit", "properties": "explicit", "parameterProperties": "explicit" } } ] } } ], "env": { "browser": true, "node": true, "es6": true, "jest/globals": true }, "globals": { "google": "readonly" } } ================================================ FILE: .github/CODEOWNERS ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners .github/ @googlemaps/admin ================================================ FILE: .github/bundlewatch.config.json ================================================ { "files": [ { "path": "dist/index.*.js" } ], "ci": { "trackBranches": ["main"], "repoBranchBase": "main" } } ================================================ FILE: .github/dependabot.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. version: 2 updates: - package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" ================================================ FILE: .github/sync-repo-settings.yaml ================================================ # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # https://github.com/googleapis/repo-automation-bots/tree/main/packages/sync-repo-settings rebaseMergeAllowed: true squashMergeAllowed: true mergeCommitAllowed: false deleteBranchOnMerge: true branchProtectionRules: - pattern: main isAdminEnforced: false requiresStrictStatusChecks: false requiredStatusCheckContexts: - 'cla/google' - 'test' - 'snippet-bot check' - 'header-check' requiredApprovingReviewCount: 1 requiresCodeOwnerReviews: true - pattern: master isAdminEnforced: false requiresStrictStatusChecks: false requiredStatusCheckContexts: - 'cla/google' - 'test' - 'snippet-bot check' - 'header-check' requiredApprovingReviewCount: 1 requiresCodeOwnerReviews: true permissionRules: - team: admin permission: admin ================================================ FILE: .github/workflows/bundlewatch.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Bundlewatch on: push: branches: - main pull_request: types: [synchronize, opened] jobs: bundlewatch: runs-on: ubuntu-latest env: CI_BRANCH_BASE: main steps: - uses: actions/checkout@v2 - uses: jackyef/bundlewatch-gh-action@b9753bc9b3ea458ff21069eaf6206e01e046f0b5 with: build-script: npm i bundlewatch-github-token: ${{ secrets.BUNDLEWATCH_GITHUB_TOKEN }} bundlewatch-config: .github/bundlewatch.config.json ================================================ FILE: .github/workflows/codeql.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [main] pull_request: # The branches below must be a subset of the branches above branches: [main] schedule: - cron: "0 13 * * *" jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: ["javascript"] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - name: Checkout repository uses: actions/checkout@v2 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 ================================================ FILE: .github/workflows/dependabot.yml ================================================ # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Dependabot on: pull_request permissions: contents: write jobs: dependabot: runs-on: ubuntu-latest if: ${{ github.actor == 'dependabot[bot]' }} env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.SYNCED_GITHUB_TOKEN_REPO}} steps: - name: approve run: gh pr review --approve "$PR_URL" - name: merge run: gh pr merge --auto --squash --delete-branch "$PR_URL" ================================================ FILE: .github/workflows/docs.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Docs on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/cache@v2 with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- - run: | npm i npm run docs - uses: peaceiris/actions-gh-pages@v3 if: github.ref == 'refs/heads/main' with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs user_name: 'googlemaps-bot' user_email: 'googlemaps-bot@users.noreply.github.com' commit_message: ${{ github.event.head_commit.message }} ================================================ FILE: .github/workflows/e2e.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: e2e on: push: schedule: - cron: "0 12 * * *" jobs: chrome: runs-on: ubuntu-latest services: hub: image: selenium/standalone-chrome volumes: - ${{ github.workspace }}:${{ github.workspace }} ports: - 4444:4444 steps: - uses: actions/checkout@v2 - run: npm i - run: npm run test:e2e firefox: runs-on: ubuntu-latest services: hub: image: selenium/standalone-firefox volumes: - ${{ github.workspace }}:${{ github.workspace }} ports: - 4444:4444 steps: - uses: actions/checkout@v2 - run: npm i - run: npm run test:e2e env: BROWSER: firefox ================================================ FILE: .github/workflows/package.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Package on: - push - pull_request jobs: package: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: npm i - uses: jpoehnelt/verify-npm-files-action@main with: keys: | types main module ================================================ FILE: .github/workflows/release.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Release on: push: branches: - main concurrency: release jobs: build: runs-on: ubuntu-latest steps: - uses: actions/setup-node@v3 with: node-version: '16' - name: Checkout uses: actions/checkout@v3 with: token: ${{ secrets.SYNCED_GITHUB_TOKEN_REPO }} - uses: actions/cache@v2 with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- - name: Test run: | npm i npm run lint npm test - name: Release uses: cycjimmy/semantic-release-action@v3 with: semantic_version: 19 extra_plugins: | @semantic-release/commit-analyzer@^9 semantic-release-interval @semantic-release/release-notes-generator@^10 @semantic-release/git @semantic-release/github@^8 @semantic-release/npm@^9 @googlemaps/semantic-release-config semantic-release-npm-deprecate env: GH_TOKEN: ${{ secrets.SYNCED_GITHUB_TOKEN_REPO }} NPM_TOKEN: ${{ secrets.NPM_WOMBAT_TOKEN }} RUNNER_DEBUG: 1 ================================================ FILE: .github/workflows/test.yml ================================================ # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/cache@v2 with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- - run: npm i - run: npm run lint - run: npm test - uses: codecov/codecov-action@v1 ================================================ FILE: .gitignore ================================================ node_modules dist/ .npmrc **/docs # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # next.js build output .next # nuxt.js build output .nuxt # gatsby files .cache/ public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 # User-specific stuff .idea/**/workspace.xml .idea/**/tasks.xml .idea/**/usage.statistics.xml .idea/**/dictionaries .idea/**/shelf # Generated files .idea/**/contentModel.xml # Sensitive or high-churn files .idea/**/dataSources/ .idea/**/dataSources.ids .idea/**/dataSources.local.xml .idea/**/sqlDataSources.xml .idea/**/dynamic.xml .idea/**/uiDesigner.xml .idea/**/dbnavigator.xml # Gradle .idea/**/gradle.xml .idea/**/libraries # Gradle and Maven with auto-import # When using Gradle or Maven with auto-import, you should exclude module files, # since they will be recreated, and may cause churn. Uncomment if using # auto-import. # .idea/modules.xml # .idea/*.iml # .idea/modules # *.iml # *.ipr # CMake cmake-build-*/ # Mongo Explorer plugin .idea/**/mongoSettings.xml # File-based project format *.iws # IntelliJ out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Cursive Clojure plugin .idea/replstate.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties # Editor-based Rest Client .idea/httpRequests # Android studio 3.1+ serialized cache file .idea/caches/build_file_checksums.ser # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # Windows thumbnail cache files Thumbs.db Thumbs.db:encryptable ehthumbs.db ehthumbs_vista.db # Dump file *.stackdump # Folder config file [Dd]esktop.ini # Recycle Bin used on file shares $RECYCLE.BIN/ # Windows Installer files *.cab *.msi *.msix *.msm *.msp # Windows shortcuts *.lnk .vscode ================================================ FILE: .prettierrc ================================================ { "trailingComma": "es5" } ================================================ FILE: .releaserc ================================================ extends: "@googlemaps/semantic-release-config" ================================================ FILE: CONTRIBUTING.md ================================================ # How to become a contributor and submit your own code 1. Submit an issue describing your proposed change to the repo in question. 1. The repo owner will respond to your issue promptly. 1. Fork the desired repo, develop and test your code changes. 1. Ensure that your code adheres to the existing style in the code to which you are contributing. 1. Ensure that your code has an appropriate set of tests which all pass. 1. Title your pull request following [Conventional Commits](https://www.conventionalcommits.org/) styling. 1. Submit a pull request. ## Running the tests 1. Install dependencies: npm i 1. Run lint npm run lint npm run format # will fix some issues 1. Run the tests: # Run unit tests. npm test ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Google Maps ThreeJS Overlay View and Utilities [![npm](https://img.shields.io/npm/v/@googlemaps/three)](https://www.npmjs.com/package/@googlemaps/three) ![Build](https://github.com/googlemaps/js-three/workflows/Test/badge.svg) ![Release](https://github.com/googlemaps/js-three/workflows/Release/badge.svg) [![codecov](https://codecov.io/gh/googlemaps/js-three/branch/main/graph/badge.svg)](https://codecov.io/gh/googlemaps/js-three) ![GitHub contributors](https://img.shields.io/github/contributors/googlemaps/js-three?color=green) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![](https://github.com/jpoehnelt/in-solidarity-bot/raw/main/static//badge-flat.png)](https://github.com/apps/in-solidarity) [![Discord](https://img.shields.io/discord/676948200904589322?color=6A7EC2&logo=discord&logoColor=ffffff)](https://discord.gg/jRteCzP) ## Description Add [three.js](https://threejs.org) objects to Google Maps Platform JS. The library provides a `ThreeJSOverlayView` class extending `google.maps.WebGLOverlayView` and utility functions for converting geo-coordinates (latitude/longitude) to vectors in the coordinate system used by three.js. ## Install Available via npm as the package [@googlemaps/three](https://www.npmjs.com/package/@googlemaps/three). ``` npm i @googlemaps/three ``` Alternatively you can load the package directly to the html document using unpkg or other CDNs. In this case, make sure to load three.js before loading this library: ``` ``` When adding via unpkg, the package can be accessed as `google.maps.plugins.three`. A version can be specified by using `https://unpkg.com/@googlemaps/three@VERSION/dist/...`. The third option to use it is via ES-Module imports, similar to how the three.js examples work. For this, you first need to specify an [importmap](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap) (example using unpkg.com, but it works the same way with any other CDN or self-hosted files): ```html ``` In order to support browsers that don't yet implement importmap, you can use the [es-module-shims package](https://github.com/guybedford/es-module-shims). After that, you can use three.js and the ThreeJSOverlayView like you would when using a bundler. ```html ``` ## Documentation Checkout the reference [documentation](https://googlemaps.github.io/js-three/index.html). ### Coordinates, Projection and Anchor-Points The coordinate system within the three.js scene (so-called 'world coordinates') is a right-handed coordinate system in z-up orientation. The y-axis is pointing true north, and the x-axis is pointing east. The units are meters. So the point `new Vector3(0, 50, 10)` is 10 meters above ground and 50 meters east of the specified anchor point. This anchor-point and orientation can be set in the constructor, or by using the `setAnchor()` and `setUpAxis()`-methods (be aware that all object-positions in your scene depend on the anchor-point and orientation, so they have to be recomputed when either of them is changed): ```typescript import { ThreeJSOverlayView } from "@googlemaps/three"; const overlay = new ThreeJSOverlayView({ anchor: { lat: 37.7793, lng: -122.4192, altitude: 0 }, upAxis: "Y", }); overlay.setAnchor({ lat: 35.680432, lng: 139.769013, altitude: 0 }); overlay.setUpAxis("Z"); // can also be specified as Vector3: overlay.setUpAxis(new Vector3(0, 0, 1)); ``` > The default up-axis used in this library is the z-axis (+x is east > and +y is north), which is different from the y-up orientation normally > used in three. All computations on the GPU related to the position use float32 numbers, which limits the possible precision to about 7 decimal digits. Because of this, we cannot use a global reference system and still have the precision to show details in the meters to centimeters range. This is where the anchor point is important. The anchor specifies the geo-coordinates (lat/lng/altitude) where the origin of the world-space coordinate system is, and you should always define it close to where the objects are placed in the scene - unless of course you are only working with large-scale (city-sized) objects distributed globally. Another reason why setting the anchor close to the objects in the scene is generally a good idea: In the mercator map-projection used in Google Maps, the scaling of meters is only accurate in regions close to the equator. This can be compensated for by applying a scale factor that depends on the latitude of the anchor. This scale factor is factored into the coordinate calculations in WebGlOverlayView based on the latitude of the anchor. #### Converting coordinates When you need more than just a single georeferenced object in your scene, you need to compute the world-space position for those coordinates. The ThreeJSOverlayView class provides a helper function for this conversion that takes the current `anchor` and `upAxis` into account: ```typescript const coordinates = { lat: 12.34, lng: 56.78 }; const position: Vector3 = overlay.latLngAltitudeToVector3(coordinates); // alternative: pass the Vector3 to write the position // to as the second parameter, so to set the position of a mesh: overlay.latLngAltitudeToVector3(coordinates, mesh.position); ``` ### Raycasting and Interactions If you want to add interactivity to any three.js content, you typically have to implement raycasting. We took care of that for you, and the ThreeJSOverlayView provides a method `overlay.raycast()` for this. To make use of it, you first have to keep track of mouse movements on the map: ```js import { Vector2 } from "three"; // ... const mapDiv = map.getDiv(); const mousePosition = new Vector2(); map.addListener("mousemove", (ev) => { const { domEvent } = ev; const { left, top, width, height } = mapDiv.getBoundingClientRect(); const x = domEvent.clientX - left; const y = domEvent.clientY - top; mousePosition.x = 2 * (x / width) - 1; mousePosition.y = 1 - 2 * (y / height); // since the actual raycasting is performed when the next frame is // rendered, we have to make sure that it will be called for the next frame. overlay.requestRedraw(); }); ``` With the mouse position being always up to date, you can then use the `raycast()` function in the `onBeforeDraw` callback. In this example, we change the color of the object under the cursor: ```js const DEFAULT_COLOR = 0xffffff; const HIGHLIGHT_COLOR = 0xff0000; let highlightedObject = null; overlay.onBeforeDraw = () => { const intersections = overlay.raycast(mousePosition); if (highlightedObject) { highlightedObject.material.color.setHex(DEFAULT_COLOR); } if (intersections.length === 0) return; highlightedObject = intersections[0].object; highlightedObject.material.color.setHex(HIGHLIGHT_COLOR); }; ``` The full examples can be found in [`./examples/raycasting.ts`](./examples/raycasting.ts). ## Example The following example provides a skeleton for adding objects to the map with this library. ```js import * as THREE from "three"; import { ThreeJSOverlayView, latLngToVector3 } from "@googlemaps/three"; // when loading via UMD, remove the imports and use this instead: // const { ThreeJSOverlayView, latLngToVector3 } = google.maps.plugins.three; const map = new google.maps.Map(document.getElementById("map"), mapOptions); const overlay = new ThreeJSOverlayView({ map, upAxis: "Y", anchor: mapOptions.center, }); // create a box mesh const box = new THREE.Mesh( new THREE.BoxGeometry(10, 50, 10), new THREE.MeshMatcapMaterial() ); // move the box up so the origin of the box is at the bottom box.geometry.translateY(25); // set position at center of map box.position.copy(overlay.latLngAltitudeToVector3(mapOptions.center)); // add box mesh to the scene overlay.scene.add(box); // rotate the box using requestAnimationFrame const animate = () => { box.rotateY(THREE.MathUtils.degToRad(0.1)); requestAnimationFrame(animate); }; // start animation loop requestAnimationFrame(animate); ``` This adds a box to the map. threejs box on map ## Demos View the package in action: - [Basic Example](https://googlemaps.github.io/js-three/public/basic/) - [Anchor Example](https://googlemaps.github.io/js-three/public/anchor/) - [Orientation Example](https://googlemaps.github.io/js-three/public/orientation/) ================================================ FILE: SECURITY.md ================================================ # Report a security issue To report a security issue, please use https://g.co/vulnz. We use https://g.co/vulnz for our intake, and do coordination and disclosure here on GitHub (including using GitHub Security Advisory). The Google Security Team will respond within 5 working days of your report on g.co/vulnz. To contact us about other bugs, please open an issue on GitHub. > **Note**: This file is synchronized from the https://github.com/googlemaps/.github repository. ================================================ FILE: e2e/README.md ================================================ ================================================ FILE: examples/anchor.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LOADER_OPTIONS, MAP_ID } from "./config"; import { ThreeJSOverlayView, WORLD_SIZE } from "../src"; import { Loader } from "@googlemaps/js-api-loader"; import { AxesHelper } from "three"; const mapOptions = { center: { lat: 45, lng: 0, }, mapId: MAP_ID, zoom: 5, heading: -45, tilt: 45, }; new Loader(LOADER_OPTIONS).load().then(() => { const map = new google.maps.Map(document.getElementById("map"), mapOptions); const overlay = new ThreeJSOverlayView({ anchor: { ...mapOptions.center, altitude: 0 }, map, }); overlay.scene.add(new AxesHelper(WORLD_SIZE)); }); ================================================ FILE: examples/basic.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LOADER_OPTIONS, MAP_ID } from "./config"; import { ThreeJSOverlayView } from "../src"; import { Loader } from "@googlemaps/js-api-loader"; import { BoxGeometry, MathUtils, Mesh, MeshMatcapMaterial } from "three"; const mapOptions = { center: { lng: -122.343787, lat: 47.607465, }, mapId: MAP_ID, zoom: 15, heading: 45, tilt: 67, }; new Loader(LOADER_OPTIONS).load().then(() => { // create the map and ThreeJS Overlay const map = new google.maps.Map(document.getElementById("map"), mapOptions); const overlay = new ThreeJSOverlayView({ map }); // Create a box mesh const box = new Mesh( new BoxGeometry(100, 200, 500), new MeshMatcapMaterial() ); // set position at center of map const pos = overlay.latLngAltitudeToVector3(mapOptions.center); box.position.copy(pos); // set position vertically box.position.z = 25; // add box mesh to the scene overlay.scene.add(box); // rotate the box using requestAnimationFrame const animate = () => { box.rotateZ(MathUtils.degToRad(0.1)); requestAnimationFrame(animate); }; requestAnimationFrame(animate); }); ================================================ FILE: examples/config.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LoaderOptions } from "@googlemaps/js-api-loader"; export const MAP_ID = "7b9a897acd0a63a4"; export const LOADER_OPTIONS: LoaderOptions = { apiKey: "AIzaSyD8xiaVPWB02OeQkJOenLiJzdeUHzlhu00", version: "beta", libraries: [], }; ================================================ FILE: examples/hemispheres.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LOADER_OPTIONS, MAP_ID } from "./config"; import { ThreeJSOverlayView } from "../src"; import { Loader } from "@googlemaps/js-api-loader"; import { BoxGeometry, Mesh, MeshMatcapMaterial } from "three"; const mapOptions = { center: { lng: 0, lat: 0, }, mapId: MAP_ID, zoom: 4, tilt: 67, }; new Loader(LOADER_OPTIONS).load().then(() => { // create the map and overlay const map = new google.maps.Map(document.getElementById("map"), mapOptions); const overlay = new ThreeJSOverlayView({ map }); [ { lat: 45, lng: -90 }, { lat: 45, lng: 90 }, { lat: -45, lng: -90 }, { lat: -45, lng: 90 }, ].forEach((latLng: google.maps.LatLngLiteral) => { // create a box mesh with origin on the ground, in z-up orientation const geometry = new BoxGeometry(10, 50, 10) .translate(0, 25, 0) .rotateX(Math.PI / 2); const box = new Mesh(geometry, new MeshMatcapMaterial()); // make it huge box.scale.multiplyScalar(10000); // set position at center of map overlay.latLngAltitudeToVector3(latLng, box.position); // add box mesh to the scene overlay.scene.add(box); }); }); ================================================ FILE: examples/orientation.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LOADER_OPTIONS, MAP_ID } from "./config"; import { ThreeJSOverlayView, WORLD_SIZE } from "../src"; import { Loader } from "@googlemaps/js-api-loader"; import { AxesHelper, Scene } from "three"; const mapOptions = { center: { lat: 0, lng: 0, }, mapId: MAP_ID, zoom: 5, heading: -45, tilt: 45, }; new Loader(LOADER_OPTIONS).load().then(() => { const map = new google.maps.Map(document.getElementById("map"), mapOptions); const scene = new Scene(); scene.add(new AxesHelper(WORLD_SIZE)); new ThreeJSOverlayView({ scene, map }); }); ================================================ FILE: examples/raycasting.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { LOADER_OPTIONS } from "./config"; import { ThreeJSOverlayView } from "../src"; import { Loader } from "@googlemaps/js-api-loader"; import { AxesHelper, CylinderGeometry, GridHelper, MathUtils, Mesh, MeshMatcapMaterial, Vector2, } from "three"; // the corners of the field in the Levi’s Stadium in Santa Clara const coordinates = [ { lng: -121.9702904, lat: 37.4034362 }, { lng: -121.9698018, lat: 37.4027095 }, { lng: -121.9693109, lat: 37.402918 }, { lng: -121.969804, lat: 37.4036465 }, ]; const center = { lng: -121.9698032, lat: 37.4031777, altitude: 0 }; const DEFAULT_COLOR = 0xffffff; const HIGHLIGHT_COLOR = 0xff0000; const mapOptions = { center, mapId: "7057886e21226ff7", zoom: 18, tilt: 67.5, disableDefaultUI: true, backgroundColor: "transparent", gestureHandling: "greedy", }; new Loader(LOADER_OPTIONS).load().then(() => { // create the map and overlay const map = new google.maps.Map(document.getElementById("map"), mapOptions); const overlay = new ThreeJSOverlayView({ map, anchor: center, upAxis: "Y" }); const mapDiv = map.getDiv(); const mousePosition = new Vector2(); map.addListener("mousemove", (ev: google.maps.MapMouseEvent) => { const domEvent = ev.domEvent as MouseEvent; const { left, top, width, height } = mapDiv.getBoundingClientRect(); const x = domEvent.clientX - left; const y = domEvent.clientY - top; mousePosition.x = 2 * (x / width) - 1; mousePosition.y = 1 - 2 * (y / height); // since the actual raycasting is performed when the next frame is // rendered, we have to make sure that it will be called for the next frame. overlay.requestRedraw(); }); // grid- and axes helpers to help with the orientation const grid = new GridHelper(1); grid.rotation.y = MathUtils.degToRad(28.1); grid.scale.set(48.8, 0, 91.44); overlay.scene.add(grid); overlay.scene.add(new AxesHelper(20)); const meshes = coordinates.map((p) => { const mesh = new Mesh( new CylinderGeometry(2, 1, 20, 24, 1), new MeshMatcapMaterial() ); mesh.geometry.translate(0, mesh.geometry.parameters.height / 2, 0); overlay.latLngAltitudeToVector3(p, mesh.position); overlay.scene.add(mesh); return mesh; }); let highlightedObject: (typeof meshes)[number] | null = null; overlay.onBeforeDraw = () => { const intersections = overlay.raycast(mousePosition, meshes, { recursive: false, }); if (highlightedObject) { // when there's a previously highlighted object, reset the highlighting highlightedObject.material.color.setHex(DEFAULT_COLOR); } if (intersections.length === 0) { // reset default cursor when no object is under the cursor map.setOptions({ draggableCursor: null }); highlightedObject = null; return; } // change the color of the object and update the map-cursor to indicate // the object is clickable. highlightedObject = intersections[0].object; highlightedObject.material.color.setHex(HIGHLIGHT_COLOR); map.setOptions({ draggableCursor: "pointer" }); }; }); ================================================ FILE: jest.config.js ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export default { roots: ["/src"], preset: "ts-jest", testPathIgnorePatterns: ["/dist/", "/__utils__/"], testEnvironment: "jsdom", setupFilesAfterEnv: ["jest-extended/all"], }; ================================================ FILE: package.json ================================================ { "name": "@googlemaps/three", "version": "4.0.18", "type": "module", "keywords": [ "google", "maps", "webgl", "threejs" ], "homepage": "https://github.com/googlemaps/js-three", "bugs": { "url": "https://github.com/googlemaps/js-three/issues" }, "repository": { "type": "git", "url": "https://github.com/googlemaps/js-three.git" }, "license": "Apache-2.0", "author": "Justin Poehnelt", "source": "src/index.ts", "main": "dist/index.umd.js", "exports": { ".": { "import": { "types": "./dist/index.d.ts", "default": "./dist/index.esm.js" }, "require": "./dist/index.umd.js", "umd": "./dist/index.umd.js", "browser": "./dist/index.esm.js" } }, "unpkg": "dist/index.min.js", "module": "dist/index.esm.js", "types": "dist/index.d.ts", "files": [ "/src", "/dist" ], "scripts": { "build:examples": "rm -rf public && rollup -c rollup.config.examples.js", "docs": "typedoc src/index.ts && npm run build:examples && cp -r dist docs/dist && cp -r public docs/public", "format": "eslint . --fix", "lint": "eslint .", "prepare": "rm -rf dist && rollup -c", "start": "run-p start:*", "start:rollup": "rollup -c rollup.config.examples.js -w --no-watch.clearScreen", "start:server": "http-server ./public", "test": "jest --coverage=true src/*", "test:e2e": "jest --passWithNoTests e2e/*" }, "peerDependencies": { "three": "*" }, "devDependencies": { "@babel/preset-env": "^7.25.7", "@babel/preset-modules": "^0.1.6", "@babel/runtime-corejs3": "^7.25.7", "@googlemaps/jest-mocks": "^2.21.4", "@googlemaps/js-api-loader": "^1.16.8", "@rollup/plugin-babel": "^6.0.4", "@rollup/plugin-commonjs": "^26.0.1", "@rollup/plugin-html": "^1.0.3", "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^15.2.4", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.6", "@types/d3-random": "^3.0.3", "@types/google.maps": "^3.58.1", "@types/jest": "^29.5.14", "@types/proj4": "^2.5.5", "@types/selenium-webdriver": "^4.1.25", "@types/stats.js": "^0.17.3", "@types/three": "^0.156.0", "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^6.19.1", "core-js": "^3.37.1", "d3-random": "^3.0.1", "eslint": "^8.57.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-jest": "^28.9.0", "eslint-plugin-prettier": "^5.1.3", "geckodriver": "^5.0.0", "http-server": "^14.1.1", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "jest-extended": "^4.0.2", "jest-webgl-canvas-mock": "^2.5.3", "npm-run-all": "^4.1.5", "prettier": "^3.3.3", "rollup": "^4.22.4", "selenium-webdriver": "^4.23.0", "three": "^0.161.0", "ts-jest": "^29.2.5", "typedoc": "^0.25.13", "typescript": "^5.4.5" }, "publishConfig": { "access": "public", "registry": "https://wombat-dressing-room.appspot.com" } } ================================================ FILE: rollup.config.examples.js ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import fs from "node:fs"; import path from "node:path"; import * as url from "node:url"; import html, { makeHtmlAttributes } from "@rollup/plugin-html"; import commonjs from "@rollup/plugin-commonjs"; import jsonNodeResolve from "@rollup/plugin-json"; import { nodeResolve } from "@rollup/plugin-node-resolve"; import typescript from "@rollup/plugin-typescript"; const template = ({ attributes, files, meta, publicPath, title }) => { const scripts = (files.js || []) .map(({ fileName }) => { const attrs = makeHtmlAttributes(attributes.script); return ``; }) .join("\n"); const links = (files.css || []) .map(({ fileName }) => { const attrs = makeHtmlAttributes(attributes.link); return ``; }) .join("\n"); const metas = meta .map((input) => { const attrs = makeHtmlAttributes(input); return ``; }) .join("\n"); return ` ${metas} ${title} ${links}
${scripts} `; }; const typescriptOptions = { tsconfig: "tsconfig.examples.json", compilerOptions: { sourceMap: true, inlineSources: true, }, }; const dirname = url.fileURLToPath(new URL(".", import.meta.url)); const examples = fs .readdirSync(path.join(dirname, "examples")) .filter((f) => f !== "config.ts") .map((f) => f.slice(0, f.length - 3)); export default examples.map((name) => ({ input: `examples/${name}.ts`, plugins: [ typescript(typescriptOptions), commonjs(), nodeResolve(), jsonNodeResolve(), ], output: { dir: `public/${name}`, sourcemap: "inline", plugins: [ html({ fileName: `index.html`, title: `@googlemaps/three: ${name}`, template, }), ], manualChunks: (id) => { if (id.includes("node_modules")) { return "vendor"; } }, }, })); ================================================ FILE: rollup.config.js ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { babel } from "@rollup/plugin-babel"; import commonjs from "@rollup/plugin-commonjs"; import terser from "@rollup/plugin-terser"; import typescript from "@rollup/plugin-typescript"; import { nodeResolve } from "@rollup/plugin-node-resolve"; const babelOptions = { extensions: [".js", ".ts"], babelHelpers: "bundled", }; const terserOptions = { output: { comments: "some" } }; export default [ { input: "src/index.ts", plugins: [ typescript({ tsconfig: "./tsconfig.json", declarationDir: "./" }), commonjs(), babel(babelOptions), nodeResolve(), terser(terserOptions), ], external: ["three"], output: [ { file: "dist/index.umd.js", format: "umd", sourcemap: true, name: "google.maps.plugins.three", globals: { three: "THREE", }, }, { file: "dist/index.min.js", format: "iife", sourcemap: true, name: "google.maps.plugins.three", globals: { three: "THREE", }, }, ], }, { input: "src/index.ts", plugins: [ typescript({ tsconfig: "./tsconfig.json", declarationDir: "./" }), commonjs(), babel(babelOptions), nodeResolve(), terser(terserOptions), ], external: ["three"], output: { file: "dist/index.dev.js", format: "iife", sourcemap: true, name: "google.maps.plugins.three", globals: { three: "THREE", }, }, }, { input: "src/index.ts", external: ["three"], plugins: [ typescript({ tsconfig: "./tsconfig.json", declarationDir: "./" }), babel({ presets: ["@babel/preset-modules"], babelrc: false, extensions: [".js", ".ts"], babelHelpers: "bundled", }), terser(terserOptions), ], output: { file: "dist/index.esm.js", sourcemap: true, format: "esm", }, }, ]; ================================================ FILE: src/__tests__/__utils__/createWebGlContext.ts ================================================ /** * Copyright 2021 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // using 'jest-webgl-canvas-mock' as intended as a setup-script in the jest // configuration causes an error 'TypeError: Cannot redefine property: window' // in newer node-version (last known working version is 18.13.0), which is why // we do the initialization manually here. // @ts-ignore import registerWebglMock from "jest-webgl-canvas-mock/lib/window.js"; /** * Creates a mocked WebGL 1.0 context (based on the one provided by * the jest-webgl-canvas-mock package) three.js can work with. */ export function createWebGlContext() { registerWebglMock(window); const gl = new WebGLRenderingContext(); const glParameters: Record = { [gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS]: 8, [gl.VERSION]: "WebGL 1.0 (OpenGL ES 2.0 Chromium)", [gl.SCISSOR_BOX]: [0, 0, 100, 100], [gl.VIEWPORT]: [0, 0, 100, 100], }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const glExtensions: Record = { EXT_blend_minmax: {}, }; jest.spyOn(gl, "getContextAttributes").mockReturnValue({}); jest.spyOn(gl, "getParameter").mockImplementation((key) => glParameters[key]); jest.spyOn(gl, "getShaderPrecisionFormat").mockImplementation(() => ({ rangeMin: 127, rangeMax: 127, precision: 23, })); const getExtensionOrig = gl.getExtension; jest.spyOn(gl, "getExtension").mockImplementation((id) => { return glExtensions[id] || getExtensionOrig(id); }); const canvas = document.createElement("canvas"); canvas.width = 200; canvas.height = 100; // eslint-disable-next-line @typescript-eslint/no-explicit-any (gl as any).canvas = canvas; return gl; } ================================================ FILE: src/__tests__/three.test.ts ================================================ /** * Copyright 2021 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable @typescript-eslint/explicit-member-accessibility */ // prevent "WARNING: Multiple instances of Three.js being imported.” when // importing three.js Object.defineProperty(window, "__THREE__", { get: () => null, set: () => null, configurable: false, }); import { ThreeJSOverlayView, ThreeJSOverlayViewOptions } from "../three"; import * as util from "../util"; import { BoxGeometry, Camera, Group, Light, Matrix4, Mesh, Object3D, PerspectiveCamera, RaycasterParameters, Scene, Vector2, Vector3, Vector4, WebGLRenderer, } from "three"; import "jest-extended"; import { initialize, Map } from "@googlemaps/jest-mocks"; import { createWebGlContext } from "./__utils__/createWebGlContext"; // setup mocked dependencies jest.mock("../util"); beforeEach(() => { initialize(); google.maps.WebGLOverlayView = jest.fn().mockImplementation(() => { return new (class extends google.maps.MVCObject { getMap = jest.fn(); setMap = jest.fn(); requestRedraw = jest.fn(); requestStateUpdate = jest.fn(); addListener = jest.fn().mockImplementation(() => { return { remove: jest.fn() } as google.maps.MapsEventListener; }); })(); }); }); afterEach(() => { jest.restoreAllMocks(); }); describe("basic functions", () => { test("instantiates with defaults", () => { const overlay = new ThreeJSOverlayView(); expect(overlay["overlay"]).toBeDefined(); expect(overlay["camera"]).toBeInstanceOf(PerspectiveCamera); expect(overlay.scene).toBeInstanceOf(Scene); // required hooks must be defined expect(overlay["overlay"].onAdd).toBeDefined(); expect(overlay["overlay"].onRemove).toBeDefined(); expect(overlay["overlay"].onContextLost).toBeDefined(); expect(overlay["overlay"].onContextRestored).toBeDefined(); expect(overlay["overlay"].onDraw).toBeDefined(); }); test("instantiates with map and calls setMap", () => { const map = new Map( document.createElement("div"), {} ) as unknown as google.maps.Map; const overlay = new ThreeJSOverlayView({ map, }); expect(overlay["overlay"].setMap).toHaveBeenCalledWith(map); }); test("setMap is called on overlay", () => { const map = new Map( document.createElement("div"), {} ) as unknown as google.maps.Map; const overlay = new ThreeJSOverlayView(); overlay.setMap(map); expect(overlay["overlay"].setMap).toHaveBeenCalledWith(map); }); test("getMap is called on overlay", () => { const overlay = new ThreeJSOverlayView(); overlay.getMap(); expect(overlay["overlay"].getMap).toHaveBeenCalledWith(); }); test("addListener is called on overlay", () => { const overlay = new ThreeJSOverlayView(); const handler = jest.fn(); const eventName = "foo"; expect(overlay.addListener(eventName, handler)).toBeDefined(); expect(overlay["overlay"].addListener).toHaveBeenCalledWith( eventName, handler ); }); }); describe("MVCObject interface", () => { let overlay: ThreeJSOverlayView; let webglOverlay: google.maps.WebGLOverlayView; beforeEach(() => { overlay = new ThreeJSOverlayView(); webglOverlay = overlay["overlay"]; }); test.each([ ["bindTo", "eventName", () => void 0, "targetKey", true], ["get", "key"], ["notify", "key"], ["set", "key", "value"], ["setValues", { key: "value" }], ["unbind", "key"], ["unbindAll"], ] as const)( "method '%s' is forwarded to overlay", (method: keyof google.maps.MVCObject, ...args) => { overlay[method].call(overlay, ...args); expect(webglOverlay[method]).toHaveBeenCalledWith(...args); } ); }); describe("WebGLOverlayView interface", () => { let overlay: ThreeJSOverlayView; let gl: WebGLRenderingContext; let transformer: google.maps.CoordinateTransformer; const projMatrixArray = new Float64Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, ]); beforeEach(() => { overlay = new ThreeJSOverlayView(); gl = createWebGlContext(); transformer = { fromLatLngAltitude: jest.fn(() => projMatrixArray), getCameraParams: jest.fn(), }; }); test("onContextRestored creates the renderer", () => { overlay.onContextRestored({ gl }); const renderer: WebGLRenderer = overlay["renderer"]; expect(renderer).toBeDefined(); const viewport = renderer.getViewport(new Vector4()); expect(viewport.x).toEqual(0); expect(viewport.y).toEqual(0); expect(viewport.width).toEqual(gl.canvas.width); expect(viewport.height).toEqual(gl.canvas.height); }); test("onDraw renders the scene and resets the state", () => { overlay.onContextRestored({ gl }); const renderer: WebGLRenderer = overlay["renderer"]; let scene: Object3D, camera: Camera; const renderSpy = jest .spyOn(renderer, "render") .mockImplementation((s, c) => { scene = s; camera = c; }); const resetStateSpy = jest.spyOn(renderer, "resetState"); overlay.onDraw({ gl, transformer }); expect(renderSpy).toHaveBeenCalled(); expect(scene).toBe(overlay.scene); expect(camera.projectionMatrix).toEqual( new Matrix4().fromArray(projMatrixArray) ); expect(resetStateSpy).toHaveBeenCalledAfter(renderSpy); }); test("onBeforeDraw gets called before render", () => { overlay.onContextRestored({ gl }); const renderer: WebGLRenderer = overlay["renderer"]; const renderSpy = jest .spyOn(renderer, "render") .mockImplementation(() => void 0); overlay.onBeforeDraw = jest.fn(); overlay.onDraw({ gl, transformer, }); expect(overlay.onBeforeDraw).toHaveBeenCalled(); expect(overlay.onBeforeDraw).toHaveBeenCalledBefore(renderSpy); }); test("onContextLost disposes of renderer", () => { overlay.onContextRestored({ gl }); const renderer: WebGLRenderer = overlay["renderer"]; const disposeSpy = jest.spyOn(renderer, "dispose"); overlay.onContextLost(); expect(disposeSpy).toHaveBeenCalled(); expect(overlay["renderer"]).toBeNull(); }); test("requestRedraw is forwarded to overlay", () => { overlay.requestRedraw(); expect(overlay["overlay"].requestRedraw).toHaveBeenCalledWith(); }); test("requestStateUpdate is forwarded to overlay", () => { overlay.requestStateUpdate(); expect(overlay["overlay"].requestStateUpdate).toHaveBeenCalledWith(); }); }); describe("setUpAxis() / scene orientation", () => { const latLngAlt = { lat: 0, lng: 0, altitude: 10 }; beforeEach(() => { const mockedUtil = util as jest.Mocked; mockedUtil.latLngToVector3Relative.mockImplementation( (p, r, target = new Vector3()) => { return target.set(1, 2, 3); } ); }); test.each([ [undefined, { x: 1, y: 2, z: 3 }], ["Z", { x: 1, y: 2, z: 3 }], ["Y", { x: 1, y: 3, z: -2 }], [new Vector3(1, 0, 0), { x: 3, y: 2, z: -1 }], ])("upAxis: %s", (upAxis, expectedCoords) => { const overlay = new ThreeJSOverlayView({ upAxis: upAxis as ThreeJSOverlayViewOptions["upAxis"], }); const v3 = overlay.latLngAltitudeToVector3(latLngAlt); expect(v3.x).toBeCloseTo(expectedCoords.x, 8); expect(v3.y).toBeCloseTo(expectedCoords.y, 8); expect(v3.z).toBeCloseTo(expectedCoords.z, 8); }); test("error for invalid upAxis values", () => { const mock = jest.spyOn(console, "warn").mockImplementation(() => void 0); const overlay = new ThreeJSOverlayView({ upAxis: "a" as ThreeJSOverlayViewOptions["upAxis"], }); expect(mock).toHaveBeenCalled(); // check that the default z-up is used const v3 = overlay.latLngAltitudeToVector3(latLngAlt); expect(v3.x).toBeCloseTo(1, 8); expect(v3.y).toBeCloseTo(2, 8); expect(v3.z).toBeCloseTo(3, 8); }); }); describe("latLngAltitudeToVector3()", () => { let mockedUtil: jest.Mocked; beforeEach(() => { mockedUtil = jest.mocked(util); const { latLngToVector3Relative } = mockedUtil; latLngToVector3Relative.mockImplementation( (p, r, target = new Vector3()) => { return target.set(1, 2, 3); } ); }); test("calls util-functions", () => { const overlay = new ThreeJSOverlayView({ anchor: { lat: 5, lng: 6, altitude: 7 }, }); const p = { lat: 0, lng: 0, altitude: 0 }; const v3 = overlay.latLngAltitudeToVector3(p); expect(mockedUtil.latLngToVector3Relative).toHaveBeenCalled(); expect(v3).toEqual(new Vector3(1, 2, 3)); }); test("writes value to target parameter", () => { const overlay = new ThreeJSOverlayView({ anchor: { lat: 5, lng: 6, altitude: 7 }, }); const p = { lat: 0, lng: 0, altitude: 0 }; const t = new Vector3(); const v3 = overlay.latLngAltitudeToVector3(p, t); expect(mockedUtil.latLngToVector3Relative).toHaveBeenCalled(); expect(v3).toBe(t); expect(t).toEqual(new Vector3(1, 2, 3)); }); }); describe("addDefaultLighting()", () => { test("lights are added to the default scene", () => { const overlay = new ThreeJSOverlayView(); const lights: Light[] = []; overlay.scene.traverse((o) => { if ((o as Light).isLight) lights.push(o as Light); }); expect(lights).not.toHaveLength(0); }); test("addDefaultLighting:false", () => { const overlay = new ThreeJSOverlayView({ addDefaultLighting: false }); const lights: Light[] = []; overlay.scene.traverse((o) => { if ((o as Light).isLight) lights.push(o as Light); }); expect(lights).toHaveLength(0); }); }); describe("raycast()", () => { let overlay: ThreeJSOverlayView; let camera: PerspectiveCamera; let box: Mesh; // these values were taken from a running application and are known to work const projMatrix = [ 0.024288994132302996, -0.0001544860884193919, -0.00004410021260124961, -0.00004410021260124961, 6.275603421503094e-20, 0.017096574772793482, -0.002943529080808796, -0.002943529080808796, -0.00028262805230606344, -0.01327650198026164, -0.0037899629741724055, -0.0037899629741724055, -0.10144748239547549, 0.2775102128618734, 0.4125525158446316, 1.079219172577191, ]; const boxPosition = new Vector3(0.12366377626911729, 0, 52.06138372088319); const mouseHitPosition = new Vector2(-0.131, -0.464); beforeEach(() => { overlay = new ThreeJSOverlayView(); // this could be done by providing a mocked CoordinateTransformer // to the onDraw function, but this is arguably easier (although // it's not ideal to access protected members) camera = overlay["camera"]; camera.projectionMatrix.fromArray(projMatrix); box = new Mesh(new BoxGeometry()); box.position.copy(boxPosition); }); test("returns an empty array for an empty scene", () => { const res = overlay.raycast(new Vector2(0, 0)); expect(res).toEqual([]); }); test("returns correct results in a known to work setting", () => { overlay.scene.add(box); box.updateMatrixWorld(true); // check for no hit at [0,0] expect(overlay.raycast(new Vector2(0, 0))).toEqual([]); let res; // we know where the box would be rendered res = overlay.raycast(mouseHitPosition); expect(res).toHaveLength(1); expect(res[0].object).toBe(box); // check that it ignores {recursive:false} here and returns the same result const res2 = overlay.raycast(mouseHitPosition, { recursive: false }); expect(res2).toEqual(res); // test calls with explicit object-list res = overlay.raycast(mouseHitPosition, [box], { recursive: false }); expect(res).toEqual(res); const box2 = new Mesh(new BoxGeometry()); res = overlay.raycast(mouseHitPosition, [box2]); expect(res).toEqual([]); // test recursion const g = new Group(); g.add(box); res = overlay.raycast(mouseHitPosition, [g], { recursive: false }); expect(res).toEqual([]); }); test("sets and restores raycaster parameters", () => { const raycaster = overlay["raycaster"]; const origParams = {} as unknown as RaycasterParameters; const customParams = {} as unknown as RaycasterParameters; let currParams = origParams; let intersectParams = null; const setParamsMock = jest.fn((v) => (currParams = v)); const getParamsMock = jest.fn(() => origParams); jest.spyOn(raycaster, "intersectObjects").mockImplementation(() => { intersectParams = currParams; return []; }); Object.defineProperty(raycaster, "params", { get: getParamsMock, set: setParamsMock, }); overlay.scene.add(box); box.updateMatrixWorld(true); overlay.raycast(mouseHitPosition, { raycasterParameters: customParams }); expect(setParamsMock).toHaveBeenCalledTimes(2); const [[arg1], [arg2]] = setParamsMock.mock.calls; expect(arg1).toBe(customParams); expect(arg2).toBe(origParams); expect(intersectParams).toBe(customParams); }); }); ================================================ FILE: src/__tests__/util.test.ts ================================================ /** * Copyright 2021 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { initialize } from "@googlemaps/jest-mocks"; import { latLngToXY, latLngToVector3Relative, toLatLngAltitudeLiteral, xyToLatLng, } from "../util"; beforeEach(() => { initialize(); }); describe("toLatLngAltitudeLiteral()", () => { test.each([ ["LatLngLiteral", { lat: 10, lng: 20 }, { lat: 10, lng: 20, altitude: 0 }], [ "LatLngAltitudeLiteral", { lat: 10, lng: 20, altitude: 30 }, { lat: 10, lng: 20, altitude: 30 }, ], ["LatLng", { lat: 10, lng: 20 }, { lat: 10, lng: 20, altitude: 0 }], [ "LatLngAltitude", { lat: 10, lng: 20, altitude: 30 }, { lat: 10, lng: 20, altitude: 30 }, ], ] as const)("toLatLngAltitudeLiteral: %p", (type, json, output) => { let input: Parameters[0] = json; if (type === "LatLng" || type === "LatLngAltitude") { input = new google.maps[type]({ lat: 0, lng: 0 }); (input as google.maps.LatLng).toJSON = jest.fn(() => json); } expect(toLatLngAltitudeLiteral(input)).toEqual(output); }); }); test.each([ [ { lng: 0, lat: 0 }, { x: 0, y: 0 }, ], [ { lng: -90, lat: 45 }, { x: -10007559.105973555, y: 5615239.936637378 }, ], [ { lng: 90, lat: -45 }, { x: 10007559.105973555, y: -5615239.936637378 }, ], [ { lng: 90, lat: 45 }, { x: 10007559.105973555, y: 5615239.936637378 }, ], [ { lng: -90, lat: -45 }, { x: -10007559.105973555, y: -5615239.936637378 }, ], [ { lng: 151.2093, lat: -33.8688 }, { x: 16813733.4125, y: -4006716.49009 }, ], ])( "latLngToXY and xyToLatLng are correct for %p", (latLng: google.maps.LatLngLiteral, expected: { x: number; y: number }) => { const [x, y] = latLngToXY(latLng); expect(x).toBeCloseTo(expected.x); expect(y).toBeCloseTo(expected.y); const { lat, lng } = xyToLatLng([x, y]); expect(lat).toBeCloseTo(latLng.lat); expect(lng).toBeCloseTo(latLng.lng); } ); test.each([ // 0 same { latLng: { lat: 0, lng: 0 }, reference: { lat: 0, lng: 0 }, relative: { x: 0, y: 0 }, }, // 1 northwest of reference { latLng: { lat: 0, lng: 0 }, reference: { lat: -1, lng: 1 }, relative: { x: -111178.17, y: 111183.81, }, }, // 2 northeast of reference { latLng: { lat: 0, lng: 2 }, reference: { lat: -1, lng: 1 }, relative: { x: 111178.17, y: 111183.81, }, }, // 3 southeast of reference { latLng: { lat: -2, lng: 2 }, reference: { lat: -1, lng: 1 }, relative: { x: 111178.17, y: -111217.69, }, }, // 4 southwest of reference { latLng: { lat: -2, lng: 0 }, reference: { lat: -1, lng: 1 }, relative: { x: -111178.17, y: -111217.69, }, }, { latLng: { lat: 48.861168, lng: 2.324197 }, reference: { lat: 48.862676, lng: 2.319095 }, relative: { x: 373.22, y: -167.68, }, }, ])( "latLngToVector3Relative is correct: %# %j", ({ latLng, reference, relative }) => { const vector = latLngToVector3Relative( { ...latLng, altitude: 0 }, { ...reference, altitude: 0 } ); expect(vector.x).toBeCloseTo(relative.x, 2); expect(vector.y).toBeCloseTo(relative.y, 2); expect(vector.z).toBeCloseTo(0, 2); } ); ================================================ FILE: src/index.ts ================================================ /** * Copyright 2021 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export * from "./three"; export * from "./util"; ================================================ FILE: src/three.ts ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { DirectionalLight, Euler, HemisphereLight, Intersection, MathUtils, Matrix4, Object3D, PCFSoftShadowMap, PerspectiveCamera, Quaternion, Raycaster, RaycasterParameters, REVISION, Scene, Vector2, Vector3, WebGLRenderer, } from "three"; import { latLngToVector3Relative, toLatLngAltitudeLiteral } from "./util"; import type { LatLngTypes } from "./util"; // Since r162, the sRGBEncoding constant is no longer exported from three. // The value is kept here to keep compatibility with older three.js versions. // This will be removed with the next major release. const sRGBEncoding = 3001; const DEFAULT_UP = new Vector3(0, 0, 1); export interface RaycastOptions { /** * Set to true to also test children of the specified objects for * intersections. * * @default false */ recursive?: boolean; /** * Update the inverse-projection-matrix before casting the ray (set this * to false if you need to run multiple raycasts for the same frame). * * @default true */ updateMatrix?: boolean; /** * Additional parameters to pass to the three.js raycaster. * * @see https://threejs.org/docs/#api/en/core/Raycaster.params */ raycasterParameters?: RaycasterParameters; } export interface ThreeJSOverlayViewOptions { /** * The anchor for the scene. * * @default {lat: 0, lng: 0, altitude: 0} */ anchor?: LatLngTypes; /** * The axis pointing up in the scene. Can be specified as "Z", "Y" or a * Vector3, in which case the normalized vector will become the up-axis. * * @default "Z" */ upAxis?: "Z" | "Y" | Vector3; /** * The map the overlay will be added to. * Can be set at initialization or by calling `setMap(map)`. */ map?: google.maps.Map; /** * The scene object to render in the overlay. If no scene is specified, a * new scene is created and can be accessed via `overlay.scene`. */ scene?: Scene; /** * The animation mode controls when the overlay will redraw, either * continuously (`always`) or on demand (`ondemand`). When using the * on demand mode, the overlay will re-render whenever the map renders * (camera movements) or when `requestRedraw()` is called. * * To achieve animations in this mode, you can either use an outside * animation-loop that calls `requestRedraw()` as long as needed or call * `requestRedraw()` from within the `onBeforeRender` function to * * @default "ondemand" */ animationMode?: "always" | "ondemand"; /** * Add default lighting to the scene. * @default true */ addDefaultLighting?: boolean; } /* eslint-disable @typescript-eslint/no-empty-function */ /** * Add a [three.js](https://threejs.org) scene as a [Google Maps WebGLOverlayView](http://goo.gle/WebGLOverlayView-ref). */ export class ThreeJSOverlayView implements google.maps.WebGLOverlayView { /** {@inheritDoc ThreeJSOverlayViewOptions.scene} */ public readonly scene: Scene; /** {@inheritDoc ThreeJSOverlayViewOptions.animationMode} */ public animationMode: "always" | "ondemand" = "ondemand"; /** {@inheritDoc ThreeJSOverlayViewOptions.anchor} */ protected anchor: google.maps.LatLngAltitudeLiteral; protected readonly camera: PerspectiveCamera; protected readonly rotationArray: Float32Array = new Float32Array(3); protected readonly rotationInverse: Quaternion = new Quaternion(); protected readonly projectionMatrixInverse = new Matrix4(); protected readonly overlay: google.maps.WebGLOverlayView; protected renderer: WebGLRenderer; protected raycaster: Raycaster = new Raycaster(); constructor(options: ThreeJSOverlayViewOptions = {}) { const { anchor = { lat: 0, lng: 0, altitude: 0 }, upAxis = "Z", scene, map, animationMode = "ondemand", addDefaultLighting = true, } = options; this.overlay = new google.maps.WebGLOverlayView(); this.renderer = null; this.camera = null; this.animationMode = animationMode; this.setAnchor(anchor); this.setUpAxis(upAxis); this.scene = scene ?? new Scene(); if (addDefaultLighting) this.initSceneLights(); this.overlay.onAdd = this.onAdd.bind(this); this.overlay.onRemove = this.onRemove.bind(this); this.overlay.onContextLost = this.onContextLost.bind(this); this.overlay.onContextRestored = this.onContextRestored.bind(this); this.overlay.onStateUpdate = this.onStateUpdate.bind(this); this.overlay.onDraw = this.onDraw.bind(this); this.camera = new PerspectiveCamera(); if (map) { this.setMap(map); } } /** * Sets the anchor-point. * @param anchor */ public setAnchor(anchor: LatLngTypes) { this.anchor = toLatLngAltitudeLiteral(anchor); } /** * Sets the axis to use as "up" in the scene. * @param axis */ public setUpAxis(axis: "Y" | "Z" | Vector3): void { const upVector = new Vector3(0, 0, 1); if (typeof axis !== "string") { upVector.copy(axis); } else { if (axis.toLowerCase() === "y") { upVector.set(0, 1, 0); } else if (axis.toLowerCase() !== "z") { console.warn(`invalid value '${axis}' specified as upAxis`); } } upVector.normalize(); const q = new Quaternion(); q.setFromUnitVectors(upVector, DEFAULT_UP); // inverse rotation is needed in latLngAltitudeToVector3() this.rotationInverse.copy(q).invert(); // copy to rotationArray for transformer.fromLatLngAltitude() const euler = new Euler().setFromQuaternion(q, "XYZ"); this.rotationArray[0] = MathUtils.radToDeg(euler.x); this.rotationArray[1] = MathUtils.radToDeg(euler.y); this.rotationArray[2] = MathUtils.radToDeg(euler.z); } /** * Runs raycasting for the specified screen-coordinates against all objects * in the scene. * * @param p normalized screenspace coordinates of the * mouse-cursor. x/y are in range [-1, 1], y is pointing up. * @param options raycasting options. In this case the `recursive` option * has no effect as it is always recursive. * @return the list of intersections */ public raycast(p: Vector2, options?: RaycastOptions): Intersection[]; /** * Runs raycasting for the specified screen-coordinates against the specified * list of objects. * * Note for typescript users: the returned Intersection objects can only be * properly typed for non-recursive lookups (this is handled by the internal * signature below). * * @param p normalized screenspace coordinates of the * mouse-cursor. x/y are in range [-1, 1], y is pointing up. * @param objects list of objects to test * @param options raycasting options. */ public raycast( p: Vector2, objects: Object3D[], options?: RaycastOptions & { recursive: true } ): Intersection[]; // additional signature to enable typings in returned objects when possible public raycast( p: Vector2, objects: T[], options?: | Omit | (RaycastOptions & { recursive: false }) ): Intersection[]; // implemetation public raycast( p: Vector2, optionsOrObjects?: Object3D[] | RaycastOptions, options: RaycastOptions = {} ): Intersection[] { let objects: Object3D[]; if (Array.isArray(optionsOrObjects)) { objects = optionsOrObjects || null; } else { objects = [this.scene]; options = { ...optionsOrObjects, recursive: true }; } const { updateMatrix = true, recursive = false, raycasterParameters, } = options; // when `raycast()` is called from within the `onBeforeRender()` callback, // the mvp-matrix for this frame has already been computed and stored in // `this.camera.projectionMatrix`. // The mvp-matrix transforms world-space meters to clip-space // coordinates. The inverse matrix created here does the exact opposite // and converts clip-space coordinates to world-space. if (updateMatrix) { this.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert(); } // create two points (with different depth) from the mouse-position and // convert them into world-space coordinates to set up the ray. this.raycaster.ray.origin .set(p.x, p.y, 0) .applyMatrix4(this.projectionMatrixInverse); this.raycaster.ray.direction .set(p.x, p.y, 0.5) .applyMatrix4(this.projectionMatrixInverse) .sub(this.raycaster.ray.origin) .normalize(); // back up the raycaster parameters const oldRaycasterParams = this.raycaster.params; if (raycasterParameters) { this.raycaster.params = raycasterParameters; } const results = this.raycaster.intersectObjects(objects, recursive); // reset raycaster params to whatever they were before this.raycaster.params = oldRaycasterParams; return results; } /** * Overwrite this method to handle any GL state updates outside the * render animation frame. * @param options */ public onStateUpdate(options: google.maps.WebGLStateOptions): void; public onStateUpdate(): void {} /** * Overwrite this method to fetch or create intermediate data structures * before the overlay is drawn that don’t require immediate access to the * WebGL rendering context. */ public onAdd(): void {} /** * Overwrite this method to update your scene just before a new frame is * drawn. */ public onBeforeDraw(): void {} /** * This method is called when the overlay is removed from the map with * `overlay.setMap(null)`, and is where you can remove all intermediate * objects created in onAdd. */ public onRemove(): void {} /** * Triggers the map to update GL state. */ public requestStateUpdate(): void { this.overlay.requestStateUpdate(); } /** * Triggers the map to redraw a frame. */ public requestRedraw(): void { this.overlay.requestRedraw(); } /** * Returns the map the overlay is added to. */ public getMap(): google.maps.Map { return this.overlay.getMap(); } /** * Adds the overlay to the map. * @param map The map to access the div, model and view state. */ public setMap(map: google.maps.Map): void { this.overlay.setMap(map); } /** * Adds the given listener function to the given event name. Returns an * identifier for this listener that can be used with * google.maps.event.removeListener. */ public addListener( eventName: string, handler: (...args: unknown[]) => void ): google.maps.MapsEventListener { return this.overlay.addListener(eventName, handler); } /** * This method is called once the rendering context is available. Use it to * initialize or bind any WebGL state such as shaders or buffer objects. * @param options that allow developers to restore the GL context. */ public onContextRestored({ gl }: google.maps.WebGLStateOptions) { this.renderer = new WebGLRenderer({ canvas: gl.canvas, context: gl, ...gl.getContextAttributes(), }); this.renderer.autoClear = false; this.renderer.autoClearDepth = false; this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = PCFSoftShadowMap; // Since r152, default outputColorSpace is SRGB // Deprecated outputEncoding kept for backwards compatibility if (Number(REVISION) < 152) { // eslint-disable-next-line @typescript-eslint/no-explicit-any (this.renderer as any).outputEncoding = sRGBEncoding; } const { width, height } = gl.canvas; this.renderer.setViewport(0, 0, width, height); } /** * This method is called when the rendering context is lost for any reason, * and is where you should clean up any pre-existing GL state, since it is * no longer needed. */ public onContextLost() { if (!this.renderer) { return; } this.renderer.dispose(); this.renderer = null; } /** * Implement this method to draw WebGL content directly on the map. Note * that if the overlay needs a new frame drawn then call {@link * ThreeJSOverlayView.requestRedraw}. * @param options that allow developers to render content to an associated * Google basemap. */ public onDraw({ gl, transformer }: google.maps.WebGLDrawOptions): void { this.camera.projectionMatrix.fromArray( transformer.fromLatLngAltitude(this.anchor, this.rotationArray) ); gl.disable(gl.SCISSOR_TEST); this.onBeforeDraw(); this.renderer.render(this.scene, this.camera); this.renderer.resetState(); if (this.animationMode === "always") this.requestRedraw(); } /** * Convert coordinates from WGS84 Latitude Longitude to world-space * coordinates while taking the origin and orientation into account. */ public latLngAltitudeToVector3( position: LatLngTypes, target = new Vector3() ) { latLngToVector3Relative( toLatLngAltitudeLiteral(position), this.anchor, target ); target.applyQuaternion(this.rotationInverse); return target; } // MVCObject interface forwarded to the overlay /** * Binds a View to a Model. */ public bindTo( key: string, target: google.maps.MVCObject, targetKey?: string, noNotify?: boolean ): void { this.overlay.bindTo(key, target, targetKey, noNotify); } /** * Gets a value. */ public get(key: string) { return this.overlay.get(key); } /** * Notify all observers of a change on this property. This notifies both * objects that are bound to the object's property as well as the object * that it is bound to. */ public notify(key: string): void { this.overlay.notify(key); } /** * Sets a value. */ public set(key: string, value: unknown): void { this.overlay.set(key, value); } /** * Sets a collection of key-value pairs. */ public setValues(values?: object): void { this.overlay.setValues(values); } /** * Removes a binding. Unbinding will set the unbound property to the current * value. The object will not be notified, as the value has not changed. */ public unbind(key: string): void { this.overlay.unbind(key); } /** * Removes all bindings. */ public unbindAll(): void { this.overlay.unbindAll(); } /** * Creates lights (directional and hemisphere light) to illuminate the model * (roughly approximates the lighting of buildings in maps) */ private initSceneLights() { const hemiLight = new HemisphereLight(0xffffff, 0x444444, 1); hemiLight.position.set(0, -0.2, 1).normalize(); const dirLight = new DirectionalLight(0xffffff); dirLight.position.set(0, 10, 100); this.scene.add(hemiLight, dirLight); } } ================================================ FILE: src/util.ts ================================================ /** * Copyright 2021 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { MathUtils, Vector3 } from "three"; export type LatLngTypes = | google.maps.LatLngLiteral | google.maps.LatLng | google.maps.LatLngAltitudeLiteral | google.maps.LatLngAltitude; // shorthands for math-functions, makes equations more readable const { atan, cos, exp, log, tan, PI } = Math; const { degToRad, radToDeg } = MathUtils; export const EARTH_RADIUS = 6371010.0; export const WORLD_SIZE = Math.PI * EARTH_RADIUS; /** * Converts any of the supported position formats into the * google.maps.LatLngAltitudeLiteral format used for the calculations. * @param point */ export function toLatLngAltitudeLiteral( point: LatLngTypes ): google.maps.LatLngAltitudeLiteral { if ( window.google && google.maps && (point instanceof google.maps.LatLng || point instanceof google.maps.LatLngAltitude) ) { return { altitude: 0, ...point.toJSON() }; } return { altitude: 0, ...(point as google.maps.LatLngLiteral) }; } /** * Converts latitude and longitude to world space coordinates relative * to a reference location with y up. */ export function latLngToVector3Relative( point: google.maps.LatLngAltitudeLiteral, reference: google.maps.LatLngAltitudeLiteral, target = new Vector3() ) { const [px, py] = latLngToXY(point); const [rx, ry] = latLngToXY(reference); target.set(px - rx, py - ry, 0); // apply the spherical mercator scale-factor for the reference latitude target.multiplyScalar(cos(degToRad(reference.lat))); target.z = point.altitude - reference.altitude; return target; } /** * Converts WGS84 latitude and longitude to (uncorrected) WebMercator meters. * (WGS84 --> WebMercator (EPSG:3857)) */ export function latLngToXY(position: google.maps.LatLngLiteral): number[] { return [ EARTH_RADIUS * degToRad(position.lng), EARTH_RADIUS * log(tan(0.25 * PI + 0.5 * degToRad(position.lat))), ]; } /** * Converts WebMercator meters to WGS84 latitude/longitude. * (WebMercator (EPSG:3857) --> WGS84) */ export function xyToLatLng(p: number[]): google.maps.LatLngLiteral { const [x, y] = p; return { lat: radToDeg(PI * 0.5 - 2.0 * atan(exp(-y / EARTH_RADIUS))), lng: radToDeg(x) / EARTH_RADIUS, }; } ================================================ FILE: tsconfig.examples.json ================================================ { "extends": "./tsconfig.json", "compilerOptions": { "declaration": false, "noEmit": true, "outDir": null, "declarationDir": null, "noImplicitAny": false, "resolveJsonModule": true }, "include": ["src/**/*", "examples/**/*"] } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "declaration": true, "declarationDir": "./dist", "noImplicitAny": true, "outDir": "./dist", "sourceMap": true, "esModuleInterop": true, "lib": ["DOM", "ESNext", "ES2019"], "target": "ES2020", "module": "ES2020", "moduleResolution": "node", "skipLibCheck": true, "resolveJsonModule": true }, "include": ["src/**/*"], "exclude": ["node_modules", "./dist"] } ================================================ FILE: typedoc.cjs ================================================ /** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ module.exports = { out: "docs", exclude: ["**/node_modules/**", "**/*.spec.ts", "**/*.test.ts"], name: "@googlemaps/three", excludePrivate: true, media: "assets", };