├── .changes
├── config.json
└── readme.md
├── .gitattributes
├── .github
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ ├── ci.yml
│ ├── covector-status.yml
│ └── covector-version-or-publish.yml
├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── glutin
├── CHANGELOG.md
├── Cargo.toml
├── LICENSE
├── README.md
├── build.rs
└── src
│ ├── lib.rs
│ └── window.rs
├── glutin_examples
├── Cargo.toml
├── LICENSE
├── build.rs
├── examples
│ ├── egl_device.rs
│ └── window.rs
└── src
│ └── lib.rs
└── rustfmt.toml
/.changes/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "gitSiteUrl": "https://github.com/tauri-apps/glutin/",
3 | "pkgManagers": {
4 | "rust": {
5 | "version": true,
6 | "getPublishedVersion": "cargo search ${ pkg.pkg } --limit 1 | sed -nE 's/^[^\"]*\"//; s/\".*//1p' -",
7 | "prepublish": [
8 | "sudo apt-get update",
9 | "sudo apt-get install -y libgtk-3-dev",
10 | "cargo install cargo-audit --features=fix",
11 | {
12 | "command": "cargo generate-lockfile",
13 | "dryRunCommand": true,
14 | "runFromRoot": true,
15 | "pipe": true
16 | },
17 | {
18 | "command": "echo '\nCargo Audit
\n\n```'",
19 | "dryRunCommand": true,
20 | "pipe": true
21 | },
22 | {
23 | "command": "cargo audit ${ process.env.CARGO_AUDIT_OPTIONS || '' }",
24 | "dryRunCommand": true,
25 | "runFromRoot": true,
26 | "pipe": true
27 | },
28 | {
29 | "command": "echo '```\n\n \n'",
30 | "dryRunCommand": true,
31 | "pipe": true
32 | }
33 | ],
34 | "publish": [
35 | {
36 | "command": "cargo package --allow-dirty",
37 | "dryRunCommand": true
38 | },
39 | {
40 | "command": "echo '\nCargo Publish
\n\n```'",
41 | "dryRunCommand": true,
42 | "pipe": true
43 | },
44 | {
45 | "command": "echo \"\\`\\`\\`\"",
46 | "dryRunCommand": true,
47 | "pipe": true
48 | },
49 | {
50 | "command": "cargo publish --no-verify",
51 | "dryRunCommand": "cargo publish --no-verify --dry-run --allow-dirty",
52 | "pipe": true
53 | },
54 | {
55 | "command": "echo '```\n\n \n'",
56 | "dryRunCommand": true,
57 | "pipe": true
58 | }
59 | ],
60 | "postpublish": [
61 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor } -f",
62 | "git tag ${ pkg.pkg }-v${ pkgFile.versionMajor }.${ pkgFile.versionMinor } -f",
63 | "git push --tags -f"
64 | ],
65 | "assets": [
66 | {
67 | "path": "${ pkg.path }/${ pkg.pkg }-${ pkgFile.version }.crate",
68 | "name": "${ pkg.pkg }-${ pkgFile.version }.crate"
69 | }
70 | ]
71 | }
72 | },
73 | "packages": {
74 | "glutin_tao": {
75 | "path": "./glutin",
76 | "manager": "rust"
77 | }
78 | }
79 | }
--------------------------------------------------------------------------------
/.changes/readme.md:
--------------------------------------------------------------------------------
1 | # Changes
2 |
3 | ##### via https://github.com/jbolda/covector
4 |
5 | As you create PRs and make changes that require a version bump, please add a new markdown file in this folder. You do not note the version _number_, but rather the type of bump that you expect: major, minor, or patch. The filename is not important, as long as it is a `.md`, but we recommend that it represents the overall change for organizational purposes.
6 |
7 | When you select the version bump required, you do _not_ need to consider dependencies. Only note the package with the actual change, and any packages that depend on that package will be bumped automatically in the process.
8 |
9 | Use the following format:
10 |
11 | ```md
12 | ---
13 | "package-a": patch
14 | "package-b": minor
15 | ---
16 |
17 | Change summary goes here
18 |
19 | ```
20 |
21 | Summaries do not have a specific character limit, but are text only. These summaries are used within the (future implementation of) changelogs. They will give context to the change and also point back to the original PR if more details and context are needed.
22 |
23 | Changes will be designated as a `major`, `minor` or `patch` as further described in [semver](https://semver.org/).
24 |
25 | Given a version number MAJOR.MINOR.PATCH, increment the:
26 |
27 | - MAJOR version when you make incompatible API changes,
28 | - MINOR version when you add functionality in a backwards compatible manner, and
29 | - PATCH version when you make backwards compatible bug fixes.
30 |
31 | Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format, but will be discussed prior to usage (as extra steps will be necessary in consideration of merging and publishing).
32 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 | *.sln merge=union
7 | *.csproj merge=union
8 | *.vbproj merge=union
9 | *.fsproj merge=union
10 | *.dbproj merge=union
11 |
12 | # Standard to msysgit
13 | *.doc diff=astextplain
14 | *.DOC diff=astextplain
15 | *.docx diff=astextplain
16 | *.DOCX diff=astextplain
17 | *.dot diff=astextplain
18 | *.DOT diff=astextplain
19 | *.pdf diff=astextplain
20 | *.PDF diff=astextplain
21 | *.rtf diff=astextplain
22 | *.RTF diff=astextplain
23 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | - [ ] Tested on all platforms changed
2 | - [ ] Added an entry to `CHANGELOG.md` if knowledge of this change could be valuable to users
3 | - [ ] Updated documentation to reflect any user-facing changes, including notes of platform-specific behavior
4 | - [ ] Created or updated an example program if it would help users understand this functionality
5 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | pull_request:
5 | paths:
6 | - '**.rs'
7 | - '**.toml'
8 | - '.github/workflows/ci.yml'
9 | push:
10 | branches: [master]
11 | paths:
12 | - '**.rs'
13 | - '**.toml'
14 | - '.github/workflows/ci.yml'
15 |
16 | jobs:
17 | # check-formatting:
18 | # name: Check formatting
19 | # runs-on: ubuntu-latest
20 | # steps:
21 | # - uses: actions/checkout@v1
22 | # - uses: hecrj/setup-rust-action@v1
23 | # with:
24 | # rust-version: nightly
25 | # components: rustfmt
26 | # - name: Check Formatting
27 | # run: cargo +nightly fmt --all -- --check
28 |
29 | tests:
30 | name: Tests
31 | strategy:
32 | fail-fast: false
33 | matrix:
34 | rust_version: [1.65.0, stable, nightly]
35 | platform:
36 | - { target: x86_64-pc-windows-msvc, os: windows-latest, }
37 | - { target: i686-pc-windows-msvc, os: windows-latest, }
38 | - { target: i686-pc-windows-msvc, os: windows-latest, options: --no-default-features, features: wgl }
39 | - { target: i686-pc-windows-msvc, os: windows-latest, options: --no-default-features, features: egl }
40 | - { target: x86_64-pc-windows-gnu, os: windows-latest, host: -x86_64-pc-windows-gnu }
41 | - { target: i686-pc-windows-gnu, os: windows-latest, host: -i686-pc-windows-gnu }
42 | # - { target: i686-unknown-linux-gnu, os: ubuntu-latest, }
43 | - { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, }
44 | # - { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: "egl,wayland,x11" }
45 | # - { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: "egl,wayland" }
46 | - { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: "egl,x11" }
47 | # - { target: x86_64-unknown-linux-gnu, os: ubuntu-latest, options: --no-default-features, features: glx }
48 | # - { target: aarch64-linux-android, os: ubuntu-latest, cmd: 'apk --' }
49 | - { target: x86_64-apple-darwin, os: macos-latest, }
50 | # We don't support ios for now.
51 | # - { target: x86_64-apple-ios, os: macos-latest, }
52 | # - { target: aarch64-apple-ios, os: macos-latest, }
53 |
54 | env:
55 | RUST_BACKTRACE: 1
56 | CARGO_INCREMENTAL: 0
57 | RUSTFLAGS: "-C debuginfo=0"
58 | OPTIONS: ${{ matrix.platform.options }}
59 | CMD: ${{ matrix.platform.cmd }}
60 | FEATURES: ${{ format(',{0}', matrix.platform.features ) }}
61 | RUSTDOCFLAGS: -Dwarnings
62 |
63 | runs-on: ${{ matrix.platform.os }}
64 | steps:
65 | - uses: actions/checkout@v1
66 | # Used to cache cargo-web
67 | - name: Cache cargo folder
68 | uses: actions/cache@v1
69 | with:
70 | path: ~/.cargo
71 | key: ${{ matrix.platform.target }}-cargo-${{ matrix.rust_version }}
72 |
73 | - uses: hecrj/setup-rust-action@v1
74 | with:
75 | rust-version: ${{ matrix.rust_version }}${{ matrix.platform.host }}
76 | targets: ${{ matrix.platform.target }}
77 | components: clippy
78 |
79 | # We need those for examples.
80 | - name: Install GCC Multilib
81 | if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
82 | run: sudo apt-get update && sudo apt-get install gcc-multilib
83 |
84 | - name: Install Gtk (ubuntu only)
85 | if: matrix.platform.os == 'ubuntu-latest'
86 | run: |
87 | sudo apt-get update
88 | sudo apt-get install -y libgtk-3-dev
89 |
90 | - name: Install cargo-apk
91 | if: contains(matrix.platform.target, 'android')
92 | run: cargo +stable install cargo-apk
93 |
94 | - name: Build tests
95 | shell: bash
96 | run: cd glutin && cargo $CMD test -p glutin --no-run --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
97 | - name: Run tests
98 | shell: bash
99 | if: (
100 | !contains(matrix.platform.target, 'android') &&
101 | !contains(matrix.platform.target, 'ios') &&
102 | !contains(matrix.platform.target, 'wasm32'))
103 | run: cargo test --verbose --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES
104 |
105 | - name: Check documentation
106 | shell: bash
107 | run: cd glutin && cargo doc --no-deps --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES --document-private-items
108 |
109 | - name: Lint with clippy
110 | shell: bash
111 | if: (matrix.rust_version == '1.65.0') && !contains(matrix.platform.options, '--no-default-features')
112 | run: cargo clippy --workspace --all-targets --target ${{ matrix.platform.target }} $OPTIONS --features $FEATURES -- -Dwarnings
113 |
114 |
--------------------------------------------------------------------------------
/.github/workflows/covector-status.yml:
--------------------------------------------------------------------------------
1 | name: covector status
2 | on: [pull_request]
3 |
4 | jobs:
5 | covector:
6 | runs-on: ubuntu-latest
7 |
8 | steps:
9 | - uses: actions/checkout@v2
10 | with:
11 | fetch-depth: 0 # required for use of git history
12 | - name: covector status
13 | uses: jbolda/covector/packages/action@covector-v0.7
14 | id: covector
15 | with:
16 | command: 'status'
17 |
--------------------------------------------------------------------------------
/.github/workflows/covector-version-or-publish.yml:
--------------------------------------------------------------------------------
1 | name: version or publish
2 |
3 | on:
4 | push:
5 | branches:
6 | - '0.31'
7 |
8 | jobs:
9 | version-or-publish:
10 | runs-on: ubuntu-latest
11 | timeout-minutes: 65
12 | outputs:
13 | change: ${{ steps.covector.outputs.change }}
14 | commandRan: ${{ steps.covector.outputs.commandRan }}
15 | successfulPublish: ${{ steps.covector.outputs.successfulPublish }}
16 |
17 | steps:
18 | - uses: actions/checkout@v2
19 | with:
20 | fetch-depth: 0
21 | - name: cargo login
22 | run: cargo login ${{ secrets.ORG_CRATES_IO_TOKEN }}
23 | - name: git config
24 | run: |
25 | git config --global user.name "${{ github.event.pusher.name }}"
26 | git config --global user.email "${{ github.event.pusher.email }}"
27 | - name: covector version or publish (publish when no change files present)
28 | uses: jbolda/covector/packages/action@covector-v0
29 | id: covector
30 | env:
31 | CARGO_AUDIT_OPTIONS: ${{ secrets.CARGO_AUDIT_OPTIONS }}
32 | with:
33 | token: ${{ secrets.GITHUB_TOKEN }}
34 | command: "version-or-publish"
35 | createRelease: true
36 | - name: Create Pull Request With Versions Bumped
37 | id: cpr
38 | uses: tauri-apps/create-pull-request@v3
39 | if: steps.covector.outputs.commandRan == 'version'
40 | with:
41 | token: ${{ secrets.GITHUB_TOKEN }}
42 | title: "Publish New Versions"
43 | commit-message: "publish new versions"
44 | labels: "version updates"
45 | branch: "release"
46 | body: ${{ steps.covector.outputs.change }}
47 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | Cargo.lock
2 | target/
3 | .DS_Store
4 | *~
5 | #*#
6 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [workspace]
2 | members = [
3 | "glutin",
4 | "glutin_examples",
5 | ]
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2022 Kirill Chibisov
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # glutin_tao
2 |
3 | Glutin is a low-level library for OpenGL context creation, glutin_tao uses tao instead of winit.
4 |
5 |
6 | [](https://crates.io/crates/glutin)
7 | [](https://docs.rs/glutin)
8 |
9 | ```toml
10 | [dependencies]
11 | glutin = "0.30.8"
12 | ```
13 |
14 | ## [Documentation](https://docs.rs/glutin_tao)
15 |
16 | ### Try it!
17 |
18 | ```bash
19 | git clone https://github.com/tauri-apps/glutin
20 | cd glutin
21 | cargo run --example window
22 | ```
23 |
24 | ### Usage
25 |
26 | Glutin is an OpenGL context creation library, and doesn't directly provide
27 | OpenGL bindings for you.
28 |
29 | For examples, please look [here](https://github.com/rust-windowing/glutin/tree/master/glutin_examples).
30 |
31 | Note that glutin aims at being a low-level brick in your rendering
32 | infrastructure. You are encouraged to write another layer of abstraction
33 | between glutin and your application.
34 |
35 | The minimum Rust version target by glutin is `1.65.0`.
36 |
37 | ## Platform-specific notes
38 |
39 | ### Wayland
40 |
41 | Wayland is currently unsupported.
--------------------------------------------------------------------------------
/glutin/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Unreleased
2 |
3 | ## \[0.33.0]
4 |
5 | - [`6027820`](https://github.com/tauri-apps/glutin/commit/6027820de63f3615ebf8c024564583cad25dbca6) Update glutin_tao version to 0.32.0 to bump to 0.33.0 properly.
6 |
7 | ## \[0.4.0]
8 |
9 | - [`0eeba77`](https://github.com/tauri-apps/glutin/commit/0eeba77ad727e3d4a40291c670b023857654be31) Update glutin to 0.30.8.
10 |
11 |
12 |
13 | - **Breaking:** Fixed a typo in a type name (`ApiPrefence` -> `ApiPreference`).
14 |
15 | # Version 0.3.0
16 |
17 | - **Breaking:** Update *winit* to `0.28`. See [winit's CHANGELOG](https://github.com/rust-windowing/winit/releases/tag/v0.28.0) for more info.
18 |
19 | # Version 0.2.2
20 |
21 | - Add traits `GlWindow` with helper methods for building and resizing surfaces using a winit `Window`.
22 |
23 | # Version 0.2.1
24 |
25 | - Fix WGL window initialization.
26 |
27 | # Version 0.2.0
28 |
29 | - Fix API typo.
30 |
31 | # Version 0.1.0
32 |
33 | - Implement *glutin-winit* helpers.
34 |
--------------------------------------------------------------------------------
/glutin/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "glutin_tao"
3 | version = "0.33.0"
4 | authors = [ "Kirill Chibisov " ]
5 | description = "Glutin bootstrapping helpers with tao"
6 | keywords = [ "windowing", "opengl", "tao" ]
7 | license = "MIT"
8 | readme = "README.md"
9 | repository = "https://github.com/rust-windowing/glutin"
10 | edition = "2021"
11 |
12 | [features]
13 | default = [ "egl", "x11", "wayland", "wgl" ]
14 | egl = [ "glutin/egl" ]
15 | wgl = [ "glutin/wgl" ]
16 | x11 = [ "glutin/x11" ]
17 | wayland = [ "glutin/wayland" ]
18 |
19 | [dependencies]
20 | winit = { package = "tao", version = "0.19.0", default-features = false }
21 | glutin = { version = "0.30.1", default-features = false }
22 | raw-window-handle = "0.5.0"
23 |
24 | [build-dependencies]
25 | cfg_aliases = "0.1.1"
26 |
--------------------------------------------------------------------------------
/glutin/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright © 2022 Kirill Chibisov
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the “Software”), to deal
5 | in the Software without restriction, including without limitation the rights to
6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 | of the Software, and to permit persons to whom the Software is furnished to do
8 | so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16 | THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/glutin/README.md:
--------------------------------------------------------------------------------
1 | # glutin-winit
2 |
3 | The crate provides cross-platform glutin `Display` bootstrapping with winit.
4 |
5 | This crate is also a reference on how to do the bootstrapping of glutin when
6 | used with a cross-platform windowing library.
7 |
--------------------------------------------------------------------------------
/glutin/build.rs:
--------------------------------------------------------------------------------
1 | // XXX keep in sync with glutin's build.rs.
2 |
3 | use cfg_aliases::cfg_aliases;
4 |
5 | fn main() {
6 | // Setup alias to reduce `cfg` boilerplate.
7 | cfg_aliases! {
8 | // Systems.
9 | android_platform: { target_os = "android" },
10 | wasm_platform: { target_family = "wasm" },
11 | macos_platform: { target_os = "macos" },
12 | ios_platform: { target_os = "ios" },
13 | apple: { any(ios_platform, macos_platform) },
14 | free_unix: { all(unix, not(apple), not(android_platform)) },
15 |
16 | // Native displays.
17 | x11_platform: { all(feature = "x11", free_unix, not(wasm_platform)) },
18 | wayland_platform: { all(feature = "wayland", free_unix, not(wasm_platform)) },
19 |
20 | // Backends.
21 | egl_backend: { all(feature = "egl", any(windows, unix), not(apple), not(wasm_platform)) },
22 | glx_backend: { all(feature = "glx", x11_platform, not(wasm_platform)) },
23 | wgl_backend: { all(feature = "wgl", windows, not(wasm_platform)) },
24 | cgl_backend: { all(macos_platform, not(wasm_platform)) },
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/glutin/src/lib.rs:
--------------------------------------------------------------------------------
1 | //! This library provides helpers for cross-platform [`glutin`] bootstrapping
2 | //! with [`winit`].
3 |
4 | #![deny(rust_2018_idioms)]
5 | #![deny(rustdoc::broken_intra_doc_links)]
6 | #![deny(clippy::all)]
7 | #![deny(missing_debug_implementations)]
8 | #![deny(missing_docs)]
9 | #![cfg_attr(feature = "cargo-clippy", deny(warnings))]
10 |
11 | mod window;
12 |
13 | pub use window::GlWindow;
14 |
15 | use std::error::Error;
16 |
17 | use glutin::config::{Config, ConfigTemplateBuilder};
18 | use glutin::display::{Display, DisplayApiPreference};
19 | // #[cfg(x11_platform)]
20 | // use glutin::platform::x11::X11GlConfigExt;
21 | use glutin::prelude::*;
22 |
23 | use raw_window_handle::{HasRawDisplayHandle, RawWindowHandle};
24 |
25 | #[cfg(wgl_backend)]
26 | use raw_window_handle::HasRawWindowHandle;
27 |
28 | use winit::error::OsError;
29 | use winit::event_loop::EventLoopWindowTarget;
30 | use winit::window::{Window, WindowBuilder};
31 |
32 | // #[cfg(glx_backend)]
33 | // use winit::platform::x11::register_xlib_error_hook;
34 | // #[cfg(x11_platform)]
35 | // use winit::platform::x11::WindowBuilderExtX11;
36 |
37 | #[cfg(all(not(egl_backend), not(glx_backend), not(wgl_backend), not(cgl_backend)))]
38 | compile_error!("Please select at least one api backend");
39 |
40 | /// The helper to perform [`Display`] creation and OpenGL platform
41 | /// bootstrapping with the help of [`winit`] with little to no platform specific
42 | /// code.
43 | ///
44 | /// This is only required for the initial setup. If you want to create
45 | /// additional windows just use the [`finalize_window`] function and the
46 | /// configuration you've used either for the original window or picked with the
47 | /// existing [`Display`].
48 | ///
49 | /// [`winit`]: winit
50 | /// [`Display`]: glutin::display::Display
51 | #[derive(Default, Debug, Clone)]
52 | pub struct DisplayBuilder {
53 | preference: ApiPreference,
54 | window_builder: Option,
55 | }
56 |
57 | impl DisplayBuilder {
58 | /// Create new display builder.
59 | pub fn new() -> Self {
60 | Default::default()
61 | }
62 |
63 | /// The preference in picking the configuration.
64 | pub fn with_preference(mut self, preference: ApiPreference) -> Self {
65 | self.preference = preference;
66 | self
67 | }
68 |
69 | /// The window builder to use when building a window.
70 | ///
71 | /// By default no window is created.
72 | pub fn with_window_builder(mut self, window_builder: Option) -> Self {
73 | self.window_builder = window_builder;
74 | self
75 | }
76 |
77 | /// Initialize the OpenGL platform and create a compatible window to use
78 | /// with it when the [`WindowBuilder`] was passed with
79 | /// [`Self::with_window_builder`]. It's optional, since on some
80 | /// platforms like `Android` it is not available early on, so you want to
81 | /// find configuration and later use it with the [`finalize_window`].
82 | /// But if you don't care about such platform you can always pass
83 | /// [`WindowBuilder`].
84 | ///
85 | /// # Api-specific
86 | ///
87 | /// **WGL:** - [`WindowBuilder`] **must** be passed in
88 | /// [`Self::with_window_builder`] if modern OpenGL(ES) is desired,
89 | /// otherwise only builtin functions like `glClear` will be available.
90 | pub fn build(
91 | mut self,
92 | window_target: &EventLoopWindowTarget,
93 | template_builder: ConfigTemplateBuilder,
94 | config_picker: Picker,
95 | ) -> Result<(Option, Config), Box>
96 | where
97 | Picker: FnOnce(Box + '_>) -> Config,
98 | {
99 | // XXX with WGL backend window should be created first.
100 | #[cfg(wgl_backend)]
101 | let window = if let Some(wb) = self.window_builder.take() {
102 | Some(wb.build(window_target)?)
103 | } else {
104 | None
105 | };
106 |
107 | #[cfg(wgl_backend)]
108 | let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());
109 | #[cfg(not(wgl_backend))]
110 | let raw_window_handle = None;
111 |
112 | let gl_display = create_display(window_target, self.preference, raw_window_handle)?;
113 |
114 | // XXX the native window must be passed to config picker when WGL is used
115 | // otherwise very limited OpenGL features will be supported.
116 | #[cfg(wgl_backend)]
117 | let template_builder = if let Some(raw_window_handle) = raw_window_handle {
118 | template_builder.compatible_with_native_window(raw_window_handle)
119 | } else {
120 | template_builder
121 | };
122 |
123 | let template = template_builder.build();
124 |
125 | let gl_config = unsafe {
126 | let configs = gl_display.find_configs(template)?;
127 | config_picker(configs)
128 | };
129 |
130 | #[cfg(not(wgl_backend))]
131 | let window = if let Some(wb) = self.window_builder.take() {
132 | Some(finalize_window(window_target, wb, &gl_config)?)
133 | } else {
134 | None
135 | };
136 |
137 | Ok((window, gl_config))
138 | }
139 | }
140 |
141 | fn create_display(
142 | window_target: &EventLoopWindowTarget,
143 | _api_preference: ApiPreference,
144 | _raw_window_handle: Option,
145 | ) -> Result> {
146 | #[cfg(egl_backend)]
147 | let _preference = DisplayApiPreference::Egl;
148 |
149 | // #[cfg(glx_backend)]
150 | // let _preference = DisplayApiPreference::Glx(Box::new(register_xlib_error_hook));
151 |
152 | #[cfg(cgl_backend)]
153 | let _preference = DisplayApiPreference::Cgl;
154 |
155 | #[cfg(wgl_backend)]
156 | let _preference = DisplayApiPreference::Wgl(_raw_window_handle);
157 |
158 | // #[cfg(all(egl_backend, glx_backend))]
159 | // let _preference = match _api_preference {
160 | // ApiPreference::PreferEgl => {
161 | // DisplayApiPreference::EglThenGlx(Box::new(register_xlib_error_hook))
162 | // },
163 | // ApiPreference::FallbackEgl => {
164 | // DisplayApiPreference::GlxThenEgl(Box::new(register_xlib_error_hook))
165 | // },
166 | // };
167 |
168 | #[cfg(all(wgl_backend, egl_backend))]
169 | let _preference = match _api_preference {
170 | ApiPreference::PreferEgl => DisplayApiPreference::EglThenWgl(_raw_window_handle),
171 | ApiPreference::FallbackEgl => DisplayApiPreference::WglThenEgl(_raw_window_handle),
172 | };
173 |
174 | unsafe { Ok(Display::new(window_target.raw_display_handle(), _preference)?) }
175 | }
176 |
177 | /// Finalize [`Window`] creation by applying the options from the [`Config`], be
178 | /// aware that it could remove incompatible options from the window builder like
179 | /// `transparency`, when the provided config doesn't support it.
180 | ///
181 | /// [`Window`]: winit::window::Window
182 | /// [`Config`]: glutin::config::Config
183 | pub fn finalize_window(
184 | window_target: &EventLoopWindowTarget,
185 | mut builder: WindowBuilder,
186 | gl_config: &Config,
187 | ) -> Result {
188 | // Disable transparency if the end config doesn't support it.
189 | if gl_config.supports_transparency() == Some(false) {
190 | builder = builder.with_transparent(false);
191 | }
192 |
193 | // #[cfg(x11_platform)]
194 | // let builder = if let Some(x11_visual) = gl_config.x11_visual() {
195 | // builder.with_x11_visual(x11_visual.into_raw())
196 | // } else {
197 | // builder
198 | // };
199 |
200 | builder.build(window_target)
201 | }
202 |
203 | /// Simplified version of the [`DisplayApiPreference`] which is used to simplify
204 | /// cross platform window creation.
205 | ///
206 | /// To learn about platform differences the [`DisplayApiPreference`] variants.
207 | ///
208 | /// [`DisplayApiPreference`]: glutin::display::DisplayApiPreference
209 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210 | pub enum ApiPreference {
211 | /// Prefer `EGL` over system provider like `GLX` and `WGL`.
212 | PreferEgl,
213 |
214 | /// Fallback to `EGL` when failed to create the system profile.
215 | ///
216 | /// This behavior is used by default. However consider using
217 | /// [`Self::PreferEgl`] if you don't care about missing EGL features.
218 | #[default]
219 | FallbackEgl,
220 | }
221 |
--------------------------------------------------------------------------------
/glutin/src/window.rs:
--------------------------------------------------------------------------------
1 | use glutin::context::PossiblyCurrentContext;
2 | use glutin::surface::{
3 | GlSurface, ResizeableSurface, Surface, SurfaceAttributes, SurfaceAttributesBuilder,
4 | SurfaceTypeTrait, WindowSurface,
5 | };
6 | use raw_window_handle::HasRawWindowHandle;
7 | use std::num::NonZeroU32;
8 | use winit::window::Window;
9 |
10 | /// [`Window`] extensions for working with [`glutin`] surfaces.
11 | pub trait GlWindow {
12 | /// Build the surface attributes suitable to create a window surface.
13 | ///
14 | /// # Panics
15 | /// Panics if either window inner dimension is zero.
16 | ///
17 | /// # Example
18 | /// ```no_run
19 | /// use glutin_tao::GlWindow;
20 | /// # let winit_window: winit::window::Window = unimplemented!();
21 | ///
22 | /// let attrs = winit_window.build_surface_attributes(<_>::default());
23 | /// ```
24 | fn build_surface_attributes(
25 | &self,
26 | builder: SurfaceAttributesBuilder,
27 | ) -> SurfaceAttributes;
28 |
29 | /// Resize the surface to the window inner size.
30 | ///
31 | /// No-op if either window size is zero.
32 | ///
33 | /// # Example
34 | /// ```no_run
35 | /// use glutin_tao::GlWindow;
36 | /// # use glutin::surface::{Surface, WindowSurface};
37 | /// # let winit_window: winit::window::Window = unimplemented!();
38 | /// # let (gl_surface, gl_context): (Surface, _) = unimplemented!();
39 | ///
40 | /// winit_window.resize_surface(&gl_surface, &gl_context);
41 | /// ```
42 | fn resize_surface(
43 | &self,
44 | surface: &Surface,
45 | context: &PossiblyCurrentContext,
46 | );
47 | }
48 |
49 | impl GlWindow for Window {
50 | fn build_surface_attributes(
51 | &self,
52 | builder: SurfaceAttributesBuilder,
53 | ) -> SurfaceAttributes {
54 | let (w, h) = self.inner_size().non_zero().expect("invalid zero inner size");
55 | builder.build(self.raw_window_handle(), w, h)
56 | }
57 |
58 | fn resize_surface(
59 | &self,
60 | surface: &Surface,
61 | context: &PossiblyCurrentContext,
62 | ) {
63 | if let Some((w, h)) = self.inner_size().non_zero() {
64 | surface.resize(context, w, h)
65 | }
66 | }
67 | }
68 |
69 | /// [`winit::dpi::PhysicalSize`] non-zero extensions.
70 | trait NonZeroU32PhysicalSize {
71 | /// Converts to non-zero `(width, height)`.
72 | fn non_zero(self) -> Option<(NonZeroU32, NonZeroU32)>;
73 | }
74 | impl NonZeroU32PhysicalSize for winit::dpi::PhysicalSize {
75 | fn non_zero(self) -> Option<(NonZeroU32, NonZeroU32)> {
76 | let w = NonZeroU32::new(self.width)?;
77 | let h = NonZeroU32::new(self.height)?;
78 | Some((w, h))
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/glutin_examples/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "glutin_examples"
3 | version = "0.1.3"
4 | authors = ["Kirill Chibisov "]
5 | description = "Examples for glutin"
6 | repository = "https://github.com/rust-windowing/glutin"
7 | license = "Apache-2.0"
8 | readme = "../README.md"
9 | rust-version = "1.65.0"
10 | edition = "2021"
11 | publish = false
12 |
13 | [features]
14 | default = ["egl", "x11", "wayland", "wgl"]
15 | egl = ["glutin_tao/egl", "png"]
16 | wgl = ["glutin_tao/wgl"]
17 | x11 = ["glutin_tao/x11"]
18 | wayland = ["glutin_tao/wayland"]
19 |
20 | [dependencies]
21 | glutin = { version = "0.30.8", default-features = false }
22 | winit = { package = "tao", version = "0.19.0", default-features = false }
23 | glutin_tao = { path = "../glutin", default-features = false }
24 | raw-window-handle = "0.5.0"
25 | png = { version = "0.17.6", optional = true }
26 |
27 | [build-dependencies]
28 | gl_generator = "0.14"
29 | cfg_aliases = "0.1.1"
30 |
31 | [[example]]
32 | name = "egl_device"
33 | required-features = ["egl"]
34 |
--------------------------------------------------------------------------------
/glutin_examples/LICENSE:
--------------------------------------------------------------------------------
1 | ../LICENSE
--------------------------------------------------------------------------------
/glutin_examples/build.rs:
--------------------------------------------------------------------------------
1 | use std::env;
2 | use std::fs::File;
3 | use std::path::PathBuf;
4 |
5 | use cfg_aliases::cfg_aliases;
6 | use gl_generator::{Api, Fallbacks, Profile, Registry, StructGenerator};
7 |
8 | fn main() {
9 | // XXX this is taken from glutin/build.rs.
10 |
11 | // Setup alias to reduce `cfg` boilerplate.
12 | cfg_aliases! {
13 | // Systems.
14 | android_platform: { target_os = "android" },
15 | wasm_platform: { target_family = "wasm" },
16 | macos_platform: { target_os = "macos" },
17 | ios_platform: { target_os = "ios" },
18 | apple: { any(ios_platform, macos_platform) },
19 | free_unix: { all(unix, not(apple), not(android_platform)) },
20 |
21 | // Native displays.
22 | x11_platform: { all(feature = "x11", free_unix, not(wasm_platform)) },
23 | wayland_platform: { all(feature = "wayland", free_unix, not(wasm_platform)) },
24 |
25 | // Backends.
26 | egl_backend: { all(feature = "egl", any(windows, unix), not(apple), not(wasm_platform)) },
27 | glx_backend: { all(feature = "glx", x11_platform, not(wasm_platform)) },
28 | wgl_backend: { all(feature = "wgl", windows, not(wasm_platform)) },
29 | cgl_backend: { all(macos_platform, not(wasm_platform)) },
30 | }
31 |
32 | let dest = PathBuf::from(&env::var("OUT_DIR").unwrap());
33 |
34 | println!("cargo:rerun-if-changed=build.rs");
35 |
36 | let mut file = File::create(dest.join("gl_bindings.rs")).unwrap();
37 | Registry::new(Api::Gles2, (3, 0), Profile::Core, Fallbacks::All, [])
38 | .write_bindings(StructGenerator, &mut file)
39 | .unwrap();
40 | }
41 |
--------------------------------------------------------------------------------
/glutin_examples/examples/egl_device.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | #[cfg(egl_backend)]
3 | example::run();
4 | }
5 |
6 | #[cfg(egl_backend)]
7 | mod example {
8 | use std::fs::OpenOptions;
9 | use std::path::Path;
10 |
11 | use glutin::api::egl::device::Device;
12 | use glutin::api::egl::display::Display;
13 | use glutin::config::{ConfigSurfaceTypes, ConfigTemplate, ConfigTemplateBuilder};
14 | use glutin::context::{ContextApi, ContextAttributesBuilder};
15 | use glutin::prelude::*;
16 | use glutin_examples::{gl, Renderer};
17 |
18 | const IMG_PATH: &str = concat!(env!("OUT_DIR"), "/egl_device.png");
19 |
20 | pub fn run() {
21 | let devices = Device::query_devices().expect("Failed to query devices").collect::>();
22 |
23 | for (index, device) in devices.iter().enumerate() {
24 | println!(
25 | "Device {}: Name: {} Vendor: {}",
26 | index,
27 | device.name().unwrap_or("UNKNOWN"),
28 | device.vendor().unwrap_or("UNKNOWN")
29 | );
30 | }
31 |
32 | let device = devices.first().expect("No available devices");
33 |
34 | // Create a display using the device.
35 | let display =
36 | unsafe { Display::with_device(device, None) }.expect("Failed to create display");
37 |
38 | let template = config_template();
39 | let config = unsafe { display.find_configs(template) }
40 | .unwrap()
41 | .reduce(
42 | |config, acc| {
43 | if config.num_samples() > acc.num_samples() {
44 | config
45 | } else {
46 | acc
47 | }
48 | },
49 | )
50 | .expect("No available configs");
51 |
52 | println!("Picked a config with {} samples", config.num_samples());
53 |
54 | // Context creation.
55 | //
56 | // In particular, since we are doing offscreen rendering we have no raw window
57 | // handle to provide.
58 | let context_attributes = ContextAttributesBuilder::new().build(None);
59 |
60 | // Since glutin by default tries to create OpenGL core context, which may not be
61 | // present we should try gles.
62 | let fallback_context_attributes =
63 | ContextAttributesBuilder::new().with_context_api(ContextApi::Gles(None)).build(None);
64 |
65 | let not_current = unsafe {
66 | display.create_context(&config, &context_attributes).unwrap_or_else(|_| {
67 | display
68 | .create_context(&config, &fallback_context_attributes)
69 | .expect("failed to create context")
70 | })
71 | };
72 |
73 | // Make the context current for rendering
74 | let _context = not_current.make_current_surfaceless().unwrap();
75 | let renderer = Renderer::new(&display);
76 |
77 | // Create a framebuffer for offscreen rendering since we do not have a window.
78 | let mut framebuffer = 0;
79 | let mut renderbuffer = 0;
80 | unsafe {
81 | renderer.GenFramebuffers(1, &mut framebuffer);
82 | renderer.GenRenderbuffers(1, &mut renderbuffer);
83 | renderer.BindFramebuffer(gl::FRAMEBUFFER, framebuffer);
84 | renderer.BindRenderbuffer(gl::RENDERBUFFER, renderbuffer);
85 | renderer.RenderbufferStorage(gl::RENDERBUFFER, gl::RGBA, 1280, 720);
86 | renderer.FramebufferRenderbuffer(
87 | gl::FRAMEBUFFER,
88 | gl::COLOR_ATTACHMENT0,
89 | gl::RENDERBUFFER,
90 | renderbuffer,
91 | );
92 | }
93 |
94 | renderer.resize(1280, 720);
95 | renderer.draw();
96 |
97 | let mut buffer = Vec::::with_capacity(1280 * 720 * 4);
98 | unsafe {
99 | // Wait for the previous commands to finish before reading from the framebuffer.
100 | renderer.Finish();
101 | // Download the framebuffer contents to the buffer.
102 | renderer.ReadPixels(
103 | 0,
104 | 0,
105 | 1280,
106 | 720,
107 | gl::RGBA,
108 | gl::UNSIGNED_BYTE,
109 | buffer.as_mut_ptr() as *mut _,
110 | );
111 | buffer.set_len(1280 * 720 * 4);
112 | }
113 |
114 | let path = Path::new(IMG_PATH);
115 | let file = OpenOptions::new().write(true).create(true).open(path).unwrap();
116 |
117 | let mut encoder = png::Encoder::new(file, 1280, 720);
118 | encoder.set_depth(png::BitDepth::Eight);
119 | encoder.set_color(png::ColorType::Rgba);
120 | let mut png_writer = encoder.write_header().unwrap();
121 |
122 | png_writer.write_image_data(&buffer[..]).unwrap();
123 | png_writer.finish().unwrap();
124 | println!("Output rendered to: {}", path.display());
125 |
126 | unsafe {
127 | // Unbind the framebuffer and renderbuffer before deleting.
128 | renderer.BindFramebuffer(gl::DRAW_FRAMEBUFFER, 0);
129 | renderer.BindRenderbuffer(gl::RENDERBUFFER, 0);
130 | renderer.DeleteFramebuffers(1, &framebuffer);
131 | renderer.DeleteRenderbuffers(1, &renderbuffer);
132 | }
133 | }
134 |
135 | fn config_template() -> ConfigTemplate {
136 | ConfigTemplateBuilder::default()
137 | .with_alpha_size(8)
138 | // Offscreen rendering has no support window surface support.
139 | .with_surface_type(ConfigSurfaceTypes::empty())
140 | .build()
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/glutin_examples/examples/window.rs:
--------------------------------------------------------------------------------
1 | use winit::event_loop::EventLoop;
2 |
3 | fn main() {
4 | glutin_examples::main(EventLoop::new())
5 | }
6 |
--------------------------------------------------------------------------------
/glutin_examples/src/lib.rs:
--------------------------------------------------------------------------------
1 | use std::ffi::{CStr, CString};
2 | use std::num::NonZeroU32;
3 | use std::ops::Deref;
4 |
5 | use winit::event::{Event, WindowEvent};
6 | use winit::event_loop::ControlFlow;
7 | use winit::window::WindowBuilder;
8 |
9 | use raw_window_handle::HasRawWindowHandle;
10 |
11 | use glutin::config::ConfigTemplateBuilder;
12 | use glutin::context::{ContextApi, ContextAttributesBuilder, Version};
13 | use glutin::display::GetGlDisplay;
14 | use glutin::prelude::*;
15 | use glutin::surface::SwapInterval;
16 |
17 | use glutin_tao::{self, DisplayBuilder, GlWindow};
18 |
19 | pub mod gl {
20 | #![allow(clippy::all)]
21 | include!(concat!(env!("OUT_DIR"), "/gl_bindings.rs"));
22 |
23 | pub use Gles2 as Gl;
24 | }
25 |
26 | pub fn main(event_loop: winit::event_loop::EventLoop<()>) {
27 | // Only windows requires the window to be present before creating the display.
28 | // Other platforms don't really need one.
29 | //
30 | // XXX if you don't care about running on android or so you can safely remove
31 | // this condition and always pass the window builder.
32 | let window_builder =
33 | if cfg!(wgl_backend) { Some(WindowBuilder::new().with_transparent(true)) } else { None };
34 |
35 | // The template will match only the configurations supporting rendering
36 | // to windows.
37 | //
38 | // XXX We force transparency only on macOS, given that EGL on X11 doesn't
39 | // have it, but we still want to show window. The macOS situation is like
40 | // that, because we can query only one config at a time on it, but all
41 | // normal platforms will return multiple configs, so we can find the config
42 | // with transparency ourselves inside the `reduce`.
43 | let template =
44 | ConfigTemplateBuilder::new().with_alpha_size(8).with_transparency(cfg!(cgl_backend));
45 |
46 | let display_builder = DisplayBuilder::new().with_window_builder(window_builder);
47 |
48 | let (mut window, gl_config) = display_builder
49 | .build(&event_loop, template, |configs| {
50 | // Find the config with the maximum number of samples, so our triangle will
51 | // be smooth.
52 | configs
53 | .reduce(|accum, config| {
54 | let transparency_check = config.supports_transparency().unwrap_or(false)
55 | & !accum.supports_transparency().unwrap_or(false);
56 |
57 | if transparency_check || config.num_samples() > accum.num_samples() {
58 | config
59 | } else {
60 | accum
61 | }
62 | })
63 | .unwrap()
64 | })
65 | .unwrap();
66 |
67 | println!("Picked a config with {} samples", gl_config.num_samples());
68 |
69 | let raw_window_handle = window.as_ref().map(|window| window.raw_window_handle());
70 |
71 | // XXX The display could be obtained from the any object created by it, so we
72 | // can query it from the config.
73 | let gl_display = gl_config.display();
74 |
75 | // The context creation part. It can be created before surface and that's how
76 | // it's expected in multithreaded + multiwindow operation mode, since you
77 | // can send NotCurrentContext, but not Surface.
78 | let context_attributes = ContextAttributesBuilder::new().build(raw_window_handle);
79 |
80 | // Since glutin by default tries to create OpenGL core context, which may not be
81 | // present we should try gles.
82 | let fallback_context_attributes = ContextAttributesBuilder::new()
83 | .with_context_api(ContextApi::Gles(None))
84 | .build(raw_window_handle);
85 |
86 | // There are also some old devices that support neither modern OpenGL nor GLES.
87 | // To support these we can try and create a 2.1 context.
88 | let legacy_context_attributes = ContextAttributesBuilder::new()
89 | .with_context_api(ContextApi::OpenGl(Some(Version::new(2, 1))))
90 | .build(raw_window_handle);
91 |
92 | let mut not_current_gl_context = Some(unsafe {
93 | gl_display.create_context(&gl_config, &context_attributes).unwrap_or_else(|_| {
94 | gl_display.create_context(&gl_config, &fallback_context_attributes).unwrap_or_else(
95 | |_| {
96 | gl_display
97 | .create_context(&gl_config, &legacy_context_attributes)
98 | .expect("failed to create context")
99 | },
100 | )
101 | })
102 | });
103 |
104 | let mut state = None;
105 | let mut renderer = None;
106 | event_loop.run(move |event, window_target, control_flow| {
107 | *control_flow = ControlFlow::Wait;
108 | match event {
109 | Event::Resumed | winit::event::Event::NewEvents(winit::event::StartCause::Init) => {
110 | #[cfg(android_platform)]
111 | println!("Android window available");
112 |
113 | let window = window.take().unwrap_or_else(|| {
114 | let window_builder = WindowBuilder::new().with_transparent(true);
115 | glutin_tao::finalize_window(window_target, window_builder, &gl_config)
116 | .unwrap()
117 | });
118 |
119 | let attrs = window.build_surface_attributes(<_>::default());
120 | let gl_surface = unsafe {
121 | gl_config.display().create_window_surface(&gl_config, &attrs).unwrap()
122 | };
123 |
124 | // Make it current.
125 | let gl_context =
126 | not_current_gl_context.take().unwrap().make_current(&gl_surface).unwrap();
127 |
128 | // The context needs to be current for the Renderer to set up shaders and
129 | // buffers. It also performs function loading, which needs a current context on
130 | // WGL.
131 | renderer.get_or_insert_with(|| Renderer::new(&gl_display));
132 |
133 | // Try setting vsync.
134 | if let Err(res) = gl_surface
135 | .set_swap_interval(&gl_context, SwapInterval::Wait(NonZeroU32::new(1).unwrap()))
136 | {
137 | eprintln!("Error setting vsync: {res:?}");
138 | }
139 |
140 | assert!(state.replace((gl_context, gl_surface, window)).is_none());
141 | },
142 | Event::Suspended => {
143 | // This event is only raised on Android, where the backing NativeWindow for a GL
144 | // Surface can appear and disappear at any moment.
145 | println!("Android window removed");
146 |
147 | // Destroy the GL Surface and un-current the GL Context before ndk-glue releases
148 | // the window back to the system.
149 | let (gl_context, ..) = state.take().unwrap();
150 | assert!(not_current_gl_context
151 | .replace(gl_context.make_not_current().unwrap())
152 | .is_none());
153 | },
154 | Event::WindowEvent { event, .. } => match event {
155 | WindowEvent::Resized(size) => {
156 | if size.width != 0 && size.height != 0 {
157 | // Some platforms like EGL require resizing GL surface to update the size
158 | // Notable platforms here are Wayland and macOS, other don't require it
159 | // and the function is no-op, but it's wise to resize it for portability
160 | // reasons.
161 | if let Some((gl_context, gl_surface, _)) = &state {
162 | gl_surface.resize(
163 | gl_context,
164 | NonZeroU32::new(size.width).unwrap(),
165 | NonZeroU32::new(size.height).unwrap(),
166 | );
167 | let renderer = renderer.as_ref().unwrap();
168 | renderer.resize(size.width as i32, size.height as i32);
169 | }
170 | }
171 | },
172 | WindowEvent::CloseRequested => {
173 | *control_flow = ControlFlow::Exit;
174 | },
175 | _ => (),
176 | },
177 | Event::RedrawEventsCleared => {
178 | if let Some((gl_context, gl_surface, window)) = &state {
179 | let renderer = renderer.as_ref().unwrap();
180 | renderer.draw();
181 | window.request_redraw();
182 |
183 | gl_surface.swap_buffers(gl_context).unwrap();
184 | }
185 | },
186 | _ => (),
187 | }
188 | })
189 | }
190 |
191 | pub struct Renderer {
192 | program: gl::types::GLuint,
193 | vao: gl::types::GLuint,
194 | vbo: gl::types::GLuint,
195 | gl: gl::Gl,
196 | }
197 |
198 | impl Renderer {
199 | pub fn new(gl_display: &D) -> Self {
200 | unsafe {
201 | let gl = gl::Gl::load_with(|symbol| {
202 | let symbol = CString::new(symbol).unwrap();
203 | gl_display.get_proc_address(symbol.as_c_str()).cast()
204 | });
205 |
206 | if let Some(renderer) = get_gl_string(&gl, gl::RENDERER) {
207 | println!("Running on {}", renderer.to_string_lossy());
208 | }
209 | if let Some(version) = get_gl_string(&gl, gl::VERSION) {
210 | println!("OpenGL Version {}", version.to_string_lossy());
211 | }
212 |
213 | if let Some(shaders_version) = get_gl_string(&gl, gl::SHADING_LANGUAGE_VERSION) {
214 | println!("Shaders version on {}", shaders_version.to_string_lossy());
215 | }
216 |
217 | let vertex_shader = create_shader(&gl, gl::VERTEX_SHADER, VERTEX_SHADER_SOURCE);
218 | let fragment_shader = create_shader(&gl, gl::FRAGMENT_SHADER, FRAGMENT_SHADER_SOURCE);
219 |
220 | let program = gl.CreateProgram();
221 |
222 | gl.AttachShader(program, vertex_shader);
223 | gl.AttachShader(program, fragment_shader);
224 |
225 | gl.LinkProgram(program);
226 |
227 | gl.UseProgram(program);
228 |
229 | gl.DeleteShader(vertex_shader);
230 | gl.DeleteShader(fragment_shader);
231 |
232 | let mut vao = std::mem::zeroed();
233 | gl.GenVertexArrays(1, &mut vao);
234 | gl.BindVertexArray(vao);
235 |
236 | let mut vbo = std::mem::zeroed();
237 | gl.GenBuffers(1, &mut vbo);
238 | gl.BindBuffer(gl::ARRAY_BUFFER, vbo);
239 | gl.BufferData(
240 | gl::ARRAY_BUFFER,
241 | (VERTEX_DATA.len() * std::mem::size_of::()) as gl::types::GLsizeiptr,
242 | VERTEX_DATA.as_ptr() as *const _,
243 | gl::STATIC_DRAW,
244 | );
245 |
246 | let pos_attrib = gl.GetAttribLocation(program, b"position\0".as_ptr() as *const _);
247 | let color_attrib = gl.GetAttribLocation(program, b"color\0".as_ptr() as *const _);
248 | gl.VertexAttribPointer(
249 | pos_attrib as gl::types::GLuint,
250 | 2,
251 | gl::FLOAT,
252 | 0,
253 | 5 * std::mem::size_of::() as gl::types::GLsizei,
254 | std::ptr::null(),
255 | );
256 | gl.VertexAttribPointer(
257 | color_attrib as gl::types::GLuint,
258 | 3,
259 | gl::FLOAT,
260 | 0,
261 | 5 * std::mem::size_of::() as gl::types::GLsizei,
262 | (2 * std::mem::size_of::()) as *const () as *const _,
263 | );
264 | gl.EnableVertexAttribArray(pos_attrib as gl::types::GLuint);
265 | gl.EnableVertexAttribArray(color_attrib as gl::types::GLuint);
266 |
267 | Self { program, vao, vbo, gl }
268 | }
269 | }
270 |
271 | pub fn draw(&self) {
272 | unsafe {
273 | self.gl.UseProgram(self.program);
274 |
275 | self.gl.BindVertexArray(self.vao);
276 | self.gl.BindBuffer(gl::ARRAY_BUFFER, self.vbo);
277 |
278 | self.gl.ClearColor(0.1, 0.1, 0.1, 0.9);
279 | self.gl.Clear(gl::COLOR_BUFFER_BIT);
280 | self.gl.DrawArrays(gl::TRIANGLES, 0, 3);
281 | }
282 | }
283 |
284 | pub fn resize(&self, width: i32, height: i32) {
285 | unsafe {
286 | self.gl.Viewport(0, 0, width, height);
287 | }
288 | }
289 | }
290 |
291 | impl Deref for Renderer {
292 | type Target = gl::Gl;
293 |
294 | fn deref(&self) -> &Self::Target {
295 | &self.gl
296 | }
297 | }
298 |
299 | impl Drop for Renderer {
300 | fn drop(&mut self) {
301 | unsafe {
302 | self.gl.DeleteProgram(self.program);
303 | self.gl.DeleteBuffers(1, &self.vbo);
304 | self.gl.DeleteVertexArrays(1, &self.vao);
305 | }
306 | }
307 | }
308 |
309 | unsafe fn create_shader(
310 | gl: &gl::Gl,
311 | shader: gl::types::GLenum,
312 | source: &[u8],
313 | ) -> gl::types::GLuint {
314 | let shader = gl.CreateShader(shader);
315 | gl.ShaderSource(shader, 1, [source.as_ptr().cast()].as_ptr(), std::ptr::null());
316 | gl.CompileShader(shader);
317 | shader
318 | }
319 |
320 | fn get_gl_string(gl: &gl::Gl, variant: gl::types::GLenum) -> Option<&'static CStr> {
321 | unsafe {
322 | let s = gl.GetString(variant);
323 | (!s.is_null()).then(|| CStr::from_ptr(s.cast()))
324 | }
325 | }
326 |
327 | #[rustfmt::skip]
328 | static VERTEX_DATA: [f32; 15] = [
329 | -0.5, -0.5, 1.0, 0.0, 0.0,
330 | 0.0, 0.5, 0.0, 1.0, 0.0,
331 | 0.5, -0.5, 0.0, 0.0, 1.0,
332 | ];
333 |
334 | const VERTEX_SHADER_SOURCE: &[u8] = b"
335 | #version 100
336 | precision mediump float;
337 |
338 | attribute vec2 position;
339 | attribute vec3 color;
340 |
341 | varying vec3 v_color;
342 |
343 | void main() {
344 | gl_Position = vec4(position, 0.0, 1.0);
345 | v_color = color;
346 | }
347 | \0";
348 |
349 | const FRAGMENT_SHADER_SOURCE: &[u8] = b"
350 | #version 100
351 | precision mediump float;
352 |
353 | varying vec3 v_color;
354 |
355 | void main() {
356 | gl_FragColor = vec4(v_color, 1.0);
357 | }
358 | \0";
359 |
--------------------------------------------------------------------------------
/rustfmt.toml:
--------------------------------------------------------------------------------
1 | format_code_in_doc_comments = true
2 | match_block_trailing_comma = true
3 | condense_wildcard_suffixes = true
4 | use_field_init_shorthand = true
5 | normalize_doc_attributes = true
6 | overflow_delimited_expr = true
7 | imports_granularity = "Module"
8 | use_small_heuristics = "Max"
9 | normalize_comments = true
10 | reorder_impl_items = true
11 | use_try_shorthand = true
12 | newline_style = "Unix"
13 | format_strings = true
14 | wrap_comments = true
15 | comment_width = 80
16 | edition = "2021"
17 |
--------------------------------------------------------------------------------