├── .gitignore ├── .idea ├── gradle.xml ├── markdown-navigator.xml ├── markdown-navigator │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── CMakeLists.txt ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── linuxpara │ │ └── agles20tutorials │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── camera │ │ │ ├── camera.frag │ │ │ └── camera.vert │ │ ├── cube │ │ │ ├── cube.frag │ │ │ └── cube.vert │ │ ├── earth │ │ │ ├── earth.frag │ │ │ └── earth.vert │ │ └── triangle │ │ │ ├── triangle.frag │ │ │ └── triangle.vert │ ├── cpp │ │ └── native-lib.cpp │ ├── java │ │ └── com │ │ │ └── linuxpara │ │ │ └── agles20tutorials │ │ │ ├── GraphicalRender.java │ │ │ ├── MainActivity.java │ │ │ ├── camera │ │ │ ├── CameraActivity.java │ │ │ └── widget │ │ │ │ ├── CameraBridge.java │ │ │ │ ├── CameraDrawer.java │ │ │ │ ├── CameraView.java │ │ │ │ ├── camera │ │ │ │ ├── CameraV2.java │ │ │ │ ├── ICamera.java │ │ │ │ └── Size.java │ │ │ │ └── video │ │ │ │ └── VideoEncoder.java │ │ │ ├── cube │ │ │ ├── CubeActivity.java │ │ │ └── CubeRender.java │ │ │ ├── earth │ │ │ ├── EarthActivity.java │ │ │ └── EarthRender.java │ │ │ ├── triangle │ │ │ ├── TriangleActivity.java │ │ │ └── TriangleRender.java │ │ │ └── util │ │ │ └── ShaderUtils.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ ├── activity_camera.xml │ │ ├── activity_cube.xml │ │ ├── activity_earth.xml │ │ ├── activity_main.xml │ │ └── activity_triangle.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── box.png │ │ ├── earth.jpg │ │ ├── ic_capture.png │ │ ├── ic_launcher.png │ │ ├── ic_launcher_round.png │ │ ├── ic_switch_camera.png │ │ └── ic_video_capture.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── attrs.xml │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── linuxpara │ └── agles20tutorials │ └── ExampleUnitTest.java ├── build.gradle ├── effect ├── 三角形绘制效果.png ├── 地球绘制效果.gif └── 立方体效果.gif ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | -------------------------------------------------------------------------------- /.idea/markdown-navigator.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 36 | 37 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /.idea/markdown-navigator/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 26 | 27 | 28 | 29 | 30 | 31 | 33 | 34 | 35 | 36 | 37 | 38 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 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 [LinuxparaChen] [陈占洋] 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 | # AGLES20Tutorials 2 | --- 3 | 4 | Android平台下OpenGL ES 2.0教程代码。 5 | 原文[Android OpenGL ES 2.0 Tutorials](https://linuxparachen.gitbooks.io/android-opengl-es-2-0-tutorials/content/) 6 | 7 | author:陈占洋 8 | 9 | email: 10 | 11 | 内容禁止用于商业用途,侵权必究。 12 | 13 | 案列效果: 14 | 1. 三角形绘制 15 | 16 | ![三角形绘制效果](effect/三角形绘制效果.png) 17 | 18 | 2. 立方体绘制效果 19 | 20 | ![立方体绘制效果](effect/立方体效果.gif) 21 | 22 | 3. 地球绘制效果 23 | 24 | ![地球绘制效果](effect/地球绘制效果.gif) 25 | 26 | 5. 摄像头预览效果 27 | 28 | [LICENSE](https://github.com/LinuxparaChen/AGLES2.0Tutorials/blob/master/LICENSE) 29 | 30 | Licensed under the Apache License, Version 2.0 (the "License"); 31 | you may not use this file except in compliance with the License. 32 | You may obtain a copy of the License at 33 | 34 | http://www.apache.org/licenses/LICENSE-2.0 35 | 36 | Unless required by applicable law or agreed to in writing, software 37 | distributed under the License is distributed on an "AS IS" BASIS, 38 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 39 | See the License for the specific language governing permissions and 40 | limitations under the License. -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # For more information about using CMake with Android Studio, read the 2 | # documentation: https://d.android.com/studio/projects/add-native-code.html 3 | 4 | # Sets the minimum version of CMake required to build the native library. 5 | 6 | cmake_minimum_required(VERSION 3.4.1) 7 | 8 | # Creates and names a library, sets it as either STATIC 9 | # or SHARED, and provides the relative paths to its source code. 10 | # You can define multiple libraries, and CMake builds them for you. 11 | # Gradle automatically packages shared libraries with your APK. 12 | 13 | add_library( # Sets the name of the library. 14 | native-lib 15 | 16 | # Sets the library as a shared library. 17 | SHARED 18 | 19 | # Provides a relative path to your source file(s). 20 | src/main/cpp/native-lib.cpp ) 21 | 22 | # Searches for a specified prebuilt library and stores the path as a 23 | # variable. Because CMake includes system libraries in the search path by 24 | # default, you only need to specify the name of the public NDK library 25 | # you want to add. CMake verifies that the library exists before 26 | # completing its build. 27 | 28 | find_library( # Sets the name of the path variable. 29 | log-lib 30 | 31 | # Specifies the name of the NDK library that 32 | # you want CMake to locate. 33 | log ) 34 | 35 | # Specifies libraries CMake should link to your target library. You 36 | # can link multiple libraries, such as libraries you define in this 37 | # build script, prebuilt third-party libraries, or system libraries. 38 | 39 | target_link_libraries( # Specifies the target library. 40 | native-lib 41 | 42 | # Links the target library to the log library 43 | # included in the NDK. 44 | ${log-lib} ) -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | defaultConfig { 6 | applicationId "com.linuxpara.agles20tutorials" 7 | minSdkVersion 19 8 | targetSdkVersion 26 9 | versionCode 1 10 | versionName "1.0" 11 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 12 | externalNativeBuild { 13 | cmake { 14 | cppFlags "-std=c++11 -frtti -fexceptions" 15 | } 16 | } 17 | } 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | externalNativeBuild { 25 | cmake { 26 | path "CMakeLists.txt" 27 | } 28 | } 29 | compileOptions { 30 | targetCompatibility 1.8 31 | sourceCompatibility 1.8 32 | } 33 | } 34 | 35 | dependencies { 36 | implementation fileTree(dir: 'libs', include: ['*.jar']) 37 | implementation 'com.android.support:appcompat-v7:26.0.0-beta1' 38 | implementation 'com.android.support.constraint:constraint-layout:1.0.2' 39 | testImplementation 'junit:junit:4.12' 40 | androidTestImplementation 'com.android.support.test:runner:0.5' 41 | androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2' 42 | //butterknife 43 | compile 'com.jakewharton:butterknife:8.8.1' 44 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' 45 | //rxjava 46 | implementation "io.reactivex.rxjava2:rxjava:2.1.10" 47 | implementation 'io.reactivex.rxjava2:rxandroid:2.0.2' 48 | //rxpermissions 49 | implementation 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar' 50 | } 51 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/linuxpara/agles20tutorials/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumented test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.linuxpara.agles20tutorials", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /app/src/main/assets/camera/camera.frag: -------------------------------------------------------------------------------- 1 | 2 | #extension GL_OES_EGL_image_external : require//请求使用外部纹理。摄像头纹理需要开启。 3 | precision mediump float; 4 | 5 | varying vec2 v_texCoord; 6 | //纹理坐标矩阵,前后摄像头位置旋转角度不一样,返回的图片数据不是正向图片。 7 | //此矩阵可以纠正,由系统返回。 8 | uniform mat4 u_coordMatrix; 9 | 10 | uniform int u_effect; 11 | uniform float u_warmCoolStrength;//冷暖色调强度 12 | 13 | uniform int u_kernelSize;//卷积核大小 14 | uniform ivec2 u_imgWH;//图像大小 15 | 16 | uniform samplerExternalOES u_texSampler;//扩展(外部)纹理采样器 17 | 18 | void main() { 19 | vec4 texColor = texture2D(u_texSampler,(u_coordMatrix * vec4(v_texCoord,0.0,1.0)).xy); 20 | if(u_effect == 0){ 21 | //原始 22 | gl_FragColor = texColor; 23 | }else if(u_effect == 1){ 24 | //灰度 25 | float gray = 0.299 * texColor.r + 0.587 * texColor.g + 0.114 * texColor.b; 26 | gl_FragColor = vec4(gray,gray,gray,texColor.a); 27 | }else if(u_effect == 2){ 28 | //底片 29 | gl_FragColor = vec4(1.0 - texColor.r,1.0 - texColor.g,1.0 - texColor.b,texColor.a); 30 | }else if(u_effect == 3){ 31 | //冷暖色 32 | if(u_warmCoolStrength > 0.0){ 33 | //暖色 34 | gl_FragColor = vec4(texColor.r + u_warmCoolStrength,texColor.g,texColor.b,texColor.a); 35 | }else{ 36 | //冷色 37 | gl_FragColor = vec4(texColor.r,texColor.g,texColor.b + u_warmCoolStrength,texColor.a); 38 | } 39 | }else if(u_effect == 4){ 40 | //浮雕 41 | int kernel_r = u_kernelSize/2;//卷积核半径 42 | float kernel_r_s = float(kernel_r)/float(u_imgWH.s);//卷积核半径,换算成纹理单位s轴 43 | float kernel_r_t = float(kernel_r)/float(u_imgWH.t);//卷积核半径,换算成纹理单位t轴 44 | vec4 lt_color = texture2D(u_texSampler,(u_coordMatrix * vec4(v_texCoord.s - kernel_r_s,v_texCoord.t + kernel_r_t,0.0,1.0)).xy); 45 | vec4 rb_color = texture2D(u_texSampler,(u_coordMatrix * vec4(v_texCoord.s + kernel_r_s,v_texCoord.t - kernel_r_t,0.0,1.0)).xy); 46 | gl_FragColor = rb_color - lt_color + 0.5; 47 | }else if(u_effect == 5){ 48 | //雕刻 49 | int kernel_r = u_kernelSize/2;//卷积核半径 50 | float kernel_r_s = float(kernel_r)/float(u_imgWH.s);//卷积核半径,换算成纹理单位s轴 51 | float kernel_r_t = float(kernel_r)/float(u_imgWH.t);//卷积核半径,换算成纹理单位t轴 52 | vec4 lt_color = texture2D(u_texSampler,(u_coordMatrix * vec4(v_texCoord.s - kernel_r_s,v_texCoord.t + kernel_r_t,0.0,1.0)).xy); 53 | vec4 rb_color = texture2D(u_texSampler,(u_coordMatrix * vec4(v_texCoord.s + kernel_r_s,v_texCoord.t - kernel_r_t,0.0,1.0)).xy); 54 | gl_FragColor = lt_color - rb_color + 0.5; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /app/src/main/assets/camera/camera.vert: -------------------------------------------------------------------------------- 1 | 2 | attribute vec3 a_position; 3 | attribute vec2 a_texCoord; 4 | 5 | uniform mat4 u_MMatrix; 6 | uniform mat4 u_VMatrix; 7 | uniform mat4 u_ProjMatrix; 8 | 9 | varying vec2 v_texCoord; 10 | 11 | void main() { 12 | gl_Position = u_ProjMatrix * u_VMatrix * u_MMatrix * vec4(a_position, 1.0); 13 | v_texCoord = a_texCoord; 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/assets/cube/cube.frag: -------------------------------------------------------------------------------- 1 | precision mediump float; 2 | 3 | uniform sampler2D u_texSampler; 4 | 5 | varying vec2 v_texCoord; 6 | 7 | void main() { 8 | gl_FragColor = texture2D(u_texSampler,v_texCoord); 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/assets/cube/cube.vert: -------------------------------------------------------------------------------- 1 | attribute vec3 a_position; 2 | attribute vec2 a_texCoord; 3 | 4 | uniform mat4 u_MMatrix; 5 | uniform mat4 u_VMatrix; 6 | uniform mat4 u_ProjMatrix; 7 | 8 | varying vec2 v_texCoord; 9 | 10 | void main() { 11 | gl_Position = u_ProjMatrix * u_VMatrix * u_MMatrix * vec4(a_position, 1.0); 12 | v_texCoord = a_texCoord; 13 | } 14 | -------------------------------------------------------------------------------- /app/src/main/assets/earth/earth.frag: -------------------------------------------------------------------------------- 1 | precision mediump float; 2 | 3 | varying vec2 v_texCoord; 4 | 5 | uniform sampler2D u_texSampler; 6 | 7 | varying vec3 v_lightPos; 8 | varying vec3 v_viewPos; 9 | varying vec3 v_fragPos; 10 | varying vec3 v_N; 11 | 12 | varying vec4 v_lightColor; 13 | 14 | /** 15 | * 环境光计算公式 16 | * @param lightColor 光源颜色 17 | * @param ambientStrength 环境光强度 18 | */ 19 | vec4 ambient(vec4 lightColor,float ambientStrength){ 20 | return ambientStrength * lightColor; 21 | } 22 | /** 23 | * 漫反射光计算公式 24 | * @param lightColor 光源颜色 25 | * @param lightPos 光源位置 26 | * @param fragPos 顶点坐标(世界坐标) 27 | * @param N 顶点法线(法线为归一化后的向量) 28 | */ 29 | vec4 diffuse(vec4 lightColor,vec3 lightPos,vec3 fragPos,vec3 N){ 30 | vec3 lightDir = normalize(lightPos - fragPos);//归一化后的光源方向 31 | float diffuseFactor = max(dot(lightDir,N),0.0);//光照方向与法线夹角的余弦值,过滤掉比0小的值 32 | return diffuseFactor * lightColor; 33 | } 34 | /** 35 | * 镜面光计算公式 36 | * @param lightColor 光源颜色 37 | * @param lightPos 光源位置 38 | * @param fragPos 顶点坐标(世界坐标) 39 | * @param N 顶点法向量(归一化后的) 40 | * @param viewPos 观察点坐标 41 | * @param reflectDeg 反射度 42 | * @param specularStrength 镜面光强度 43 | */ 44 | vec4 specular(vec4 lightColor,vec3 lightPos,vec3 fragPos,vec3 viewPos 45 | ,vec3 N,float reflectDeg,float specularStrength){ 46 | vec3 lightDir = normalize(lightPos - fragPos);//光源方向 47 | vec3 reflectDir = reflect(-lightDir,N);//反射光方向 48 | vec3 viewDir = normalize(viewPos - fragPos);//观察点方向 49 | float specularFactor = pow(max(dot(reflectDir,viewDir),0.0),reflectDeg); 50 | return specularStrength * specularFactor * lightColor; 51 | } 52 | 53 | void main() { 54 | vec4 ambientColor = ambient(v_lightColor,0.1); 55 | vec4 diffuseColor = diffuse(v_lightColor,v_lightPos,v_fragPos,v_N); 56 | vec4 specularColor = specular(v_lightColor,v_lightPos,v_fragPos,v_viewPos,v_N,8.0,1.0); 57 | vec4 texColor = texture2D(u_texSampler,v_texCoord); 58 | // gl_FragColor = texColor; 59 | gl_FragColor = (ambientColor + diffuseColor + specularColor) * texColor; 60 | } 61 | -------------------------------------------------------------------------------- /app/src/main/assets/earth/earth.vert: -------------------------------------------------------------------------------- 1 | attribute vec3 a_position; 2 | attribute vec2 a_texCoord; 3 | uniform vec3 u_lightPos;//光源位置,不能用attribute,如果非要用需要生成与顶点个数相同个颜色。 4 | uniform vec3 u_viewPos;//观察点位置 5 | uniform vec4 u_lightColor;//光源颜色 6 | 7 | uniform mat4 u_MMatrix; 8 | uniform mat4 u_VMatrix; 9 | uniform mat4 u_ProjMatrix; 10 | 11 | varying vec2 v_texCoord; 12 | 13 | varying vec3 v_lightPos; 14 | varying vec3 v_viewPos; 15 | varying vec3 v_fragPos; 16 | varying vec3 v_N; 17 | 18 | varying vec4 v_lightColor; 19 | void main() { 20 | gl_Position = u_ProjMatrix * u_VMatrix * u_MMatrix * vec4(a_position,1.0); 21 | v_texCoord = a_texCoord; 22 | 23 | v_lightPos = u_lightPos; 24 | v_viewPos = u_viewPos; 25 | v_fragPos = (u_MMatrix * vec4(a_position,1.0)).xyz; 26 | // 在这个GLSL版本中没有transpose、inverse函数,我们在u_MMatrix没有做不等比例缩放,这一步可以省略。 27 | // mat4 nMatrix = transpose(inverse(u_MMatrix));//法向量矩阵 28 | //法向量 29 | v_N = normalize((u_MMatrix * vec4(a_position,1.0)).xyz); 30 | v_lightColor = u_lightColor; 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/assets/triangle/triangle.frag: -------------------------------------------------------------------------------- 1 | //指定float的精度为中等 2 | precision mediump float;//必须指定,有时候的错误是因为没有指定精度,找错找不到。 3 | //接收顶点着色器传过来的颜色变量 4 | varying vec4 v_color; 5 | 6 | void main() { 7 | //gl_FragColor 内部变量 8 | gl_FragColor = v_color; 9 | } 10 | -------------------------------------------------------------------------------- /app/src/main/assets/triangle/triangle.vert: -------------------------------------------------------------------------------- 1 | 2 | //三角形的顶点坐标 3 | attribute vec3 a_position;//attribute 属性修饰符 4 | //三角形的顶点颜色值(rgba) 5 | attribute vec4 a_color; 6 | //模型矩阵 7 | uniform mat4 u_MMatrix;//uniform 统一修饰符 8 | //观察矩阵 9 | uniform mat4 u_VMatrix; 10 | //投影矩阵 11 | uniform mat4 u_ProjMatrix; 12 | //传给片元着色器的颜色值 13 | varying vec4 v_color;//varying 顶点、片元着色器传值,变量名需要完全一致。 14 | 15 | void main() { 16 | //gl_Position 内部变量。 17 | gl_Position = u_ProjMatrix * u_VMatrix * u_MMatrix * vec4(a_position,1.0); 18 | v_color = a_color; 19 | } 20 | -------------------------------------------------------------------------------- /app/src/main/cpp/native-lib.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | extern "C" 5 | JNIEXPORT jstring JNICALL 6 | Java_com_linuxpara_agles20tutorials_MainActivity_stringFromJNI( 7 | JNIEnv *env, 8 | jobject /* this */) { 9 | std::string hello = "Hello from C++"; 10 | return env->NewStringUTF(hello.c_str()); 11 | } 12 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/GraphicalRender.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials; 2 | 3 | import android.graphics.Bitmap; 4 | import android.opengl.GLES20; 5 | import android.opengl.GLSurfaceView; 6 | import android.opengl.GLUtils; 7 | import android.opengl.Matrix; 8 | 9 | 10 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 11 | 12 | import java.lang.ref.WeakReference; 13 | 14 | import javax.microedition.khronos.egl.EGLConfig; 15 | import javax.microedition.khronos.opengles.GL10; 16 | 17 | /** 18 | * Date: 2018/1/15 19 | * ************************************************************* 20 | * Auther: 陈占洋 21 | * ************************************************************* 22 | * Email: zhanyang.chen@gmail.com 23 | * ************************************************************* 24 | * Description: 图形渲染器,提取了GL绘制图形的一些公共方法 25 | */ 26 | 27 | public abstract class GraphicalRender implements GLSurfaceView.Renderer{ 28 | 29 | //4*4的投影矩阵 30 | public static float[] sProjMatrix = new float[16]; 31 | //4*4摄像头矩阵(观察矩阵) 32 | public static float[] sVMatrix = new float[16]; 33 | //4*4模型矩阵(变化矩阵) 34 | public static float[] sMMatrix = new float[16]; 35 | 36 | protected WeakReference mWeakRefView; 37 | 38 | public GraphicalRender(GLSurfaceView view) { 39 | mWeakRefView = new WeakReference<>(view); 40 | } 41 | 42 | /** 43 | * 界面被创建时被调用 44 | * @param gl 45 | * @param config 46 | */ 47 | @Override 48 | public void onSurfaceCreated(GL10 gl, EGLConfig config) { 49 | onCreate(); 50 | } 51 | 52 | /** 53 | * 界面改变时被调用 54 | * @param gl 55 | * @param width 56 | * @param height 57 | */ 58 | @Override 59 | public void onSurfaceChanged(GL10 gl, int width, int height) { 60 | onChange(width,height); 61 | } 62 | 63 | /** 64 | * 绘制一帧内容时被调用 65 | * @param gl 66 | */ 67 | @Override 68 | public void onDrawFrame(GL10 gl) { 69 | onDraw(); 70 | } 71 | 72 | public abstract void onCreate(); 73 | 74 | public abstract void onChange(int width, int height); 75 | 76 | public abstract void onDraw(); 77 | 78 | /** 79 | * 初始化着色器 80 | * 81 | * @param shaderTag 82 | * @param verFileName 83 | * @param fragFileName 84 | */ 85 | protected void initShaderFromAsset(int shaderTag,String verFileName, String fragFileName) { 86 | String verCode = ShaderUtils.getCodeFromAsset(verFileName, getView().getResources()); 87 | String fragCode = ShaderUtils.getCodeFromAsset(fragFileName, getView().getResources()); 88 | int shaderProgram = ShaderUtils.createProgram(verCode, fragCode); 89 | findShaderAttr(shaderTag,shaderProgram); 90 | } 91 | 92 | /** 93 | * 查找着色器属性。 94 | * @param shaderTag 95 | * @param shaderProgram 96 | */ 97 | protected abstract void findShaderAttr(int shaderTag, int shaderProgram); 98 | 99 | /** 100 | * 初始化顶点缓存 101 | */ 102 | protected void initVert() { 103 | 104 | } 105 | 106 | /** 107 | * 初始化顶点索引 108 | */ 109 | protected void initVertIdx(){ 110 | 111 | } 112 | 113 | /** 114 | * 初始化顶点颜色缓存 115 | */ 116 | protected void initVertColor() { 117 | 118 | } 119 | 120 | /** 121 | * 初始化纹理坐标 122 | */ 123 | protected void initTextureCoord() { 124 | 125 | } 126 | 127 | /** 128 | * 初始化3D模型 129 | */ 130 | protected void initObjMtl() { 131 | 132 | } 133 | 134 | /** 135 | * 生成bitmap贴图纹理Id 136 | * 137 | * @param bitmap 138 | */ 139 | protected int genBitmapTextureId(Bitmap bitmap) { 140 | int textureId = ShaderUtils.genTextureId(); 141 | if (bitmap == null || bitmap.isRecycled()) { 142 | throw new RuntimeException("传入的图片为空或者已经呗释放掉了!"); 143 | } 144 | GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); 145 | return textureId; 146 | } 147 | 148 | /** 149 | * 获取总变换矩阵 150 | * 151 | * @param matrix 152 | * @return 153 | */ 154 | protected float[] getMVPMatrix(float[] matrix) { 155 | 156 | float[] mvpMatrix = new float[16]; 157 | //mvpMatrix = sVMatrix × matrix 158 | Matrix.multiplyMM(mvpMatrix, 0, 159 | sVMatrix, 0, 160 | matrix, 0); 161 | //mvpMatrix = sProjMatrix × mvpMatrix 162 | Matrix.multiplyMM(mvpMatrix, 0, 163 | sProjMatrix, 0, 164 | mvpMatrix, 0); 165 | 166 | return mvpMatrix; 167 | } 168 | 169 | protected GLSurfaceView getView(){ 170 | if (mWeakRefView == null || mWeakRefView.get() == null) { 171 | throw new RuntimeException("初始化着色器,需要在界面销毁前执行!!!"); 172 | } 173 | return mWeakRefView.get(); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials; 2 | 3 | import android.content.Intent; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.Toast; 9 | 10 | import com.linuxpara.agles20tutorials.camera.CameraActivity; 11 | import com.linuxpara.agles20tutorials.cube.CubeActivity; 12 | import com.linuxpara.agles20tutorials.earth.EarthActivity; 13 | import com.linuxpara.agles20tutorials.triangle.TriangleActivity; 14 | 15 | import java.util.regex.Matcher; 16 | import java.util.regex.Pattern; 17 | 18 | import butterknife.ButterKnife; 19 | import butterknife.OnClick; 20 | /** 21 | * Date: 2018/3/6 22 | * ************************************************************* 23 | * Auther: 陈占洋 24 | * ************************************************************* 25 | * Email: zhanyang.chen@gmail.com 26 | * ************************************************************* 27 | * Description: 主界面Activity 28 | */ 29 | public class MainActivity extends AppCompatActivity { 30 | 31 | @Override 32 | protected void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | setContentView(R.layout.activity_main); 35 | ButterKnife.bind(this); 36 | } 37 | 38 | @OnClick({R.id.btn_triangle,R.id.btn_cube, 39 | R.id.btn_earth,R.id.btn_pyramid, 40 | R.id.btn_camera_effect}) 41 | public void onBtnClick(View view){ 42 | switch (view.getId()){ 43 | //三角形 44 | case R.id.btn_triangle: 45 | startActivity(new Intent(this, TriangleActivity.class)); 46 | break; 47 | //立方体 48 | case R.id.btn_cube: 49 | startActivity(new Intent(this, CubeActivity.class)); 50 | break; 51 | //地球 52 | case R.id.btn_earth: 53 | startActivity(new Intent(this, EarthActivity.class)); 54 | break; 55 | //金字塔 56 | case R.id.btn_pyramid: 57 | Toast.makeText(this, "金字塔",Toast.LENGTH_SHORT).show(); 58 | break; 59 | //图片效果 60 | case R.id.btn_camera_effect: 61 | startActivity(new Intent(this,CameraActivity.class)); 62 | break; 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/CameraActivity.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera; 2 | 3 | import android.Manifest; 4 | import android.os.Bundle; 5 | import android.os.Environment; 6 | import android.support.v7.app.AppCompatActivity; 7 | import android.view.View; 8 | import android.view.WindowManager; 9 | import android.widget.SeekBar; 10 | import android.widget.Toast; 11 | 12 | import com.linuxpara.agles20tutorials.R; 13 | import com.linuxpara.agles20tutorials.camera.widget.CameraDrawer; 14 | import com.linuxpara.agles20tutorials.camera.widget.CameraView; 15 | import com.tbruyelle.rxpermissions2.RxPermissions; 16 | 17 | import java.io.File; 18 | 19 | import butterknife.BindView; 20 | import butterknife.ButterKnife; 21 | import butterknife.OnClick; 22 | 23 | public class CameraActivity extends AppCompatActivity { 24 | 25 | @BindView(R.id.camera_view) 26 | CameraView mCameraView; 27 | @BindView(R.id.camera_effect_warm_cool_sb) 28 | SeekBar mWarmCoolSB; 29 | private boolean mCapturingVideoStatus;//false停止录制状态,ture开始录制状态 30 | 31 | @Override 32 | protected void onCreate(Bundle savedInstanceState) { 33 | super.onCreate(savedInstanceState); 34 | 35 | RxPermissions rxPermissions = new RxPermissions(this); 36 | rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE) 37 | .subscribe(grant -> { 38 | if (grant) { 39 | init(); 40 | } else { 41 | finish(); 42 | } 43 | }); 44 | } 45 | 46 | private void init() { 47 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 48 | setContentView(R.layout.activity_camera); 49 | ButterKnife.bind(this); 50 | 51 | mWarmCoolSB.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { 52 | @Override 53 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 54 | float strength = (progress - 50) / 50.0f; 55 | mCameraView.setWarmCoolStrength(strength); 56 | } 57 | 58 | @Override 59 | public void onStartTrackingTouch(SeekBar seekBar) { 60 | 61 | } 62 | 63 | @Override 64 | public void onStopTrackingTouch(SeekBar seekBar) { 65 | 66 | } 67 | }); 68 | } 69 | 70 | @OnClick({R.id.camera_switch, R.id.camera_capture, R.id.camera_video_capture}) 71 | public void onBtnCtlClick(View view) { 72 | switch (view.getId()) { 73 | case R.id.camera_switch: 74 | mCameraView.switchCamera(); 75 | break; 76 | case R.id.camera_capture: 77 | 78 | break; 79 | case R.id.camera_video_capture: 80 | if (!mCapturingVideoStatus) { 81 | Toast.makeText(this, "开始录制视屏", Toast.LENGTH_SHORT).show(); 82 | File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 83 | String file = dir.getAbsolutePath() + File.separator + "gles20Tutorials" + File.separator + System.currentTimeMillis() + ".mp4"; 84 | mCameraView.startCaptureVideo(new File(file)); 85 | mCapturingVideoStatus = !mCapturingVideoStatus; 86 | } else { 87 | Toast.makeText(this, "结束录制视屏", Toast.LENGTH_SHORT).show(); 88 | mCameraView.stopCaptureVideo(); 89 | mCapturingVideoStatus = !mCapturingVideoStatus; 90 | } 91 | break; 92 | } 93 | } 94 | 95 | @OnClick({R.id.camera_effect_original, R.id.camera_effect_gray, 96 | R.id.camera_effect_negative, R.id.camera_effect_warm_cool, 97 | R.id.camera_effect_cameo, R.id.camera_effect_carving}) 98 | public void onBtnEffectClick(View view) { 99 | switch (view.getId()) { 100 | case R.id.camera_effect_original: 101 | mCameraView.setEffect(CameraDrawer.Effect.NONE); 102 | break; 103 | case R.id.camera_effect_gray: 104 | mCameraView.setEffect(CameraDrawer.Effect.GRAY); 105 | break; 106 | case R.id.camera_effect_negative: 107 | mCameraView.setEffect(CameraDrawer.Effect.NEGATIVE); 108 | break; 109 | case R.id.camera_effect_warm_cool: 110 | if (mWarmCoolSB.getVisibility() != View.VISIBLE) { 111 | mWarmCoolSB.setVisibility(View.VISIBLE); 112 | } 113 | mCameraView.setEffect(CameraDrawer.Effect.WARM_COOL); 114 | break; 115 | case R.id.camera_effect_cameo: 116 | mCameraView.setEffect(CameraDrawer.Effect.CAMEO); 117 | mCameraView.setKernelSize(5); 118 | break; 119 | case R.id.camera_effect_carving: 120 | mCameraView.setEffect(CameraDrawer.Effect.CARVING); 121 | mCameraView.setKernelSize(5); 122 | break; 123 | } 124 | if (view.getId() != R.id.camera_effect_warm_cool) { 125 | mWarmCoolSB.setVisibility(View.GONE); 126 | } 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/CameraBridge.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget; 2 | 3 | import android.graphics.SurfaceTexture; 4 | import android.opengl.GLSurfaceView; 5 | import android.os.Build; 6 | import android.util.Log; 7 | import android.widget.Toast; 8 | 9 | import com.linuxpara.agles20tutorials.camera.widget.camera.CameraV2; 10 | import com.linuxpara.agles20tutorials.camera.widget.camera.ICamera; 11 | import com.linuxpara.agles20tutorials.camera.widget.camera.Size; 12 | 13 | /** 14 | * Date: 2018/3/16 15 | * ************************************************************* 16 | * Auther: 陈占洋 17 | * ************************************************************* 18 | * Email: zhanyang.chen@gmail.com 19 | * ************************************************************* 20 | * Description: CameraV2、CameraV1(暂时没有)的代理,根据系统api版本自动调用对应的API 21 | */ 22 | 23 | public class CameraBridge implements ICamera { 24 | private static final String TAG = "CameraBridge"; 25 | private ICamera mCamera; 26 | 27 | public CameraBridge(GLSurfaceView glView) { 28 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 29 | mCamera = new CameraV2(glView); 30 | } else { 31 | Toast.makeText(glView.getContext(), "暂时不支持5.0以下的系统!", Toast.LENGTH_SHORT).show(); 32 | Log.i(TAG, "CameraBridge: 暂时不支持5.0以下的系统!"); 33 | } 34 | } 35 | 36 | 37 | @Override 38 | public void openCamera(int cameraId) { 39 | mCamera.openCamera(cameraId); 40 | } 41 | 42 | @Override 43 | public void setDisplaySize(Size displaySize) { 44 | mCamera.setDisplaySize(displaySize); 45 | } 46 | 47 | @Override 48 | public void startPreview() { 49 | mCamera.startPreview(); 50 | } 51 | 52 | @Override 53 | public Size getPreviewSize() { 54 | return mCamera.getPreviewSize(); 55 | } 56 | 57 | @Override 58 | public SurfaceTexture getSurfaceTexture() { 59 | return mCamera.getSurfaceTexture(); 60 | } 61 | 62 | @Override 63 | public void closeCamera() { 64 | mCamera.closeCamera(); 65 | } 66 | 67 | @Override 68 | public boolean isClosed() { 69 | return mCamera.isClosed(); 70 | } 71 | 72 | @Override 73 | public int getOesTextureId() { 74 | return mCamera.getOesTextureId(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/CameraDrawer.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget; 2 | 3 | import android.graphics.RectF; 4 | import android.graphics.SurfaceTexture; 5 | import android.opengl.EGL14; 6 | import android.opengl.GLES11Ext; 7 | import android.opengl.GLES20; 8 | import android.opengl.GLSurfaceView; 9 | import android.opengl.Matrix; 10 | import android.support.annotation.NonNull; 11 | 12 | import com.linuxpara.agles20tutorials.GraphicalRender; 13 | import com.linuxpara.agles20tutorials.camera.widget.camera.ICamera; 14 | import com.linuxpara.agles20tutorials.camera.widget.camera.Size; 15 | import com.linuxpara.agles20tutorials.camera.widget.video.VideoEncoder; 16 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 17 | 18 | import java.io.File; 19 | import java.io.IOException; 20 | import java.nio.FloatBuffer; 21 | import java.util.regex.Matcher; 22 | import java.util.regex.Pattern; 23 | 24 | /** 25 | * Date: 2018/3/16 26 | * ************************************************************* 27 | * Auther: 陈占洋 28 | * ************************************************************* 29 | * Email: zhanyang.chen@gmail.com 30 | * ************************************************************* 31 | * Description: 获取Camera数据,并绘制。根据展示窗口大小自动裁剪camera图片数据。 32 | */ 33 | 34 | public class CameraDrawer extends GraphicalRender { 35 | 36 | private static final String TAG = "CameraDrawer"; 37 | private CaptureVideoStatus mCaptureVideoStatus = CaptureVideoStatus.NONE; 38 | private VideoEncoder mVideoEncoder; 39 | private File mCaptureVideoOutFile; 40 | 41 | public enum CaptureVideoStatus { 42 | NONE, START_CAPTURE, CAPTURING, STOP_CAPTURE 43 | } 44 | 45 | public enum Effect { 46 | //默认(原始)、灰度、 底片、 冷暖色、 浮雕 雕刻 47 | NONE(0), GRAY(1), NEGATIVE(2), WARM_COOL(3), CAMEO(4), CARVING(5); 48 | 49 | private int mValue; 50 | 51 | Effect(int value) { 52 | mValue = value; 53 | } 54 | 55 | public int getValue() { 56 | return mValue; 57 | } 58 | } 59 | 60 | private static final int CAMERA_SHADER_TAG = 0; 61 | 62 | private static final float[] sCoordMatrix = new float[16]; 63 | 64 | private int mCameraId = ICamera.INVALID_CAMERA_ID; 65 | private CameraBridge mCameraBridge; 66 | private int mCameraShaderProgram; 67 | 68 | private int a_position; 69 | private int a_texCoord; 70 | private int u_mMatrix; 71 | private int u_vMatrix; 72 | private int u_projMatrix; 73 | private int u_coordMatrix; 74 | private int u_effect; 75 | private int u_warmCoolStrength; 76 | private int u_kernelSize; 77 | private int u_imgWH; 78 | 79 | private int mVertSize; 80 | private FloatBuffer mVertBuf; 81 | private FloatBuffer mTexCoordBuf; 82 | 83 | private float w; 84 | private float h; 85 | private Size mPreviewSize; 86 | private Size mViewSize; 87 | 88 | private Effect mEffect = Effect.NONE; 89 | //冷暖色强度 90 | private float mWarmCoolStrength; 91 | private int mWidth; 92 | private int mHeight; 93 | private int mKernelSize = 3;//默认卷积核的大小为3 94 | 95 | public CameraDrawer(GLSurfaceView view) { 96 | super(view); 97 | } 98 | 99 | public CameraDrawer(GLSurfaceView view, int cameraId) { 100 | super(view); 101 | mCameraId = cameraId; 102 | } 103 | 104 | 105 | @Override 106 | public void onCreate() { 107 | GLES20.glClearColor(0, 0, 0, 0); 108 | mCameraBridge = new CameraBridge(getView()); 109 | mCameraBridge.openCamera(mCameraId); 110 | 111 | } 112 | 113 | @Override 114 | public void onChange(int width, int height) { 115 | mWidth = width; 116 | mHeight = height; 117 | GLES20.glViewport(0, 0, width, height); 118 | 119 | mCameraBridge.setDisplaySize(new Size(width, height)); 120 | mCameraBridge.startPreview(); 121 | 122 | mPreviewSize = mCameraBridge.getPreviewSize(); 123 | mViewSize = new Size(width, height); 124 | 125 | float v_r = (float) width / height; 126 | Matrix.setIdentityM(sMMatrix, 0); 127 | Matrix.setLookAtM(sVMatrix, 0, 128 | 0, 0, 3, 129 | 0, 0, 0, 130 | 0, 1, 0); 131 | Matrix.orthoM(sProjMatrix, 0, 132 | -v_r, v_r, -1, 1,//这样设置,(0,0)点为屏幕中心点 133 | 2, 4); 134 | w = 2 * v_r; 135 | h = 2 * 1; 136 | initVert(); 137 | initTextureCoord(); 138 | initShaderFromAsset(CAMERA_SHADER_TAG, "camera/camera.vert", "camera/camera.frag"); 139 | //视频编码 140 | mVideoEncoder = new VideoEncoder("video_encoder"); 141 | } 142 | 143 | @Override 144 | public void onDraw() { 145 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); 146 | 147 | if (mCaptureVideoStatus == CaptureVideoStatus.START_CAPTURE) { 148 | VideoEncoder.EncoderConfig encoderConfig = new VideoEncoder.EncoderConfig(mWidth, mHeight, 1000000, EGL14.eglGetCurrentContext()); 149 | mVideoEncoder.setEncoderConfig(encoderConfig); 150 | mVideoEncoder.setCameraDrawer(this); 151 | mVideoEncoder.startCaptureVideo(mCaptureVideoOutFile); 152 | mCaptureVideoStatus = CaptureVideoStatus.CAPTURING; 153 | } 154 | 155 | SurfaceTexture surfaceTexture = mCameraBridge.getSurfaceTexture(); 156 | surfaceTexture.updateTexImage(); 157 | surfaceTexture.getTransformMatrix(sCoordMatrix); 158 | 159 | drawPreview(); 160 | 161 | if (mCaptureVideoStatus == CaptureVideoStatus.CAPTURING) { 162 | mVideoEncoder.CaptureFrame(surfaceTexture.getTimestamp()); 163 | } 164 | if (mCaptureVideoStatus == CaptureVideoStatus.STOP_CAPTURE) { 165 | mVideoEncoder.CaptureEOSFrame(surfaceTexture.getTimestamp()); 166 | mCaptureVideoStatus = CaptureVideoStatus.NONE; 167 | } 168 | } 169 | 170 | /** 171 | * 绘制摄像头预览界面 172 | */ 173 | public void drawPreview() { 174 | 175 | GLES20.glUseProgram(mCameraShaderProgram); 176 | 177 | GLES20.glVertexAttribPointer(a_position, 3, GLES20.GL_FLOAT, false, 0, mVertBuf); 178 | GLES20.glVertexAttribPointer(a_texCoord, 2, GLES20.GL_FLOAT, false, 0, mTexCoordBuf); 179 | 180 | GLES20.glUniformMatrix4fv(u_mMatrix, 1, false, sMMatrix, 0); 181 | GLES20.glUniformMatrix4fv(u_vMatrix, 1, false, sVMatrix, 0); 182 | GLES20.glUniformMatrix4fv(u_projMatrix, 1, false, sProjMatrix, 0); 183 | 184 | GLES20.glUniformMatrix4fv(u_coordMatrix, 1, false, sCoordMatrix, 0); 185 | 186 | GLES20.glUniform1i(u_effect, mEffect.getValue()); 187 | GLES20.glUniform1f(u_warmCoolStrength, mWarmCoolStrength); 188 | GLES20.glUniform1i(u_kernelSize, mKernelSize); 189 | GLES20.glUniform2iv(u_imgWH, 1, new int[]{mWidth, mHeight}, 0); 190 | 191 | GLES20.glActiveTexture(GLES20.GL_TEXTURE0); 192 | GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, mCameraBridge.getOesTextureId()); 193 | 194 | GLES20.glEnableVertexAttribArray(a_position);//设置效果 195 | GLES20.glEnableVertexAttribArray(a_texCoord);//设置冷暖色调强度 196 | 197 | GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, mVertSize); 198 | 199 | GLES20.glDisableVertexAttribArray(a_position); 200 | GLES20.glDisableVertexAttribArray(a_texCoord); 201 | } 202 | 203 | public void destory() { 204 | if (mCaptureVideoStatus == CaptureVideoStatus.CAPTURING) { 205 | mCaptureVideoStatus = CaptureVideoStatus.STOP_CAPTURE; 206 | } 207 | mVideoEncoder.quitSafely(); 208 | } 209 | 210 | @Override 211 | protected void findShaderAttr(int shaderTag, int shaderProgram) { 212 | if (shaderTag == CAMERA_SHADER_TAG) { 213 | mCameraShaderProgram = shaderProgram; 214 | a_position = GLES20.glGetAttribLocation(mCameraShaderProgram, "a_position"); 215 | a_texCoord = GLES20.glGetAttribLocation(mCameraShaderProgram, "a_texCoord"); 216 | 217 | u_mMatrix = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_MMatrix"); 218 | u_vMatrix = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_VMatrix"); 219 | u_projMatrix = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_ProjMatrix"); 220 | 221 | u_coordMatrix = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_coordMatrix"); 222 | 223 | u_effect = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_effect"); 224 | u_warmCoolStrength = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_warmCoolStrength"); 225 | u_kernelSize = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_kernelSize"); 226 | u_imgWH = GLES20.glGetUniformLocation(mCameraShaderProgram, "u_imgWH"); 227 | } 228 | } 229 | 230 | @Override 231 | protected void initVert() { 232 | float[] verts = { 233 | -w / 2, h / 2, 0,//左上 234 | w / 2, h / 2, 0,//右上 235 | -w / 2, -h / 2, 0,//左下 236 | w / 2, -h / 2, 0//右下 237 | }; 238 | mVertSize = verts.length / 3; 239 | mVertBuf = ShaderUtils.getFloatBuffer(verts); 240 | } 241 | 242 | @Override 243 | protected void initTextureCoord() { 244 | RectF rectF = new RectF(); 245 | float w_r = (float) mPreviewSize.getWidth() / mViewSize.getWidth(); 246 | float h_r = (float) mPreviewSize.getHeight() / mViewSize.getHeight(); 247 | if (w_r < h_r) { 248 | //以宽为纹理单位长度 249 | //先把预览图片缩放为展示图片的宽度,计算出缩放后的高度 250 | float h = mPreviewSize.getHeight() / w_r; 251 | //纹理的起始点在左下角(top、bottom是反着的),计算顶点对应纹理的坐标 252 | float end = (h - mViewSize.getHeight()) / 2 / h; 253 | float start = end + mViewSize.getHeight() / h; 254 | //截取纹理区域 255 | rectF.left = 0; 256 | rectF.top = start; 257 | rectF.right = 1; 258 | rectF.bottom = end; 259 | } else { 260 | //以高为纹理单位长度 261 | //先把预览图片缩放为展示图片的高度,计算出缩放后的宽度 262 | float w = mPreviewSize.getWidth() / h_r; 263 | //计算顶点对应纹理的坐标 264 | float start = (w - mViewSize.getWidth()) / 2 / w; 265 | float end = start + mViewSize.getWidth() / w; 266 | rectF.left = start; 267 | rectF.top = 1; 268 | rectF.right = end; 269 | rectF.bottom = 0; 270 | } 271 | float[] coords = { 272 | rectF.left, rectF.top, 273 | rectF.right, rectF.top, 274 | rectF.left, rectF.bottom, 275 | rectF.right, rectF.bottom 276 | }; 277 | mTexCoordBuf = ShaderUtils.getFloatBuffer(coords); 278 | } 279 | 280 | public void switchCamera() { 281 | mCameraId = mCameraId == ICamera.FRONT_CAMERA_ID ? ICamera.BACK_CAMERA_ID : ICamera.FRONT_CAMERA_ID; 282 | mCameraBridge.closeCamera(); 283 | getView().onPause(); 284 | getView().onResume(); 285 | } 286 | 287 | public void setEffect(Effect effect) { 288 | mEffect = effect; 289 | } 290 | 291 | /** 292 | * 设置冷暖色强度 293 | * 294 | * @param strength 冷色负数,暖色正数。范围-1至+1. 295 | */ 296 | public void setWarmCoolStrength(float strength) { 297 | mWarmCoolStrength = strength > 1 ? 1 : strength; 298 | mWarmCoolStrength = strength < -1 ? -1 : strength; 299 | } 300 | 301 | /** 302 | * 设置卷积核大小 303 | * 304 | * @param kernelSize 305 | */ 306 | public void setKernelSize(int kernelSize) { 307 | this.mKernelSize = kernelSize; 308 | } 309 | 310 | /** 311 | * 开始录制视频,如果文件已经存在会在文件名后增加(num) 312 | */ 313 | public void startCaptureVideo(File file) { 314 | // File final_file; 315 | // if (!file.exists()) { 316 | // file.getParentFile().mkdirs();//创建父目录 317 | // try { 318 | // file.createNewFile(); 319 | // } catch (IOException e) { 320 | // e.printStackTrace(); 321 | // } 322 | // final_file = file; 323 | // } else { 324 | // String fileName = file.getName(); 325 | // Pattern pattern = Pattern.compile("\\(\\d+\\)"); 326 | // Matcher m = pattern.matcher(fileName); 327 | // if (m.matches()) { 328 | // int num = 0; 329 | // while (m.find()) { 330 | // String content = m.group(0); 331 | // num = Integer.parseInt(content.substring(1, content.length() - 1)); 332 | // } 333 | // String new_file_name = fileName.replace(num + "", ++num + ""); 334 | // final_file = new File(file.getParentFile(), new_file_name); 335 | // } else { 336 | // String filePath = file.getAbsolutePath(); 337 | // //后缀 338 | // String suffix = filePath.substring(filePath.indexOf("."), filePath.length() - 1); 339 | // String new_file_path = filePath.replace(suffix, "(1)" + suffix); 340 | // final_file = new File(new_file_path); 341 | // } 342 | // if (!final_file.exists()) { 343 | // try { 344 | // final_file.createNewFile(); 345 | // } catch (IOException e) { 346 | // e.printStackTrace(); 347 | // } 348 | // } 349 | // } 350 | file.getParentFile().mkdirs(); 351 | try { 352 | file.createNewFile(); 353 | } catch (IOException e) { 354 | e.printStackTrace(); 355 | } 356 | mCaptureVideoOutFile = file; 357 | mCaptureVideoStatus = CaptureVideoStatus.START_CAPTURE; 358 | } 359 | 360 | /** 361 | * 结束视频录制 362 | */ 363 | 364 | public void stopCaptureVideo() { 365 | mCaptureVideoStatus = CaptureVideoStatus.STOP_CAPTURE; 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/CameraView.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget; 2 | 3 | import android.content.Context; 4 | import android.content.res.TypedArray; 5 | import android.opengl.GLSurfaceView; 6 | import android.util.AttributeSet; 7 | import android.view.SurfaceHolder; 8 | 9 | import com.linuxpara.agles20tutorials.R; 10 | import com.linuxpara.agles20tutorials.camera.widget.camera.ICamera; 11 | 12 | import java.io.File; 13 | 14 | /** 15 | * Date: 2018/3/16 16 | * ************************************************************* 17 | * Auther: 陈占洋 18 | * ************************************************************* 19 | * Email: zhanyang.chen@gmail.com 20 | * ************************************************************* 21 | * Description: 照相机控件。 22 | */ 23 | public class CameraView extends GLSurfaceView { 24 | 25 | private static final String TAG = "CameraView"; 26 | 27 | private int mCameraId = ICamera.FRONT_CAMERA_ID; 28 | private CameraDrawer mCameraDrawer; 29 | 30 | public CameraView(Context context) { 31 | this(context, null); 32 | } 33 | 34 | public CameraView(Context context, AttributeSet attrs) { 35 | super(context, attrs); 36 | 37 | TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CameraView); 38 | mCameraId = ta.getInt(R.styleable.CameraView_camera_id, ICamera.FRONT_CAMERA_ID); 39 | ta.recycle(); 40 | 41 | setEGLContextClientVersion(2); 42 | mCameraDrawer = new CameraDrawer(this, mCameraId); 43 | setRenderer(mCameraDrawer); 44 | setRenderMode(RENDERMODE_WHEN_DIRTY); 45 | 46 | } 47 | 48 | @Override 49 | public void surfaceDestroyed(SurfaceHolder holder) { 50 | super.surfaceDestroyed(holder); 51 | mCameraDrawer.destory(); 52 | } 53 | 54 | public void switchCamera() { 55 | mCameraDrawer.switchCamera(); 56 | } 57 | 58 | public void setEffect(CameraDrawer.Effect effect) { 59 | mCameraDrawer.setEffect(effect); 60 | } 61 | 62 | /** 63 | * 设置冷暖色强度 64 | * 65 | * @param strength 冷色负数,暖色正数。范围-1至+1. 66 | */ 67 | public void setWarmCoolStrength(float strength) { 68 | mCameraDrawer.setWarmCoolStrength(strength); 69 | } 70 | 71 | /** 72 | * 卷积核大小,卷积核的大小一般为奇数3,5,7,9,...... 73 | * 74 | * @param kernelSize 75 | */ 76 | public void setKernelSize(int kernelSize) { 77 | mCameraDrawer.setKernelSize(kernelSize); 78 | } 79 | 80 | /** 81 | * 开始捕获视屏 82 | * 83 | * @param file 84 | */ 85 | public void startCaptureVideo(File file) { 86 | mCameraDrawer.startCaptureVideo(file); 87 | } 88 | 89 | /** 90 | * 结束视频录制 91 | */ 92 | public void stopCaptureVideo() { 93 | mCameraDrawer.stopCaptureVideo(); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/camera/CameraV2.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget.camera; 2 | 3 | import android.Manifest; 4 | import android.annotation.TargetApi; 5 | import android.content.Context; 6 | import android.content.pm.PackageManager; 7 | import android.graphics.SurfaceTexture; 8 | import android.hardware.camera2.CameraAccessException; 9 | import android.hardware.camera2.CameraCaptureSession; 10 | import android.hardware.camera2.CameraCharacteristics; 11 | import android.hardware.camera2.CameraDevice; 12 | import android.hardware.camera2.CameraManager; 13 | import android.hardware.camera2.CaptureRequest; 14 | import android.hardware.camera2.params.StreamConfigurationMap; 15 | import android.opengl.GLSurfaceView; 16 | import android.os.Build; 17 | import android.os.Handler; 18 | import android.os.HandlerThread; 19 | import android.os.SystemClock; 20 | import android.support.annotation.NonNull; 21 | import android.support.v4.app.ActivityCompat; 22 | import android.util.Log; 23 | import android.view.Surface; 24 | import android.widget.Toast; 25 | 26 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 27 | 28 | import java.lang.ref.WeakReference; 29 | import java.util.ArrayList; 30 | import java.util.Arrays; 31 | import java.util.List; 32 | 33 | /** 34 | * Date: 2018/3/16 35 | * ************************************************************* 36 | * Auther: 陈占洋 37 | * ************************************************************* 38 | * Email: zhanyang.chen@gmail.com 39 | * ************************************************************* 40 | * Description: 封装5.0后摄像头API 41 | */ 42 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 43 | public class CameraV2 implements ICamera { 44 | private static final String TAG = "CameraV2"; 45 | 46 | private WeakReference mWeakGLViewRef; 47 | 48 | private CameraManager mCameraManager; 49 | private HandlerThread mCameraThead; 50 | private Handler mCameraHandler; 51 | 52 | private CameraDevice mCameraDevice; 53 | private SurfaceTexture mSurfaceTexture; 54 | 55 | private CameraCaptureSession mCaptureSession; 56 | private CaptureRequest mCaptureRequest; 57 | private boolean mIsOpened = false; 58 | private List mSupportSizes; 59 | private Size mOptimalSize; 60 | private int mOesTextureId; 61 | 62 | 63 | public CameraV2(GLSurfaceView glView) { 64 | mWeakGLViewRef = new WeakReference<>(glView); 65 | cameraPrepare(); 66 | } 67 | 68 | /** 69 | * 获取上下文 70 | * 71 | * @return 72 | */ 73 | public Context getContext() { 74 | return getGLView().getContext(); 75 | } 76 | 77 | /** 78 | * 获取GLSurfaceView 79 | * 80 | * @return 81 | */ 82 | private GLSurfaceView getGLView() { 83 | if (mWeakGLViewRef != null && mWeakGLViewRef.get() != null) { 84 | return mWeakGLViewRef.get(); 85 | } 86 | throw new RuntimeException("CameraV2: GLView被释放!"); 87 | } 88 | 89 | /** 90 | * 摄像头准备工作 91 | */ 92 | private void cameraPrepare() { 93 | mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE); 94 | mCameraThead = new HandlerThread("camera_thread"); 95 | mCameraThead.start(); 96 | mCameraHandler = new Handler(mCameraThead.getLooper()); 97 | 98 | mOesTextureId = ShaderUtils.genOESTextureId(); 99 | mSurfaceTexture = new SurfaceTexture(mOesTextureId); 100 | mSurfaceTexture.setOnFrameAvailableListener(new SurfaceTexture.OnFrameAvailableListener() { 101 | @Override 102 | public void onFrameAvailable(SurfaceTexture surfaceTexture) { 103 | getGLView().requestRender(); 104 | } 105 | }); 106 | } 107 | 108 | /** 109 | * 开启摄像头 110 | */ 111 | @Override 112 | public void openCamera(int cameraId) { 113 | if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { 114 | Toast.makeText(getContext(), "摄像头权限未开启!", Toast.LENGTH_SHORT).show(); 115 | return; 116 | } 117 | if (cameraId == INVALID_CAMERA_ID) { 118 | Log.i(TAG, "openCamera: 摄像头ID无效"); 119 | return; 120 | } 121 | if (!isClosed()) { 122 | closeCamera(); 123 | } 124 | mSupportSizes = getSupportSize(cameraId); 125 | try { 126 | //开启摄像头 127 | mCameraManager.openCamera(cameraId + "", new CameraDevice.StateCallback() { 128 | @Override 129 | public void onOpened(@NonNull CameraDevice camera) { 130 | mCameraDevice = camera; 131 | // openCaptureSession(); 132 | mIsOpened = true; 133 | } 134 | 135 | @Override 136 | public void onDisconnected(@NonNull CameraDevice camera) { 137 | camera.close(); 138 | } 139 | 140 | @Override 141 | public void onError(@NonNull CameraDevice camera, int error) { 142 | Log.i(TAG, "onError: 开启摄像头发生错误,错误码:" + error); 143 | camera.close(); 144 | } 145 | }, mCameraHandler); 146 | } catch (CameraAccessException e) { 147 | e.printStackTrace(); 148 | } 149 | } 150 | 151 | @Override 152 | public void setDisplaySize(Size displaySize) { 153 | mOptimalSize = getOptimalSize(displaySize); 154 | mSurfaceTexture.setDefaultBufferSize(mOptimalSize.getWidth(), mOptimalSize.getHeight()); 155 | } 156 | 157 | /** 158 | * 获取最优尺寸 159 | * 160 | * @param displaySize 161 | * @return 162 | */ 163 | private Size getOptimalSize(Size displaySize) { 164 | if (mSupportSizes == null || mSupportSizes.size() == 0) { 165 | throw new RuntimeException("未开启摄像头,请先调用openCamera()方法开启摄像头"); 166 | } 167 | List optimalSizes = new ArrayList<>(); 168 | float d_r; 169 | if (displaySize.getHeight() > displaySize.getWidth()) { 170 | d_r = (float) displaySize.getHeight() / displaySize.getWidth(); 171 | } else { 172 | d_r = (float) displaySize.getWidth() / displaySize.getHeight(); 173 | } 174 | for (int i = 0; i < mSupportSizes.size(); i++) { 175 | Size supportSize = mSupportSizes.get(i); 176 | float s_r = (float) supportSize.getWidth() / supportSize.getHeight(); 177 | if (Math.abs(d_r - s_r) <= 0.05 && 178 | supportSize.getWidth() * supportSize.getHeight() >= NORMAL_SIZE.getWidth() * NORMAL_SIZE.getHeight()) { 179 | optimalSizes.add(supportSize); 180 | } 181 | } 182 | if (optimalSizes.size() > 0) { 183 | return optimalSizes.get(0); 184 | } 185 | return NORMAL_SIZE; 186 | } 187 | 188 | 189 | private List getSupportSize(int cameraId) { 190 | try { 191 | CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(cameraId + ""); 192 | StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); 193 | android.util.Size[] outputSizes = map.getOutputSizes(mSurfaceTexture.getClass()); 194 | ArrayList supportSizes = new ArrayList<>(); 195 | for (int i = 0; i < outputSizes.length; i++) { 196 | android.util.Size outputSize = outputSizes[i]; 197 | Size size = new Size(outputSize.getWidth(), outputSize.getHeight()); 198 | supportSizes.add(size); 199 | } 200 | printList(supportSizes); 201 | return supportSizes; 202 | } catch (CameraAccessException e) { 203 | e.printStackTrace(); 204 | } 205 | 206 | return null; 207 | } 208 | 209 | private void printList(List sizes) { 210 | for (int i = 0; i < sizes.size(); i++) { 211 | Log.i(TAG, "printList: " + sizes.get(i).toString()); 212 | } 213 | } 214 | 215 | /** 216 | * 开启摄像头捕捉画面会话 217 | */ 218 | private void openCaptureSession() { 219 | try { 220 | Surface surface = new Surface(mSurfaceTexture); 221 | CaptureRequest.Builder captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); 222 | captureRequestBuilder.addTarget(surface); 223 | mCaptureRequest = captureRequestBuilder.build(); 224 | 225 | mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() { 226 | @Override 227 | public void onConfigured(@NonNull CameraCaptureSession session) { 228 | mCaptureSession = session; 229 | try { 230 | mCaptureSession.setRepeatingRequest(mCaptureRequest, null, mCameraHandler); 231 | } catch (CameraAccessException e) { 232 | e.printStackTrace(); 233 | } 234 | } 235 | 236 | @Override 237 | public void onConfigureFailed(@NonNull CameraCaptureSession session) { 238 | Log.i(TAG, "onConfigureFailed: captureSession 配置失败!"); 239 | session.getDevice().close(); 240 | } 241 | }, mCameraHandler); 242 | } catch (CameraAccessException e) { 243 | e.printStackTrace(); 244 | } 245 | } 246 | 247 | /** 248 | * 开始预览 249 | */ 250 | @Override 251 | public void startPreview() { 252 | //调用的时候有可能摄像头还没开启完成,需要等待开启完成。 253 | while (!mIsOpened) { 254 | SystemClock.sleep(100); 255 | } 256 | openCaptureSession(); 257 | } 258 | 259 | /** 260 | * 关闭摄像头 261 | */ 262 | @Override 263 | public void closeCamera() { 264 | if (mCameraDevice != null) { 265 | mCameraDevice.close(); 266 | mCameraDevice = null; 267 | mIsOpened = false; 268 | mCameraThead.quitSafely(); 269 | mCameraHandler = null; 270 | } 271 | } 272 | 273 | /** 274 | * 判断摄像头是否关闭 275 | * 276 | * @return 277 | */ 278 | @Override 279 | public boolean isClosed() { 280 | return mCameraDevice == null; 281 | } 282 | 283 | @Override 284 | public int getOesTextureId() { 285 | return mOesTextureId; 286 | } 287 | 288 | @Override 289 | public Size getPreviewSize() { 290 | if (mOptimalSize == null) { 291 | throw new RuntimeException("请先调用setDisplaySize()"); 292 | } 293 | return new Size(mOptimalSize.getHeight(), mOptimalSize.getWidth()); 294 | } 295 | 296 | @Override 297 | public SurfaceTexture getSurfaceTexture() { 298 | return mSurfaceTexture; 299 | } 300 | 301 | 302 | } 303 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/camera/ICamera.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget.camera; 2 | 3 | import android.graphics.SurfaceTexture; 4 | 5 | /** 6 | * Date: 2018/3/16 7 | * ************************************************************* 8 | * Auther: 陈占洋 9 | * ************************************************************* 10 | * Email: zhanyang.chen@gmail.com 11 | * ************************************************************* 12 | * Description: 自定义摄像头接口,用于适配5.0前后的API 13 | */ 14 | 15 | public interface ICamera { 16 | 17 | int INVALID_CAMERA_ID = -1; 18 | int BACK_CAMERA_ID = 0; 19 | int FRONT_CAMERA_ID = 1; 20 | 21 | Size NORMAL_SIZE = new Size(1280, 720); 22 | 23 | /** 24 | * 打开摄像头 25 | * 26 | * @param cameraId 27 | */ 28 | void openCamera(int cameraId); 29 | 30 | /** 31 | * 设置显示的大小 32 | * 33 | * @param displaySize 34 | */ 35 | void setDisplaySize(Size displaySize); 36 | 37 | /** 38 | * 摄像头开始预览 39 | */ 40 | void startPreview(); 41 | 42 | /** 43 | * 获取预览图片大小 44 | * 45 | * @return 46 | */ 47 | Size getPreviewSize(); 48 | 49 | /** 50 | * 获取SurfaceTexture 51 | */ 52 | SurfaceTexture getSurfaceTexture(); 53 | 54 | /** 55 | * 关闭摄像头 56 | */ 57 | void closeCamera(); 58 | 59 | /** 60 | * 判断摄像头是否关闭 61 | * 62 | * @return 63 | */ 64 | boolean isClosed(); 65 | 66 | /** 67 | * 获取外部纹理Id 68 | * 69 | * @return 70 | */ 71 | int getOesTextureId(); 72 | 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/camera/Size.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget.camera; 2 | 3 | /** 4 | * Date: 2018/3/16 5 | * ************************************************************* 6 | * Auther: 陈占洋 7 | * ************************************************************* 8 | * Email: zhanyang.chen@gmail.com 9 | * ************************************************************* 10 | * Description: 11 | */ 12 | 13 | public class Size { 14 | 15 | private int mHeight; 16 | private int mWidth; 17 | 18 | public Size(int width, int height) { 19 | mWidth = width; 20 | mHeight = height; 21 | } 22 | 23 | public void setWidth(int width) { 24 | this.mWidth = width; 25 | } 26 | 27 | public int getWidth() { 28 | return mWidth; 29 | } 30 | 31 | public void setHeight(int height) { 32 | this.mHeight = height; 33 | } 34 | 35 | public int getHeight() { 36 | return mHeight; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return "width × height = " + mWidth + " × " + mHeight; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/camera/widget/video/VideoEncoder.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.camera.widget.video; 2 | 3 | import android.media.MediaCodec; 4 | import android.media.MediaCodecInfo; 5 | import android.media.MediaFormat; 6 | import android.media.MediaMuxer; 7 | import android.opengl.EGL14; 8 | import android.opengl.EGLConfig; 9 | import android.opengl.EGLContext; 10 | import android.opengl.EGLDisplay; 11 | import android.opengl.EGLExt; 12 | import android.opengl.EGLSurface; 13 | import android.os.Handler; 14 | import android.os.HandlerThread; 15 | import android.os.Message; 16 | import android.util.Log; 17 | import android.view.Surface; 18 | 19 | import com.linuxpara.agles20tutorials.camera.widget.CameraDrawer; 20 | 21 | import java.io.File; 22 | import java.io.IOException; 23 | import java.lang.ref.WeakReference; 24 | import java.nio.ByteBuffer; 25 | 26 | 27 | /** 28 | * Date: 2018/3/22 29 | * ************************************************************* 30 | * Auther: 陈占洋 31 | * ************************************************************* 32 | * Email: zhanyang.chen@gmail.com 33 | * ************************************************************* 34 | * Description: 视频编码 35 | */ 36 | 37 | public class VideoEncoder extends HandlerThread { 38 | 39 | private static final String TAG = "VideoEncoder"; 40 | 41 | private static final String H264 = MediaFormat.MIMETYPE_VIDEO_AVC; 42 | private static final int MSG_ENCODE_START = 0; 43 | private static final int MSG_ENCODE_FRAME = 1; 44 | private static final int MSG_ENCODE_EOS_FRAME = 2; 45 | private static final int MSG_ENCODE_RELEASE = 3; 46 | 47 | private static int FRAME_RATE = 30;//30fps 48 | private static int FRAME_INTERVAL = 5; 49 | 50 | private MediaCodec mEncoder; 51 | private MediaMuxer mMuxer; 52 | private Handler mHandler; 53 | private int mTrackIdx = -1; 54 | private boolean mMuxerStarted; 55 | private EncoderConfig mEncoderConfig; 56 | private EGLDisplay mEGLDisplay; 57 | private EGLSurface mEGLSurface; 58 | private WeakReference mWeakRefCameraDrawer; 59 | 60 | 61 | public VideoEncoder(String name) { 62 | super(name); 63 | start(); 64 | mHandler = new Handler(getLooper()) { 65 | @Override 66 | public void handleMessage(Message msg) { 67 | handleAction(msg); 68 | } 69 | }; 70 | } 71 | 72 | public VideoEncoder(String name, int priority) { 73 | super(name, priority); 74 | start(); 75 | mHandler = new Handler(getLooper()) { 76 | @Override 77 | public void handleMessage(Message msg) { 78 | handleAction(msg); 79 | } 80 | }; 81 | } 82 | 83 | private void handleAction(Message msg) { 84 | switch (msg.what) { 85 | case MSG_ENCODE_START: 86 | EncoderConfig encoderConfig = (EncoderConfig) msg.obj; 87 | mEncoder = createEncoder(encoderConfig); 88 | try { 89 | mMuxer = new MediaMuxer(encoderConfig.getOutFile().getAbsolutePath(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); 90 | } catch (IOException e) { 91 | e.printStackTrace(); 92 | } 93 | Surface inputSurface = mEncoder.createInputSurface(); 94 | createEGLEnvironment(inputSurface, encoderConfig); 95 | mEncoder.start(); 96 | break; 97 | case MSG_ENCODE_FRAME: 98 | //在此EGL环境中绘制预览 99 | if (mWeakRefCameraDrawer != null && mWeakRefCameraDrawer.get() != null){ 100 | mWeakRefCameraDrawer.get().drawPreview(); 101 | } 102 | //给当前帧添加时间戳 103 | long timestamp = (long) msg.obj; 104 | EGLExt.eglPresentationTimeANDROID(mEGLDisplay, mEGLSurface, timestamp); 105 | EGL14.eglSwapBuffers(mEGLDisplay, mEGLSurface); 106 | //编码帧数据 107 | encodeFrame(false); 108 | break; 109 | case MSG_ENCODE_EOS_FRAME: 110 | long timestamp_eos = (long) msg.obj; 111 | EGLExt.eglPresentationTimeANDROID(mEGLDisplay, mEGLSurface, timestamp_eos); 112 | EGL14.eglSwapBuffers(mEGLDisplay, mEGLSurface); 113 | //编码结束帧数据 114 | encodeEOSFrame(); 115 | break; 116 | case MSG_ENCODE_RELEASE: 117 | releaseEncoder(); 118 | break; 119 | } 120 | } 121 | 122 | /** 123 | * 设置编码配置 124 | * 125 | * @param encoderConfig 126 | */ 127 | public void setEncoderConfig(EncoderConfig encoderConfig) { 128 | mEncoderConfig = encoderConfig; 129 | } 130 | 131 | /** 132 | * 创建解码器 133 | * 134 | * @param encoderConfig 135 | * @return 136 | */ 137 | private MediaCodec createEncoder(EncoderConfig encoderConfig) { 138 | MediaFormat format = MediaFormat.createVideoFormat(H264, encoderConfig.getWidth(), encoderConfig.getHeight()); 139 | //设置颜色格式从surface中获取 140 | format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); 141 | //设置码率 142 | format.setInteger(MediaFormat.KEY_BIT_RATE, encoderConfig.getBitRate()); 143 | //设置帧率 144 | format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE); 145 | //设置I帧间隔 146 | format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, FRAME_INTERVAL); 147 | 148 | try { 149 | //根据MIME类型创建媒体编解码器 150 | MediaCodec encoder = MediaCodec.createEncoderByType(H264); 151 | //配置编解码器,从未初始化状态切换到初始化状态。 152 | //format 编码时为输出格式,解码时为输入格式 153 | //surface 如果不是raw输出、不是一个解码器,或者想配置为ByteBuffer时传入null 154 | encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); 155 | return encoder; 156 | } catch (IOException e) { 157 | e.printStackTrace(); 158 | } 159 | return null; 160 | } 161 | 162 | /** 163 | * 创建EGL环境 164 | * 165 | * @param surface 166 | * @param encoderConfig 167 | */ 168 | private void createEGLEnvironment(Surface surface, EncoderConfig encoderConfig) { 169 | //-------------------------eglDisplay-------------------------- 170 | mEGLDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); 171 | int[] version = new int[2]; 172 | if (!EGL14.eglInitialize(mEGLDisplay, version, 0, version, 1)) { 173 | throw new RuntimeException("eglInitialize 初始化EGLDisplay失败!"); 174 | } 175 | Log.i(TAG, "createEGLEnvironment: EGL Version = " + version[0] + "." + version[1]); 176 | //-------------------------eglConfig-------------------------- 177 | EGLConfig eglConfig; 178 | int[] config_attrib_list = { 179 | EGL14.EGL_RED_SIZE, 8, 180 | EGL14.EGL_GREEN_SIZE, 8, 181 | EGL14.EGL_BLUE_SIZE, 8, 182 | EGL14.EGL_ALPHA_SIZE, 8, 183 | EGL14.EGL_DEPTH_SIZE, 16, 184 | EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, 185 | EGL14.EGL_NONE 186 | }; 187 | EGLConfig[] configs = new EGLConfig[1]; 188 | int[] num_config = new int[1]; 189 | if (!EGL14.eglChooseConfig(mEGLDisplay, config_attrib_list, 0, 190 | configs, 0, configs.length, 191 | num_config, 0)) { 192 | throw new RuntimeException("eglChooseConfig 获取EGLConfig失败!"); 193 | } else { 194 | if (num_config[0] == 0) { 195 | throw new RuntimeException("eglChooseConfig 获取EGLConfig失败,没有符合条件的EGLConfig"); 196 | } else { 197 | eglConfig = configs[0]; 198 | } 199 | } 200 | //-------------------------eglSurface-------------------------- 201 | int[] surface_attrib_list = { 202 | // EGL14.EGL_WIDTH, encoderConfig.getWidth(), 203 | // EGL14.EGL_HEIGHT, encoderConfig.getHeight(), 204 | EGL14.EGL_NONE 205 | }; 206 | mEGLSurface = EGL14.eglCreateWindowSurface(mEGLDisplay, eglConfig, 207 | surface, surface_attrib_list, 0); 208 | if (mEGLSurface == EGL14.EGL_NO_SURFACE) { 209 | throw new RuntimeException("eglCreateWindowSurface 创建EGLSurface失败!"); 210 | } 211 | //-------------------------eglContext-------------------------- 212 | int[] context_attrib_list = { 213 | EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, 214 | EGL14.EGL_NONE 215 | }; 216 | EGLContext eglContext = EGL14.eglCreateContext(mEGLDisplay, eglConfig, encoderConfig.getEGLContext(), 217 | context_attrib_list, 0); 218 | if (eglContext == EGL14.EGL_NO_CONTEXT) { 219 | throw new RuntimeException("eglCreateContext 创建EGLContext失败!"); 220 | } 221 | 222 | 223 | EGL14.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, eglContext); 224 | } 225 | 226 | /** 227 | * 编码一帧数据 228 | */ 229 | private void encodeFrame(boolean isEOS) { 230 | ByteBuffer[] outputBuffers = mEncoder.getOutputBuffers(); 231 | MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); 232 | while (true) { 233 | int status = mEncoder.dequeueOutputBuffer(bufferInfo, 10000); 234 | if (status == MediaCodec.INFO_TRY_AGAIN_LATER) { 235 | Log.i(TAG, "encodeFrame: try-again-later"); 236 | if (!isEOS) { 237 | break; 238 | } else { 239 | Log.i(TAG, "encodeFrame: 等待结束帧"); 240 | } 241 | } else if (status == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { 242 | Log.i(TAG, "encodeFrame: output-buffers-changed " + status); 243 | outputBuffers = mEncoder.getOutputBuffers(); 244 | } else if (status == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { 245 | Log.i(TAG, "encodeFrame: output-format-changed " + status); 246 | if (mMuxerStarted) { 247 | throw new RuntimeException("正在录制视频时,视频格式发生了改变!"); 248 | } 249 | MediaFormat encodeFormat = mEncoder.getOutputFormat(); 250 | mTrackIdx = mMuxer.addTrack(encodeFormat); 251 | mMuxer.start(); 252 | mMuxerStarted = true; 253 | } else if (status < 0) { 254 | Log.i(TAG, "encodeFrame: 未知状态!"); 255 | } else { 256 | //获取编码完成的数据 257 | ByteBuffer encodeData = outputBuffers[status]; 258 | if (encodeData == null) { 259 | throw new RuntimeException("编码器输出为空!"); 260 | } 261 | if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { 262 | Log.i(TAG, "encodeFrame: BUFFER_FLAG_CODEC_CONFIG 配置数据,忽略此Buffer " + status); 263 | bufferInfo.size = 0; 264 | } 265 | if (bufferInfo.size != 0) { 266 | if (!mMuxerStarted) { 267 | throw new RuntimeException("muxer 未开启!"); 268 | } 269 | encodeData.position(bufferInfo.offset); 270 | encodeData.limit(bufferInfo.offset + bufferInfo.size); 271 | //将编码完成的数据写入到文件中 272 | mMuxer.writeSampleData(mTrackIdx, encodeData, bufferInfo); 273 | Log.i(TAG, "encodeFrame: 写入数据 " + bufferInfo.size + " bytes to muxer, 时间戳 = " + bufferInfo.presentationTimeUs); 274 | } 275 | //释放buffer 276 | mEncoder.releaseOutputBuffer(status, false); 277 | 278 | if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { 279 | if (!isEOS) { 280 | Log.i(TAG, "encodeFrame: 非正常结束帧!"); 281 | } else { 282 | Log.i(TAG, "encodeFrame: 结束录制! " + status); 283 | } 284 | break; 285 | } 286 | } 287 | } 288 | } 289 | 290 | private void encodeEOSFrame() { 291 | Log.i(TAG, "encodeEOSFrame: sending EOS to encoder"); 292 | if (mEncoder != null) { 293 | mEncoder.signalEndOfInputStream(); 294 | encodeFrame(true); 295 | } 296 | mHandler.sendEmptyMessageDelayed(MSG_ENCODE_RELEASE,50); 297 | } 298 | 299 | /** 300 | * 释放编码器 301 | */ 302 | private void releaseEncoder() { 303 | if (mEncoder != null) { 304 | mEncoder.stop(); 305 | mEncoder.release(); 306 | mEncoder = null; 307 | } 308 | if (mMuxer != null) { 309 | mMuxer.stop(); 310 | mMuxer.release(); 311 | mMuxer = null; 312 | } 313 | } 314 | 315 | /** 316 | * 开始捕获视频 317 | * 318 | * @param outFile 319 | */ 320 | public void startCaptureVideo(File outFile) { 321 | mEncoderConfig.setOutFile(outFile); 322 | Message msg = Message.obtain(); 323 | msg.what = MSG_ENCODE_START; 324 | msg.obj = mEncoderConfig; 325 | mHandler.sendMessage(msg); 326 | } 327 | 328 | /** 329 | * 捕获一帧数据 330 | * 331 | * @param timestamp 332 | */ 333 | public void CaptureFrame(long timestamp) { 334 | Message msg = Message.obtain(); 335 | msg.what = MSG_ENCODE_FRAME; 336 | msg.obj = timestamp; 337 | mHandler.sendMessage(msg); 338 | } 339 | 340 | /** 341 | * 捕获结束帧数据 342 | * 343 | * @param timestamp 344 | */ 345 | public void CaptureEOSFrame(long timestamp) { 346 | Message msg = Message.obtain(); 347 | msg.what = MSG_ENCODE_EOS_FRAME; 348 | msg.obj = timestamp; 349 | mHandler.sendMessage(msg); 350 | } 351 | 352 | /** 353 | * 设置绘制效果的类 354 | * @param cameraDrawer 355 | */ 356 | public void setCameraDrawer(CameraDrawer cameraDrawer) { 357 | mWeakRefCameraDrawer = new WeakReference<>(cameraDrawer); 358 | } 359 | 360 | /** 361 | * 编码配置 362 | */ 363 | public static class EncoderConfig { 364 | 365 | private int mWidth; 366 | private int mHeight; 367 | private int mBitRate; 368 | private EGLContext mEGLContext; 369 | private File mOutFile; 370 | 371 | public EncoderConfig(int width, int height, int bitRate, EGLContext eglContext) { 372 | this.mWidth = width; 373 | this.mHeight = height; 374 | this.mBitRate = bitRate; 375 | this.mEGLContext = eglContext; 376 | } 377 | 378 | /** 379 | * 获取视频宽 380 | * 381 | * @return 382 | */ 383 | public int getWidth() { 384 | return mWidth; 385 | } 386 | 387 | /** 388 | * 获取视频高 389 | * 390 | * @return 391 | */ 392 | public int getHeight() { 393 | return mHeight; 394 | } 395 | 396 | /** 397 | * 获取编码率 398 | * 399 | * @return 400 | */ 401 | public int getBitRate() { 402 | return mBitRate; 403 | } 404 | 405 | /** 406 | * 获取EGL上下文 407 | * 408 | * @return 409 | */ 410 | public EGLContext getEGLContext() { 411 | return mEGLContext; 412 | } 413 | 414 | /** 415 | * 设置视频存储路径 416 | * 417 | * @param mOutFile 418 | */ 419 | public void setOutFile(File mOutFile) { 420 | this.mOutFile = mOutFile; 421 | } 422 | 423 | /** 424 | * 获取视频存储路劲 425 | * 426 | * @return 427 | */ 428 | public File getOutFile() { 429 | return mOutFile; 430 | } 431 | } 432 | 433 | } 434 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/cube/CubeActivity.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.cube; 2 | 3 | import android.opengl.GLSurfaceView; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.view.MotionEvent; 7 | import android.view.View; 8 | 9 | import com.linuxpara.agles20tutorials.R; 10 | 11 | import butterknife.BindView; 12 | import butterknife.ButterKnife; 13 | import butterknife.OnClick; 14 | import butterknife.OnTouch; 15 | 16 | public class CubeActivity extends AppCompatActivity { 17 | 18 | @BindView(R.id.cube_gl_view) 19 | GLSurfaceView mGLView; 20 | private float mPreX; 21 | private float mPreY; 22 | private CubeRender mCubeRender; 23 | 24 | @Override 25 | protected void onCreate(Bundle savedInstanceState) { 26 | super.onCreate(savedInstanceState); 27 | setContentView(R.layout.activity_cube); 28 | ButterKnife.bind(this); 29 | 30 | mCubeRender = new CubeRender(mGLView); 31 | mGLView.setEGLContextClientVersion(2); 32 | mGLView.setRenderer(mCubeRender); 33 | mGLView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); 34 | } 35 | 36 | @Override 37 | protected void onResume() { 38 | super.onResume(); 39 | mGLView.onResume(); 40 | } 41 | 42 | @Override 43 | protected void onPause() { 44 | super.onPause(); 45 | mGLView.onPause(); 46 | } 47 | 48 | @OnClick({R.id.cube_x_rotate, R.id.cube_y_rotate}) 49 | public void onBtnClick(View view) { 50 | switch (view.getId()) { 51 | case R.id.cube_x_rotate: 52 | mCubeRender.setRAxis(CubeRender.RAxis.X); 53 | break; 54 | case R.id.cube_y_rotate: 55 | mCubeRender.setRAxis(CubeRender.RAxis.Y); 56 | break; 57 | } 58 | } 59 | 60 | @OnTouch(R.id.cube_gl_view) 61 | public boolean onGLViewTouch(View view, MotionEvent event) { 62 | switch (event.getAction()) { 63 | case MotionEvent.ACTION_DOWN: 64 | mPreX = event.getX(); 65 | mPreY = event.getY(); 66 | break; 67 | case MotionEvent.ACTION_MOVE: 68 | mCubeRender.rotate(event.getX() - mPreX, event.getY() - mPreY); 69 | mPreX = event.getX(); 70 | mPreY = event.getY(); 71 | break; 72 | case MotionEvent.ACTION_UP: 73 | 74 | break; 75 | } 76 | return true; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/cube/CubeRender.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.cube; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | import android.graphics.Camera; 6 | import android.opengl.GLES20; 7 | import android.opengl.GLSurfaceView; 8 | import android.opengl.Matrix; 9 | import android.util.Log; 10 | 11 | import com.linuxpara.agles20tutorials.GraphicalRender; 12 | import com.linuxpara.agles20tutorials.R; 13 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 14 | 15 | import java.nio.ByteBuffer; 16 | import java.nio.FloatBuffer; 17 | import java.nio.IntBuffer; 18 | 19 | /** 20 | * Date: 2018/3/9 21 | * ************************************************************* 22 | * Auther: 陈占洋 23 | * ************************************************************* 24 | * Email: zhanyang.chen@gmail.com 25 | * ************************************************************* 26 | * Description: 27 | */ 28 | 29 | class CubeRender extends GraphicalRender { 30 | 31 | private static final int CUBE_SHADER_TAG = 0; 32 | 33 | private int mCubeShaderProgram; 34 | 35 | private int a_position; 36 | private int a_texCoord; 37 | private int u_mMatrix; 38 | private int u_vMatrix; 39 | private int u_projMatrix; 40 | 41 | private int mTextureId; 42 | private int mVertIdxSize; 43 | private FloatBuffer mVertBuf; 44 | private ByteBuffer mVertIdxBuf; 45 | private FloatBuffer mTexCoordBuf; 46 | 47 | private float mXAxis = 1; 48 | private float mYAxis = 0; 49 | private float mAngle = 0; 50 | private RAxis mRAxis = RAxis.X; 51 | 52 | //旋转轴 53 | enum RAxis { 54 | X, Y 55 | } 56 | 57 | public CubeRender(GLSurfaceView glview) { 58 | super(glview); 59 | } 60 | 61 | @Override 62 | public void onCreate() { 63 | //设置背景 64 | GLES20.glClearColor(0.5f, 0.5f, 0.5f, 0.5f); 65 | //开启深度测试,在绘制3D效果时,需要开启深度测试, 66 | // 否则绘制出来的3D顶点在平面上,效果跟想要的结果不一样。 67 | GLES20.glEnable(GLES20.GL_DEPTH_TEST); 68 | } 69 | 70 | @Override 71 | public void onChange(int width, int height) { 72 | //宽高比 73 | float r = (float) width / height; 74 | //设置视口 75 | GLES20.glViewport(0, 0, width, height); 76 | //设置模型矩阵为单位矩阵 77 | Matrix.setIdentityM(sMMatrix, 0); 78 | //设置摄像机位置、观察矩阵 79 | Matrix.setLookAtM(sVMatrix, 0, 80 | 0, 0, 6, 81 | 0, 0, 0, 82 | 0, 1, 0); 83 | //设置平截头体、投影矩阵(透视投影) 84 | Matrix.frustumM(sProjMatrix, 0, 85 | -r, r, 1, -1,//此时屏幕坐标原点为屏幕中心点 86 | 3, 9); 87 | //初始化顶点数据 88 | initVert(); 89 | //初始化顶点索引 90 | initVertIdx(); 91 | //根据将资源图片转成纹理 92 | Bitmap bitmap = BitmapFactory.decodeResource(getView().getResources(), R.mipmap.box); 93 | mTextureId = genBitmapTextureId(bitmap); 94 | bitmap.recycle(); 95 | //初始化纹理坐标 96 | initTextureCoord(); 97 | //初始化着色器程序 98 | initShaderFromAsset(CUBE_SHADER_TAG, "cube/cube.vert", "cube/cube.frag"); 99 | 100 | } 101 | 102 | @Override 103 | public void onDraw() { 104 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); 105 | 106 | Matrix.setRotateM(sMMatrix, 0, 107 | mAngle, mXAxis, mYAxis, 0); 108 | 109 | GLES20.glUseProgram(mCubeShaderProgram); 110 | 111 | GLES20.glVertexAttribPointer(a_position, 3, GLES20.GL_FLOAT, false, 0, mVertBuf); 112 | GLES20.glVertexAttribPointer(a_texCoord, 2, GLES20.GL_FLOAT, false, 0, mTexCoordBuf); 113 | 114 | GLES20.glUniformMatrix4fv(u_mMatrix, 1, false, sMMatrix, 0); 115 | GLES20.glUniformMatrix4fv(u_vMatrix, 1, false, sVMatrix, 0); 116 | GLES20.glUniformMatrix4fv(u_projMatrix, 1, false, sProjMatrix, 0); 117 | 118 | GLES20.glActiveTexture(GLES20.GL_TEXTURE0); 119 | GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureId); 120 | 121 | GLES20.glEnableVertexAttribArray(a_position); 122 | GLES20.glEnableVertexAttribArray(a_texCoord); 123 | 124 | GLES20.glDrawElements(GLES20.GL_TRIANGLES, mVertIdxSize, GLES20.GL_UNSIGNED_BYTE, mVertIdxBuf); 125 | 126 | GLES20.glDisableVertexAttribArray(a_position); 127 | GLES20.glDisableVertexAttribArray(a_texCoord); 128 | } 129 | 130 | @Override 131 | protected void findShaderAttr(int shaderTag, int shaderProgram) { 132 | if (shaderTag == CUBE_SHADER_TAG) { 133 | mCubeShaderProgram = shaderProgram; 134 | 135 | a_position = GLES20.glGetAttribLocation(mCubeShaderProgram, "a_position"); 136 | a_texCoord = GLES20.glGetAttribLocation(mCubeShaderProgram, "a_texCoord"); 137 | 138 | u_mMatrix = GLES20.glGetUniformLocation(mCubeShaderProgram, "u_MMatrix"); 139 | u_vMatrix = GLES20.glGetUniformLocation(mCubeShaderProgram, "u_VMatrix"); 140 | u_projMatrix = GLES20.glGetUniformLocation(mCubeShaderProgram, "u_ProjMatrix"); 141 | } 142 | } 143 | 144 | @Override 145 | protected void initVert() { 146 | float[] verts = { 147 | -0.5f, 0.5f, 0.5f,//0 148 | -0.5f, -0.5f, 0.5f,//1 149 | 0.5f, 0.5f, 0.5f,//2 150 | 0.5f, -0.5f, 0.5f,//3 151 | 152 | 0.5f, 0.5f, -0.5f,//4 153 | 0.5f, -0.5f, -0.5f,//5 154 | -0.5f, 0.5f, -0.5f,//6 155 | -0.5f, -0.5f, -0.5f,//7 156 | }; 157 | mVertBuf = ShaderUtils.getFloatBuffer(verts); 158 | } 159 | 160 | @Override 161 | protected void initVertIdx() { 162 | byte[] vertIdxs = { 163 | 0, 1, 2, 1, 2, 3,//正面 164 | 2, 3, 4, 3, 4, 5,//右侧面 165 | 4, 5, 6, 5, 6, 7,//背面 166 | 6, 7, 0, 7, 0, 1,//左侧面 167 | 0, 2, 6, 2, 6, 4,//上面 168 | 1, 3, 7, 3, 7, 5//下面 169 | }; 170 | mVertIdxSize = vertIdxs.length; 171 | mVertIdxBuf = ShaderUtils.getByteBuffer(vertIdxs); 172 | } 173 | 174 | @Override 175 | protected void initTextureCoord() { 176 | float[] texCoords = { 177 | 0, 1, 178 | 0, 0, 179 | 1, 1, 180 | 1, 0, 181 | 182 | 0, 1, 183 | 0, 0, 184 | 1, 1, 185 | 1, 0 186 | }; 187 | mTexCoordBuf = ShaderUtils.getFloatBuffer(texCoords); 188 | } 189 | 190 | /** 191 | * 设置旋转轴 192 | * 193 | * @param r_axis 194 | */ 195 | public void setRAxis(RAxis r_axis) { 196 | mRAxis = r_axis; 197 | mAngle = 0; 198 | if (r_axis == RAxis.X) { 199 | mXAxis = 1; 200 | mYAxis = 0; 201 | } else { 202 | mXAxis = 0; 203 | mYAxis = 1; 204 | } 205 | } 206 | 207 | public void rotate(float distanceX, float distanceY) { 208 | if (mRAxis == RAxis.X) { 209 | if (Math.abs(distanceX) > Math.abs(distanceY)) { 210 | return; 211 | } 212 | mAngle += -distanceY / 5; 213 | return; 214 | } 215 | if (mRAxis == RAxis.Y) { 216 | if (Math.abs(distanceY) > Math.abs(distanceX)) { 217 | return; 218 | } 219 | mAngle += distanceX / 5; 220 | return; 221 | } 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/earth/EarthActivity.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.earth; 2 | 3 | import android.opengl.GLSurfaceView; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | 7 | import com.linuxpara.agles20tutorials.R; 8 | 9 | import butterknife.BindView; 10 | import butterknife.ButterKnife; 11 | 12 | public class EarthActivity extends AppCompatActivity { 13 | 14 | @BindView(R.id.earth_gl_view) 15 | GLSurfaceView mGLView; 16 | private EarthRender mEarthRender; 17 | 18 | @Override 19 | protected void onCreate(Bundle savedInstanceState) { 20 | super.onCreate(savedInstanceState); 21 | setContentView(R.layout.activity_earth); 22 | ButterKnife.bind(this); 23 | 24 | mEarthRender = new EarthRender(mGLView); 25 | mGLView.setEGLContextClientVersion(2); 26 | mGLView.setRenderer(mEarthRender); 27 | mGLView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/earth/EarthRender.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.earth; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | import android.opengl.GLES20; 6 | import android.opengl.GLSurfaceView; 7 | import android.opengl.Matrix; 8 | import android.os.Handler; 9 | import android.os.Looper; 10 | import android.os.Message; 11 | 12 | import com.linuxpara.agles20tutorials.GraphicalRender; 13 | import com.linuxpara.agles20tutorials.R; 14 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 15 | 16 | import java.nio.FloatBuffer; 17 | import java.util.ArrayList; 18 | 19 | /** 20 | * Date: 2018/3/11 21 | * ************************************************************* 22 | * Auther: 陈占洋 23 | * ************************************************************* 24 | * Email: zhanyang.chen@gmail.com 25 | * ************************************************************* 26 | * Description: 27 | */ 28 | 29 | class EarthRender extends GraphicalRender { 30 | 31 | private static final int SPHERE_SHADER_TAG = 0; 32 | 33 | private int a_position; 34 | private int a_texCoord; 35 | private int u_lightPos; 36 | private int u_viewPos; 37 | private int u_lightColor; 38 | private int u_mMatrix; 39 | private int u_vMatrix; 40 | private int u_projMatrix; 41 | 42 | private int mSphereShaderProgram; 43 | private FloatBuffer mVertBuf; 44 | private FloatBuffer mTexCoordBuf; 45 | private int mVertSize; 46 | private int mTextureId; 47 | 48 | private int mVStep = 5;//步长需要能被90整除 49 | private int mHStep = 2 * mVStep; 50 | private float mR = 1.5f; 51 | 52 | private float mAngle; 53 | private final Handler mHandler; 54 | private float mRotateX = (float) Math.sin(Math.toRadians(23.5)); 55 | private float mRotateY = (float) Math.cos(Math.toRadians(23.5)); 56 | 57 | 58 | public EarthRender(GLSurfaceView view) { 59 | super(view); 60 | mHandler = new Handler(Looper.getMainLooper()) { 61 | @Override 62 | public void handleMessage(Message msg) { 63 | mAngle++; 64 | mHandler.sendEmptyMessageDelayed(0, 40); 65 | } 66 | }; 67 | mHandler.sendEmptyMessageDelayed(0, 100); 68 | } 69 | 70 | @Override 71 | public void onCreate() { 72 | GLES20.glClearColor(0.5f, 0.5f, 0.5f, 0.5f); 73 | GLES20.glEnable(GLES20.GL_DEPTH_TEST); 74 | } 75 | 76 | @Override 77 | public void onChange(int width, int height) { 78 | GLES20.glViewport(0, 0, width, height); 79 | float r = (float) width / height; 80 | 81 | Matrix.setIdentityM(sMMatrix, 0); 82 | //setRotateEulerM:欧拉角转成旋转矩阵 83 | //rotateM:基于上次旋转,累加 84 | //setRotateM:与rotateM相反不会累加,基于0 85 | Matrix.setRotateM(sMMatrix, 0, -23.5f, 0, 0, 1); 86 | 87 | Matrix.setLookAtM(sVMatrix, 0, 88 | 0, 0, 8, 89 | 0, 0, 0, 90 | 0, 1, 0); 91 | 92 | Matrix.frustumM(sProjMatrix, 0, 93 | -r, r, -1, 1, 94 | 3, 13); 95 | 96 | initVert(); 97 | initTextureCoord(); 98 | 99 | Bitmap bitmap = BitmapFactory.decodeResource(getView().getResources(), R.mipmap.earth); 100 | mTextureId = genBitmapTextureId(bitmap); 101 | bitmap.recycle(); 102 | 103 | initShaderFromAsset(SPHERE_SHADER_TAG, "earth/earth.vert", "earth/earth.frag"); 104 | } 105 | 106 | @Override 107 | public void onDraw() { 108 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); 109 | 110 | Matrix.setRotateM(sMMatrix, 0, mAngle, mRotateX, mRotateY, 0); 111 | GLES20.glUseProgram(mSphereShaderProgram); 112 | 113 | GLES20.glVertexAttribPointer(a_position, 3, GLES20.GL_FLOAT, false, 0, mVertBuf); 114 | GLES20.glVertexAttribPointer(a_texCoord, 2, GLES20.GL_FLOAT, false, 0, mTexCoordBuf); 115 | //给光源位置赋值 116 | GLES20.glUniform3fv(u_lightPos, 1, new float[]{40, 0, 0}, 0); 117 | //给观察点位置赋值(setLookAtM中eye的xyz) 118 | GLES20.glUniform3fv(u_viewPos, 1, new float[]{0.0f, 0.0f, 8.0f}, 0); 119 | //给光源颜色赋值 120 | GLES20.glUniform4fv(u_lightColor, 1, new float[]{1.0f, 1.0f, 1.0f, 1.0f}, 0); 121 | 122 | GLES20.glUniformMatrix4fv(u_mMatrix, 1, false, sMMatrix, 0); 123 | GLES20.glUniformMatrix4fv(u_vMatrix, 1, false, sVMatrix, 0); 124 | GLES20.glUniformMatrix4fv(u_projMatrix, 1, false, sProjMatrix, 0); 125 | 126 | GLES20.glActiveTexture(GLES20.GL_TEXTURE0); 127 | GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureId); 128 | 129 | GLES20.glEnableVertexAttribArray(a_position); 130 | GLES20.glEnableVertexAttribArray(a_texCoord); 131 | 132 | GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, mVertSize); 133 | 134 | GLES20.glDisableVertexAttribArray(a_position); 135 | GLES20.glDisableVertexAttribArray(a_texCoord); 136 | 137 | } 138 | 139 | @Override 140 | protected void findShaderAttr(int shaderTag, int shaderProgram) { 141 | if (shaderTag == SPHERE_SHADER_TAG) { 142 | mSphereShaderProgram = shaderProgram; 143 | a_position = GLES20.glGetAttribLocation(mSphereShaderProgram, "a_position"); 144 | a_texCoord = GLES20.glGetAttribLocation(mSphereShaderProgram, "a_texCoord"); 145 | 146 | u_lightPos = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_lightPos"); 147 | u_viewPos = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_viewPos"); 148 | u_lightColor = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_lightColor"); 149 | 150 | u_mMatrix = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_MMatrix"); 151 | u_vMatrix = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_VMatrix"); 152 | u_projMatrix = GLES20.glGetUniformLocation(mSphereShaderProgram, "u_ProjMatrix"); 153 | 154 | } 155 | } 156 | 157 | @Override 158 | protected void initVert() { 159 | ArrayList vertList = new ArrayList<>(); 160 | 161 | for (int vAngle = -90; vAngle < 90; vAngle += mVStep) { 162 | 163 | double hR1 = mR * Math.cos(Math.toRadians(vAngle)); 164 | double y1 = mR * Math.sin(Math.toRadians(vAngle)); 165 | 166 | double hR2 = mR * Math.cos(Math.toRadians(vAngle + mVStep)); 167 | double y2 = mR * Math.sin(Math.toRadians(vAngle + mVStep)); 168 | 169 | for (int hAngle = 0; hAngle <= 360; hAngle += mHStep) { 170 | double x1 = hR1 * Math.cos(Math.toRadians(hAngle)); 171 | double z1 = hR1 * Math.sin(Math.toRadians(hAngle)); 172 | 173 | double x2 = hR2 * Math.cos(Math.toRadians(hAngle)); 174 | double z2 = hR2 * Math.sin(Math.toRadians(hAngle)); 175 | 176 | vertList.add((float) x1); 177 | vertList.add((float) y1); 178 | vertList.add((float) z1); 179 | 180 | vertList.add((float) x2); 181 | vertList.add((float) y2); 182 | vertList.add((float) z2); 183 | } 184 | } 185 | float[] verts = new float[vertList.size()]; 186 | for (int i = 0; i < vertList.size(); i++) { 187 | verts[i] = vertList.get(i); 188 | } 189 | mVertSize = verts.length / 3; 190 | mVertBuf = ShaderUtils.getFloatBuffer(verts); 191 | } 192 | 193 | @Override 194 | protected void initTextureCoord() { 195 | ArrayList texCoordList = new ArrayList<>(); 196 | for (int i = 0; i < 180; i += mVStep) { 197 | float t1 = 1 - i / 180.0f; 198 | float t2 = 1 - (i + mVStep) / 180.0f; 199 | for (int j = 0; j <= 360; j += mHStep) { 200 | float s = 1 - j / 360.0f; 201 | 202 | texCoordList.add(s); 203 | texCoordList.add(t1); 204 | 205 | texCoordList.add(s); 206 | texCoordList.add(t2); 207 | } 208 | } 209 | float[] texCoords = new float[texCoordList.size()]; 210 | for (int i = 0; i < texCoordList.size(); i++) { 211 | texCoords[i] = texCoordList.get(i); 212 | } 213 | mTexCoordBuf = ShaderUtils.getFloatBuffer(texCoords); 214 | } 215 | 216 | } 217 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/triangle/TriangleActivity.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.triangle; 2 | 3 | import android.opengl.GLSurfaceView; 4 | import android.os.Bundle; 5 | import android.support.v7.app.AppCompatActivity; 6 | 7 | 8 | import com.linuxpara.agles20tutorials.R; 9 | 10 | import butterknife.BindView; 11 | import butterknife.ButterKnife; 12 | 13 | /** 14 | * Date: 2018/1/15 15 | * ************************************************************* 16 | * Auther: 陈占洋 17 | * ************************************************************* 18 | * Email: zhanyang.chen@gmail.com 19 | * ************************************************************* 20 | * Description: 展示三角形界面 21 | */ 22 | public class TriangleActivity extends AppCompatActivity { 23 | 24 | @BindView(R.id.triangle_gl_view) 25 | GLSurfaceView mGLView; 26 | 27 | @Override 28 | protected void onCreate(Bundle savedInstanceState) { 29 | super.onCreate(savedInstanceState); 30 | setContentView(R.layout.activity_triangle); 31 | ButterKnife.bind(this); 32 | 33 | mGLView.setEGLContextClientVersion(2); 34 | mGLView.setRenderer(new TriangleRender(mGLView)); 35 | mGLView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/triangle/TriangleRender.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.triangle; 2 | 3 | import android.opengl.GLES20; 4 | import android.opengl.GLSurfaceView; 5 | import android.opengl.Matrix; 6 | 7 | 8 | import com.linuxpara.agles20tutorials.GraphicalRender; 9 | import com.linuxpara.agles20tutorials.util.ShaderUtils; 10 | 11 | import java.nio.FloatBuffer; 12 | 13 | /** 14 | * Date: 2018/1/16 15 | * ************************************************************* 16 | * Auther: 陈占洋 17 | * ************************************************************* 18 | * Email: zhanyang.chen@gmail.com 19 | * ************************************************************* 20 | * Description: 三角形渲染器 21 | */ 22 | 23 | public class TriangleRender extends GraphicalRender { 24 | 25 | private static final int TRIANGLE_SHADER_TAG = 0; 26 | 27 | private float mWidth; 28 | private float mHeight; 29 | 30 | private int a_position; 31 | private int a_color; 32 | private int u_mMatrix; 33 | private int u_vMatrix; 34 | private int u_projMatrix; 35 | 36 | private FloatBuffer mVertBuf; 37 | private FloatBuffer mVertColorBuf; 38 | private int mVertSize; 39 | 40 | private int mTriangleShaderProgram; 41 | 42 | public TriangleRender(GLSurfaceView view) { 43 | super(view); 44 | } 45 | 46 | @Override 47 | public void onCreate() { 48 | //设置背景色,普通的setBackground()对GLSurfaceView无效 49 | GLES20.glClearColor(0.5f, 0.5f, 0.5f, 0.5f); 50 | } 51 | 52 | @Override 53 | public void onChange(int width, int height) { 54 | //设置视口 55 | GLES20.glViewport(0, 0, width, height); 56 | float radio = (float) width / height; 57 | //初始化变换矩阵为单位矩阵 58 | Matrix.setIdentityM(sMMatrix, 0); 59 | //设置观察点(相机)矩阵,在坐标转换中详细介绍了每个参数的含义、及系统是怎么确定摄像机位置的。 60 | Matrix.setLookAtM(sVMatrix, 0, 61 | 0, 0, 3,//摄像机位置, 62 | 0, 0, 0,//目标位置(摄像机和目标位置可以决定屏幕的坐标体系) 63 | 0, 1, 0);//up向量(上向量) 64 | //设置正交投影矩阵 65 | Matrix.orthoM(sProjMatrix, 0, 66 | 0, radio, 1, 0,//平截头体的四个坐标(可以确定坐标原点的位置,此时坐标原点为屏幕左上角) 67 | 3, 10);//近平面距离摄像机的距离、远平面距离摄像机的距离 68 | mWidth = radio; 69 | mHeight = 1; 70 | //初始化顶点数据(顶点在局部空间中的位置) 71 | initVert(); 72 | //初始化顶点颜色 73 | initVertColor(); 74 | //加载着色器程序 75 | initShaderFromAsset(TRIANGLE_SHADER_TAG, "triangle/triangle.vert", "triangle/triangle.frag"); 76 | } 77 | 78 | @Override 79 | public void onDraw() { 80 | //清除颜色缓存 81 | GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); 82 | //使用指定着色器程序 83 | GLES20.glUseProgram(mTriangleShaderProgram); 84 | //给着色器中attribute修饰的变量赋值 85 | GLES20.glVertexAttribPointer(a_position, 3, GLES20.GL_FLOAT, false, 0, mVertBuf); 86 | //给着色器中的a_color变量赋值 87 | GLES20.glVertexAttribPointer(a_color, 4, GLES20.GL_FLOAT, false, 0, mVertColorBuf); 88 | //给着色器中uniform修饰的变量赋值 89 | GLES20.glUniformMatrix4fv(u_mMatrix, 1, false, sMMatrix, 0); 90 | GLES20.glUniformMatrix4fv(u_vMatrix, 1, false, sVMatrix, 0); 91 | GLES20.glUniformMatrix4fv(u_projMatrix, 1, false, sProjMatrix, 0); 92 | //启用顶点位置数据 93 | GLES20.glEnableVertexAttribArray(a_position); 94 | //启用顶点颜色数据 95 | GLES20.glEnableVertexAttribArray(a_color); 96 | //绘制图形,数组法绘制 97 | GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, mVertSize); 98 | //绘制图形,索引法绘制 99 | //GLES20.glDrawElements(GLES20.GL_TRIANGLES,mVertSize,GLES20.GL_INT,mVertIdxBuf); 100 | //关闭顶点属性 101 | GLES20.glDisableVertexAttribArray(a_position); 102 | //关闭顶点颜色属性 103 | GLES20.glDisableVertexAttribArray(a_color); 104 | 105 | } 106 | 107 | @Override 108 | protected void findShaderAttr(int shaderTag, int shaderProgram) { 109 | if (TRIANGLE_SHADER_TAG == shaderTag) { 110 | mTriangleShaderProgram = shaderProgram; 111 | //获取顶点着色器中a_position指针(attribute类型) 112 | a_position = GLES20.glGetAttribLocation(mTriangleShaderProgram, "a_position"); 113 | //获取顶点着色器中a_color指针(attribute类型) 114 | a_color = GLES20.glGetAttribLocation(mTriangleShaderProgram, "a_color"); 115 | //获取顶点着色器中u_MMatrix指针(uniform类型) 116 | u_mMatrix = GLES20.glGetUniformLocation(mTriangleShaderProgram, "u_MMatrix"); 117 | //获取顶点着色器中u_VMatrix指针(uniform类型) 118 | u_vMatrix = GLES20.glGetUniformLocation(mTriangleShaderProgram, "u_VMatrix"); 119 | //获取顶点着色器中u_ProjMatrix指针(uniform类型) 120 | u_projMatrix = GLES20.glGetUniformLocation(mTriangleShaderProgram, "u_ProjMatrix"); 121 | } 122 | } 123 | 124 | @Override 125 | protected void initVert() { 126 | float[] verts = { 127 | mWidth / 2, 0.0f, 0.0f,//第一个顶点的xyz坐标 128 | 0.0f, mHeight, 0.0f,//第二个顶点的xyz坐标 129 | mWidth, mHeight, 0.0f//第三个顶点的xyz坐标 130 | }; 131 | //顶点个数 132 | mVertSize = verts.length / 3; 133 | mVertBuf = ShaderUtils.getFloatBuffer(verts); 134 | } 135 | 136 | @Override 137 | protected void initVertColor() { 138 | float[] vertColor = { 139 | 1.0f, 0.0f, 0.0f, 0.0f,//第一个顶点的rgba颜色值 140 | 0.0f, 1.0f, 0.0f, 0.0f,//第二个顶点的rgba颜色值 141 | 0.0f, 0.0f, 1.0f, 0.0f//第三个顶点的rgba颜色值 142 | }; 143 | mVertColorBuf = ShaderUtils.getFloatBuffer(vertColor); 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /app/src/main/java/com/linuxpara/agles20tutorials/util/ShaderUtils.java: -------------------------------------------------------------------------------- 1 | package com.linuxpara.agles20tutorials.util; 2 | 3 | import android.content.res.Resources; 4 | import android.opengl.GLES11Ext; 5 | import android.opengl.GLES20; 6 | import android.util.Log; 7 | 8 | import java.io.ByteArrayOutputStream; 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.nio.ByteBuffer; 12 | import java.nio.ByteOrder; 13 | import java.nio.FloatBuffer; 14 | import java.nio.IntBuffer; 15 | 16 | /** 17 | * Date: 2018/1/15 18 | * ************************************************************* 19 | * Auther: 陈占洋 20 | * ************************************************************* 21 | * Email: zhanyang.chen@gmail.com 22 | * ************************************************************* 23 | * Description: 着色器相关的工具类 24 | */ 25 | 26 | public class ShaderUtils { 27 | /** 28 | * 获取浮点类型缓存 29 | * 30 | * @param buffer 31 | * @return 32 | */ 33 | public static FloatBuffer getFloatBuffer(float[] buffer) { 34 | 35 | FloatBuffer floatBuffer = ByteBuffer.allocateDirect(buffer.length * 4) 36 | .order(ByteOrder.nativeOrder()) 37 | .asFloatBuffer() 38 | .put(buffer); 39 | floatBuffer.position(0); 40 | 41 | return floatBuffer; 42 | } 43 | 44 | /** 45 | * 获取int类型缓存 46 | * 47 | * @param buffer 48 | * @return 49 | */ 50 | public static IntBuffer getIntBuffer(int[] buffer) { 51 | 52 | IntBuffer intBuffer = ByteBuffer.allocateDirect(buffer.length * 4) 53 | .order(ByteOrder.nativeOrder()) 54 | .asIntBuffer() 55 | .put(buffer); 56 | intBuffer.position(0); 57 | 58 | return intBuffer; 59 | } 60 | 61 | /** 62 | * 获取字节类型缓存 63 | * 64 | * @param buffer 65 | * @return 66 | */ 67 | public static ByteBuffer getByteBuffer(byte[] buffer) { 68 | 69 | ByteBuffer byteBuffer = ByteBuffer.allocateDirect(buffer.length) 70 | .order(ByteOrder.nativeOrder()) 71 | .put(buffer); 72 | byteBuffer.position(0); 73 | 74 | return byteBuffer; 75 | } 76 | 77 | /** 78 | * 生成纹理Id 79 | * @return 80 | */ 81 | public static int genTextureId(){ 82 | int[] textures = new int[1]; 83 | GLES20.glGenTextures(1,textures,0); 84 | GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textures[0]); 85 | 86 | GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_NEAREST); 87 | GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR); 88 | 89 | GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_CLAMP_TO_EDGE); 90 | GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE); 91 | 92 | return textures[0]; 93 | } 94 | 95 | /** 96 | * 生成OES扩展纹理Id 97 | * @return 98 | */ 99 | public static int genOESTextureId(){ 100 | int[] textures = new int[1]; 101 | GLES20.glGenTextures(1,textures,0); 102 | GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,textures[0]); 103 | 104 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,GLES20.GL_TEXTURE_MIN_FILTER,GLES20.GL_NEAREST); 105 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,GLES20.GL_TEXTURE_MAG_FILTER,GLES20.GL_LINEAR); 106 | 107 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,GLES20.GL_TEXTURE_WRAP_S,GLES20.GL_CLAMP_TO_EDGE); 108 | GLES20.glTexParameterf(GLES11Ext.GL_TEXTURE_EXTERNAL_OES,GLES20.GL_TEXTURE_WRAP_T,GLES20.GL_CLAMP_TO_EDGE); 109 | 110 | return textures[0]; 111 | } 112 | 113 | /** 114 | * 从资产目录中获取shader代码 115 | * 116 | * @param fileName 117 | * @return 118 | */ 119 | public static String getCodeFromAsset(String fileName, Resources resources) { 120 | 121 | InputStream in = null; 122 | ByteArrayOutputStream baos = null; 123 | String result = ""; 124 | 125 | try { 126 | in = resources.getAssets().open(fileName); 127 | 128 | baos = new ByteArrayOutputStream(); 129 | 130 | byte[] buf = new byte[1024]; 131 | int len = 0; 132 | while ((len = in.read(buf)) != -1) { 133 | baos.write(buf, 0, len); 134 | } 135 | String source = baos.toString("UTF-8"); 136 | result = source.replaceAll("\\r\\n", "\n"); 137 | } catch (IOException e) { 138 | e.printStackTrace(); 139 | } finally { 140 | if (in != null) { 141 | try { 142 | in.close(); 143 | } catch (IOException e) { 144 | e.printStackTrace(); 145 | } 146 | } 147 | if (baos != null) { 148 | try { 149 | baos.close(); 150 | } catch (IOException e) { 151 | e.printStackTrace(); 152 | } 153 | } 154 | return result; 155 | } 156 | } 157 | 158 | /** 159 | * 创建着色器程序。 160 | * 161 | * @param verCode 162 | * @param fragCode 163 | * @return 164 | */ 165 | public static int createProgram(String verCode, String fragCode) { 166 | //加载顶点着色器代码,获取顶点着色器。 167 | int verShader = loadShader(GLES20.GL_VERTEX_SHADER, verCode); 168 | if (verShader == 0) { 169 | return 0; 170 | } 171 | //加载片元着色器代码,获取片元着色器。 172 | int fragShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragCode); 173 | if (fragShader == 0) { 174 | return 0; 175 | } 176 | //创建着色器程序 177 | int program = GLES20.glCreateProgram(); 178 | if (program != 0) { 179 | //将顶点着色器依赖到创建好的着色器程序上。 180 | GLES20.glAttachShader(program, verShader); 181 | //检查错误 182 | checkGLError("glAttachShader"); 183 | //将片元着色器依赖到创建好的着色器程序上。 184 | GLES20.glAttachShader(program, fragShader); 185 | //检查错误 186 | checkGLError("glAttachShader"); 187 | //链接着色器程序。 188 | GLES20.glLinkProgram(program); 189 | 190 | int[] linked = new int[1]; 191 | //获取着色器程序信息检查是否出错。 192 | GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0); 193 | if (linked[0] == 0) { 194 | Log.e("ES20_ERROR", "Could not link program: "); 195 | Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program)); 196 | GLES20.glDeleteProgram(program); 197 | program = 0; 198 | } 199 | } 200 | //删除着色器 201 | GLES20.glDeleteShader(verShader); 202 | GLES20.glDeleteShader(fragShader); 203 | return program; 204 | } 205 | 206 | /** 207 | * 加载着色器代码 208 | * 209 | * @param shaderType 着色器类型,GLES20.GL_VERTEX_SHADER(顶点着色器) 210 | * GLES20.GL_FRAGMENT_SHADER(片元着色器) 211 | * @param shaderCode 着色器代码 212 | * @return 213 | */ 214 | private static int loadShader(int shaderType, String shaderCode) { 215 | //创建shader索引 216 | int shader = GLES20.glCreateShader(shaderType); 217 | if (shader != 0) { 218 | //加载shader代码 219 | GLES20.glShaderSource(shader, shaderCode); 220 | //编译shader代码 221 | GLES20.glCompileShader(shader); 222 | int[] complied = new int[1]; 223 | //获取shader编译信息 224 | GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, complied, 0); 225 | if (complied[0] == 0) { 226 | Log.e("ES20_ERROR", "Could not compile shader " + shaderType + ":"); 227 | Log.e("ES20_ERROR", GLES20.glGetShaderInfoLog(shader)); 228 | //出错后,删除着色器。 229 | GLES20.glDeleteShader(shader); 230 | shader = 0; 231 | } 232 | } 233 | return shader; 234 | 235 | } 236 | 237 | /** 238 | * 检查错误 239 | * 240 | * @param op 241 | */ 242 | public static void checkGLError(String op) { 243 | 244 | int error = 0; 245 | if ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { 246 | Log.e("ES20_ERROR", op + ": glError " + error); 247 | throw new RuntimeException(op + ": glError " + error); 248 | } 249 | 250 | } 251 | 252 | } 253 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_camera.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 14 | 15 | 24 | 25 | 32 | 33 | 42 | 43 | 44 | 45 | 53 | 54 | 60 | 61 | 66 | 67 | 77 | 78 | 82 | 83 | 93 | 94 | 98 | 99 | 109 | 110 | 114 | 115 | 125 | 126 | 130 | 131 | 141 | 142 | 146 | 147 | 157 | 158 | 162 | 163 | 164 | 165 | 166 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_cube.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 |