├── gears
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── assets
│ │ ├── gears.frag
│ │ └── gears.vert
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── org
│ │ └── lwjgl
│ │ └── demo
│ │ └── android
│ │ └── gears
│ │ ├── MainActivity.java
│ │ └── Gears.java
├── proguard-rules.pro
└── build.gradle
├── hellovulkan
├── .gitignore
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ ├── dimens.xml
│ │ │ ├── colors.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── values-w820dp
│ │ │ └── dimens.xml
│ │ └── layout
│ │ │ └── activity_main.xml
│ │ ├── java
│ │ └── org
│ │ │ └── lwjgl
│ │ │ └── demo
│ │ │ └── android
│ │ │ └── hellovulkan
│ │ │ ├── MainActivity.java
│ │ │ ├── VKSurfaceView.java
│ │ │ └── HelloVulkan.java
│ │ └── AndroidManifest.xml
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── lwjgl
└── build.gradle
├── .idea
├── copyright
│ └── profiles_settings.xml
├── vcs.xml
├── runConfigurations.xml
├── modules.xml
├── compiler.xml
├── gradle.xml
└── misc.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── LICENSE.md
├── README.md
├── gradlew.bat
└── gradlew
/gears/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/hellovulkan/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':lwjgl', ':gears', ':hellovulkan'
2 |
--------------------------------------------------------------------------------
/lwjgl/build.gradle:
--------------------------------------------------------------------------------
1 | configurations.maybeCreate("default")
2 | artifacts.add("default", file('lwjgl.aar'))
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gears/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | LWJGL glxgears
3 |
4 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | LWJGL Hello Vulkan!
3 |
4 |
--------------------------------------------------------------------------------
/gears/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gears/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/gears/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gears/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/gears/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gears/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/gears/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gears/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/gears/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/gears/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/hellovulkan/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/hellovulkan/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/hellovulkan/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/hellovulkan/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LWJGL/android-test/HEAD/hellovulkan/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.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/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gears/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gears/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gears/src/main/assets/gears.frag:
--------------------------------------------------------------------------------
1 | #version 300 es
2 |
3 | precision mediump float;
4 |
5 | uniform vec4 u_COLOR;
6 |
7 | in float v_Shade;
8 |
9 | layout(location = 0) out vec4 out_Color;
10 |
11 | void main() {
12 | out_Color = vec4(u_COLOR.xyz * v_Shade, u_COLOR.w);
13 | }
14 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Feb 02 18:51:34 CET 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gears/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/gears/src/main/assets/gears.vert:
--------------------------------------------------------------------------------
1 | #version 300 es
2 |
3 | uniform mat4 u_MVP;
4 | uniform mat3 u_NORMAL;
5 |
6 | uniform vec3 u_LIGHT;
7 |
8 | layout(location = 0) in vec3 in_Position;
9 | layout(location = 1) in vec3 in_Normal;
10 |
11 | out float v_Shade;
12 |
13 | void main() {
14 | vec3 normal = normalize(u_NORMAL * in_Normal);
15 | v_Shade = max(dot(normal, u_LIGHT), 0.0);
16 | gl_Position = u_MVP * vec4(in_Position, 1.0);
17 | }
18 |
--------------------------------------------------------------------------------
/gears/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/java/org/lwjgl/demo/android/hellovulkan/MainActivity.java:
--------------------------------------------------------------------------------
1 | package org.lwjgl.demo.android.hellovulkan;
2 |
3 | import android.support.v7.app.AppCompatActivity;
4 | import android.os.Bundle;
5 | import android.view.*;
6 |
7 | public class MainActivity extends AppCompatActivity {
8 |
9 | private SurfaceView vkView;
10 |
11 | @Override
12 | protected void onCreate(Bundle savedInstanceState) {
13 | super.onCreate(savedInstanceState);
14 |
15 | vkView = new VKSurfaceView(this);
16 | setContentView(vkView);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/hellovulkan/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in G:\PROGRAMS\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/gears/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | org.gradle.jvmargs=-Xmx1536m
13 |
14 | # When configured, Gradle will run in incubating parallel mode.
15 | # This option should only be used with decoupled projects. More details, visit
16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
17 | # org.gradle.parallel=true
18 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/gears/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
18 |
19 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
13 |
14 |
18 |
19 |
--------------------------------------------------------------------------------
/hellovulkan/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 |
7 | defaultConfig {
8 | applicationId "org.lwjgl.demo.android.hellovulkan"
9 | minSdkVersion 24
10 | targetSdkVersion 25
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | multiDexEnabled true
17 | }
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles 'proguard-rules.pro', getDefaultProguardFile('proguard-android.txt')
22 | }
23 | }
24 | }
25 |
26 | dependencies {
27 | compile fileTree(dir: 'libs', include: ['*.jar'])
28 | compile 'com.android.support:appcompat-v7:25.1.1'
29 | compile project(':lwjgl')
30 | }
31 |
--------------------------------------------------------------------------------
/gears/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in G:\PROGRAMS\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | -optimizations !field/*,!class/merging,*
20 | -optimizationpasses 5
21 |
22 | -keepclassmembers class org.lwjgl.system.** { *; }
23 | -keepclassmembernames class org.lwjgl.system.** { *; }
24 |
25 | -keepclassmembers class sun.misc.Unsafe { *; }
26 | -keepclassmembernames class sun.misc.Unsafe { *; }
--------------------------------------------------------------------------------
/gears/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 25
5 | buildToolsVersion "25.0.2"
6 |
7 | defaultConfig {
8 | applicationId "org.lwjgl.demo.android.gears"
9 | minSdkVersion 24
10 | targetSdkVersion 25
11 | versionCode 1
12 | versionName "1.0"
13 |
14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
15 |
16 | multiDexEnabled true
17 | }
18 | buildTypes {
19 | release {
20 | minifyEnabled false
21 | proguardFiles 'proguard-rules.pro', getDefaultProguardFile('proguard-android.txt')
22 | }
23 | }
24 | }
25 |
26 | repositories {
27 | mavenCentral()
28 | maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
29 | }
30 |
31 | dependencies {
32 | compile fileTree(dir: 'libs', include: ['*.jar'])
33 | compile 'com.android.support:appcompat-v7:25.1.1'
34 | compile 'org.joml:joml:1.9.3-SNAPSHOT'
35 | compile project(':lwjgl')
36 | }
37 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright (c) 2012-present Lightweight Java Game Library
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are
6 | met:
7 |
8 | - Redistributions of source code must retain the above copyright
9 | notice, this list of conditions and the following disclaimer.
10 |
11 | - Redistributions in binary form must reproduce the above copyright
12 | notice, this list of conditions and the following disclaimer in the
13 | documentation and/or other materials provided with the distribution.
14 |
15 | - Neither the name Lightweight Java Game Library nor the names of
16 | its contributors may be used to endorse or promote products derived
17 | from this software without specific prior written permission.
18 |
19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [](https://github.com/LWJGL/android-test/blob/master/LICENSE.md)
4 | 
5 | [](https://slack.lwjgl.org/)
6 |
7 | ## LWJGL 3 - Android example project and tests
8 |
9 | Build instructions for the Android version of lwjgl3:
10 |
11 | - `clone` [lwjgl3](https://github.com/LWJGL/lwjgl3) and `checkout` the `android` branch.
12 | - `SET/export` the `ANDROID_SDK_HOME` environment variable. Its value should be the root of the Android SDK. The Android NDK must also be installed under the root, in the default `ndk-bundle` subdirectory.
13 | - Run `ant compile-templates`. This will take 1-2 minutes.
14 | - Run `ant aar`. This will produce an `lwjgl.aar` file in the `bin/android/` folder.
15 | - Copy `lwjgl.aar` to the `android-test` repository, in the `lwjgl` folder.
16 |
17 | Build instructions for the Android demos:
18 |
19 | - Open the root in Android Studio.
20 | - Wait for gradle synchronization and indexing to complete.
21 | - Build the project.
22 | - Connect a platform 24 compatible device, either via USB or Wi-Fi.
23 | - Launch either the `gears` or `hellovulkan` run configurations. (shortcut: `Alt+Shift+F10`)
24 |
25 | Installation of Vulkan validation layers:
26 |
27 | - Create a JNI library folder for the target architecture. For example:
28 | * `hellovulkan/src/main/jniLibs/arm64-v8a/` or
29 | * `hellovulkan/src/main/jniLibs/armeabi-v7a/`
30 | - Copy the shared libraries from the corresponding folder in the Android NDK. For example:
31 | * `/ndk-bundle/sources/third_party/vulkan/src/build-android/jniLibs/arm64-v8a/` or
32 | * `/ndk-bundle/sources/third_party/vulkan/src/build-android/jniLibs/armeabi-v7a/`
33 | - Set the `VALIDATE` variable to `true` in `HelloVulkan.java:53`
34 |
--------------------------------------------------------------------------------
/gears/src/main/java/org/lwjgl/demo/android/gears/MainActivity.java:
--------------------------------------------------------------------------------
1 | package org.lwjgl.demo.android.gears;
2 |
3 | import android.opengl.*;
4 | import android.os.*;
5 | import android.support.v7.app.*;
6 |
7 | import org.lwjgl.egl.EGL;
8 | import org.lwjgl.egl.*;
9 | import org.lwjgl.opengles.*;
10 | import org.lwjgl.system.*;
11 |
12 | import java.lang.reflect.*;
13 |
14 | import javax.microedition.khronos.egl.EGLConfig;
15 | import javax.microedition.khronos.opengles.*;
16 |
17 | import static org.lwjgl.egl.EGL10.*;
18 | import static org.lwjgl.opengles.GLES20.*;
19 | import static org.lwjgl.system.APIUtil.*;
20 |
21 | public class MainActivity extends AppCompatActivity {
22 |
23 | private Gears gears;
24 |
25 | private GLSurfaceView glView;
26 |
27 | @Override
28 | protected void onCreate(Bundle savedInstanceState) {
29 | super.onCreate(savedInstanceState);
30 |
31 | glView = new GLSurfaceView(this);
32 | glView.setEGLContextClientVersion(2);
33 | glView.setRenderer(new GLSurfaceView.Renderer() {
34 | @Override
35 | public void onSurfaceCreated(GL10 gl, EGLConfig config) {
36 | GLES.createCapabilities();
37 |
38 | /*APIUtil.APIVersion version = apiParseVersion(eglQueryString(eglGetCurrentDisplay(), EGL_VERSION));
39 | EGLCapabilities caps = EGL.createDisplayCapabilities(eglGetCurrentDisplay(), version.major, version.minor);
40 |
41 | System.out.println(caps);
42 | Field[] fields = caps.getClass().getDeclaredFields();
43 | for (Field field : fields) {
44 | try {
45 | if (field.getType() != Boolean.TYPE || !field.getBoolean(caps))
46 | continue;
47 | System.out.println(field.getName());
48 | } catch (IllegalAccessException e) {
49 | e.printStackTrace();
50 | }
51 | }*/
52 |
53 | gears = new Gears(MainActivity.this.getResources());
54 | }
55 |
56 | @Override
57 | public void onSurfaceChanged(GL10 gl, int width, int height) {
58 | gears.reshape(width, height);
59 | }
60 |
61 | @Override
62 | public void onDrawFrame(GL10 gl) {
63 | float sin = (float) Math.sin(System.currentTimeMillis() / 1000.0);
64 |
65 | glClearColor(0.2f, 0.4f, sin * sin, 1.0f);
66 | glClear(GL_COLOR_BUFFER_BIT);
67 |
68 | gears.draw();
69 | gears.idle();
70 | }
71 | });
72 |
73 | setContentView(glView);
74 | }
75 |
76 | }
77 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/hellovulkan/src/main/java/org/lwjgl/demo/android/hellovulkan/VKSurfaceView.java:
--------------------------------------------------------------------------------
1 | package org.lwjgl.demo.android.hellovulkan;
2 |
3 | import android.content.*;
4 | import android.view.*;
5 |
6 | import java.util.concurrent.atomic.*;
7 |
8 | import static org.lwjgl.system.MemoryUtil.*;
9 | import static org.lwjgl.system.android.ANativeWindow.*;
10 |
11 | public class VKSurfaceView extends SurfaceView implements SurfaceHolder.Callback2 {
12 |
13 | private final AtomicBoolean detached = new AtomicBoolean(true);
14 | private final AtomicBoolean hasSurface = new AtomicBoolean(false);
15 |
16 | private final AtomicBoolean framebufferSizeChanged = new AtomicBoolean(false);
17 | private final AtomicInteger framebufferWidth = new AtomicInteger();
18 | private final AtomicInteger framebufferHeight = new AtomicInteger();
19 |
20 | private VKThread thread;
21 |
22 | public VKSurfaceView(Context context) {
23 | super(context);
24 | getHolder().addCallback(this);
25 | }
26 |
27 | @Override
28 | protected void onAttachedToWindow() {
29 | super.onAttachedToWindow();
30 | //System.err.println("onAttachedToWindow()");
31 |
32 | detached.set(false);
33 | thread = new VKThread();
34 | thread.start();
35 | }
36 |
37 | @Override
38 | protected void onDetachedFromWindow() {
39 | super.onDetachedFromWindow();
40 | //System.err.println("onDetachedFromWindow()");
41 |
42 | detached.set(true);
43 | try {
44 | thread.join();
45 | thread = null;
46 | } catch (InterruptedException e) {
47 | e.printStackTrace();
48 | }
49 | }
50 |
51 | @Override
52 | public void surfaceCreated(SurfaceHolder holder) {
53 | //System.err.println("surfaceCreated()");
54 | hasSurface.set(true);
55 | }
56 |
57 | @Override
58 | public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
59 | //System.err.println("surfaceChanged(" + width + ", " + height + ")");
60 |
61 | framebufferWidth.set(width);
62 | framebufferHeight.set(height);
63 | framebufferSizeChanged.set(true);
64 | }
65 |
66 | @Override
67 | public void surfaceRedrawNeeded(SurfaceHolder holder) {
68 | //System.err.println("surfaceRedrawNeeded()");
69 | //helloVulkan.demo_draw();
70 | }
71 |
72 | @Override
73 | public void surfaceDestroyed(SurfaceHolder holder) {
74 | //System.err.println("surfaceDestroyed()");
75 | hasSurface.set(false);
76 | }
77 |
78 | private class VKThread extends Thread {
79 |
80 | VKThread() {
81 | super("VKThread");
82 | }
83 |
84 | private long nativeWindow;
85 | private HelloVulkan renderer;
86 |
87 | @Override
88 | public void run() {
89 | while (!detached.get()) {
90 | while (!hasSurface.get()) {
91 | sleep();
92 | if (detached.get())
93 | break;
94 | }
95 |
96 | if (renderer == null) {
97 | nativeWindow = ANativeWindow_fromSurface(getHolder().getSurface());
98 | if (!init(nativeWindow))
99 | continue;
100 | }
101 |
102 | if (framebufferSizeChanged.get())
103 | updateSurface();
104 |
105 | if ( !renderer.drawFrame() )
106 | cleanup();
107 | }
108 |
109 | cleanup();
110 | }
111 |
112 | private boolean init(long nativeWindow) {
113 | if (nativeWindow == NULL)
114 | return false;
115 |
116 | renderer = new HelloVulkan(nativeWindow);
117 | renderer.initSurface();
118 | return true;
119 | }
120 |
121 | private void sleep() {
122 | try {
123 | Thread.sleep(16);
124 | } catch (InterruptedException e) {
125 | e.printStackTrace();
126 | }
127 | }
128 |
129 | private void updateSurface() {
130 | renderer.framebufferSizeChanged(
131 | framebufferWidth.get(),
132 | framebufferHeight.get()
133 | );
134 | framebufferSizeChanged.set(false);
135 | }
136 |
137 | private void cleanup() {
138 | if (renderer == null)
139 | return;
140 |
141 | renderer.destroy();
142 | renderer = null;
143 | ANativeWindow_release(nativeWindow);
144 | }
145 | }
146 |
147 | }
148 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gears/src/main/java/org/lwjgl/demo/android/gears/Gears.java:
--------------------------------------------------------------------------------
1 | package org.lwjgl.demo.android.gears;
2 |
3 | import android.content.res.*;
4 |
5 | import org.joml.*;
6 | import org.lwjgl.*;
7 | import org.lwjgl.system.*;
8 |
9 | import java.io.*;
10 | import java.nio.*;
11 | import java.nio.channels.*;
12 |
13 | import static java.lang.Math.*;
14 | import static org.lwjgl.opengles.GLES20.*;
15 | import static org.lwjgl.opengles.GLES30.*;
16 | import static org.lwjgl.system.MemoryStack.*;
17 | import static org.lwjgl.system.MemoryUtil.*;
18 |
19 | class Gears {
20 |
21 | private final Gear
22 | gear1,
23 | gear2,
24 | gear3;
25 |
26 | private final int program;
27 |
28 | private final int u_NORMAL;
29 | private final int u_MVP;
30 | private final int u_LIGHT;
31 | private final int u_COLOR;
32 |
33 | // ---------------------
34 |
35 | private final Matrix4d
36 | P = new Matrix4d(),
37 | V = new Matrix4d(),
38 | MVP = new Matrix4d();
39 |
40 | private final Matrix3d normal = new Matrix3d();
41 | private final Vector3d light = new Vector3d();
42 |
43 | private final FloatBuffer vec3f = BufferUtils.createFloatBuffer(3);
44 | private final FloatBuffer mat3f = BufferUtils.createFloatBuffer(3 * 3);
45 | private final FloatBuffer mat4f = BufferUtils.createFloatBuffer(4 * 4);
46 |
47 | // ---------------------
48 |
49 | private long count = 0;
50 | private double startTime;
51 |
52 | private double
53 | view_rotx = 20.0f,
54 | view_roty = 30.0f,
55 | view_rotz = 0.0f;
56 |
57 | private double distance = 40.0f;
58 | private double angle = 0.0f;
59 |
60 | Gears(Resources resources) {
61 | glDisable(GL_CULL_FACE);
62 | glEnable(GL_DEPTH_TEST);
63 |
64 | P.setFrustum(-1.0, 1.0, -1.0, 1.0, 5.0, 100.0);
65 |
66 | program = loadShaders(resources,
67 | "gears.vert",
68 | "gears.frag"
69 | );
70 |
71 | u_MVP = glGetUniformLocation(program, "u_MVP");
72 | u_NORMAL = glGetUniformLocation(program, "u_NORMAL");
73 | u_LIGHT = glGetUniformLocation(program, "u_LIGHT");
74 | u_COLOR = glGetUniformLocation(program, "u_COLOR");
75 |
76 | gear1 = new Gear(1.0, 4.0, 1.0, 20, 0.7, new float[]{0.8f, 0.1f, 0.0f, 1.0f});
77 | gear2 = new Gear(0.5, 2.0, 2.0, 10, 0.7, new float[]{0.0f, 0.8f, 0.2f, 1.0f});
78 | gear3 = new Gear(1.3, 2.0, 0.5, 10, 0.7, new float[]{0.2f, 0.2f, 1.0f, 1.0f});
79 |
80 | startTime = System.currentTimeMillis() / 1000.0;
81 | }
82 |
83 | void idle() {
84 | angle += 2.0;
85 | }
86 |
87 | void reshape(int width, int height) {
88 | float h = (float) height / (float) width;
89 |
90 | glViewport(0, 0, width, height);
91 | P.setFrustum(-1.0, 1.0, -h, h, 5.0, 100.0);
92 |
93 | distance = width < height ? 40.0 : 80.0;
94 | }
95 |
96 | void draw() {
97 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
98 |
99 | // VIEW
100 | V.translation(0.0, 0.0, -distance);
101 | V.rotateX(view_rotx * PI / 180);
102 | V.rotateY(view_roty * PI / 180);
103 | V.rotateZ(view_rotz * PI / 180);
104 |
105 | // LIGHT
106 | V.transformDirection(light.set(5.0, 5.0, 10.0)).normalize();
107 | vec3f.put(0, (float) light.x);
108 | vec3f.put(1, (float) light.y);
109 | vec3f.put(2, (float) light.z);
110 | glUniform3fv(u_LIGHT, vec3f);
111 |
112 | // GEAR 1
113 | MVP
114 | .translation(-3.0, -2.0, 0.0)
115 | .rotateZ(angle * PI / 180);
116 | drawGear(gear1);
117 |
118 | // GEAR 2
119 | MVP
120 | .translation(3.1, -2.0, 0.0)
121 | .rotateZ((-2.0 * angle - 9.0) * PI / 180);
122 | drawGear(gear2);
123 |
124 | // GEAR 3
125 | MVP
126 | .translation(-3.1, 4.2, 0.0)
127 | .rotateZ((-2.0 * angle - 25.0) * PI / 180);
128 | drawGear(gear3);
129 |
130 | count++;
131 |
132 | double theTime = System.currentTimeMillis() / 1000.0;
133 | if (theTime >= startTime + 1.0) {
134 | System.out.format("%d fps\n", count);
135 | startTime = theTime;
136 | count = 0;
137 | }
138 | }
139 |
140 | private void drawGear(Gear gear) {
141 | V.mul(MVP, MVP);
142 | glUniformMatrix3fv(u_NORMAL, false, MVP.normal(normal).get(mat3f));
143 | P.mul(MVP, MVP);
144 | glUniformMatrix4fv(u_MVP, false, MVP.get(mat4f));
145 | glUniform4fv(u_COLOR, gear.color);
146 |
147 | glBindVertexArray(gear.vao);
148 | glDrawArrays(GL_TRIANGLES, 0, gear.vertexCount);
149 | }
150 |
151 | private static void printShaderInfoLog(int obj) {
152 | int infologLength = glGetShaderi(obj, GL_INFO_LOG_LENGTH);
153 | if (infologLength > 0) {
154 | glGetShaderInfoLog(obj);
155 | System.out.format("%s\n", glGetShaderInfoLog(obj));
156 | }
157 | }
158 |
159 | private static void printProgramInfoLog(int obj) {
160 | int infologLength = glGetProgrami(obj, GL_INFO_LOG_LENGTH);
161 | if (infologLength > 0) {
162 | glGetProgramInfoLog(obj);
163 | System.out.format("%s\n", glGetProgramInfoLog(obj));
164 | }
165 | }
166 |
167 | private static void compileShader(int shader, ByteBuffer code) {
168 | try (MemoryStack stack = stackPush()) {
169 | PointerBuffer pp = stack.mallocPointer(1);
170 | IntBuffer pi = stack.mallocInt(1);
171 |
172 | pp.put(0, code);
173 | pi.put(0, code.remaining());
174 | glShaderSource(shader, pp, pi);
175 | glCompileShader(shader);
176 | printShaderInfoLog(shader);
177 |
178 | if (glGetShaderi(shader, GL_COMPILE_STATUS) != GL_TRUE)
179 | throw new IllegalStateException("Failed to compile shader.");
180 | }
181 | }
182 |
183 | private static int compileShaders(ByteBuffer vs, ByteBuffer fs) {
184 | int v = glCreateShader(GL_VERTEX_SHADER);
185 | int f = glCreateShader(GL_FRAGMENT_SHADER);
186 |
187 | compileShader(v, vs);
188 | compileShader(f, fs);
189 |
190 | int p = glCreateProgram();
191 | glAttachShader(p, v);
192 | glAttachShader(p, f);
193 | glLinkProgram(p);
194 | printProgramInfoLog(p);
195 |
196 | if (glGetProgrami(p, GL_LINK_STATUS) != GL_TRUE)
197 | throw new IllegalStateException("Failed to link program.");
198 |
199 | glUseProgram(p);
200 | return p;
201 | }
202 |
203 | private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
204 | ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
205 | buffer.flip();
206 | newBuffer.put(buffer);
207 | return newBuffer;
208 | }
209 |
210 | private static ByteBuffer readFile(Resources resources, String fileName, int bufferSize) throws IOException {
211 | ByteBuffer buffer;
212 |
213 | try (
214 | InputStream source = resources.getAssets().open(fileName);
215 | ReadableByteChannel rbc = Channels.newChannel(source)
216 | ) {
217 | buffer = BufferUtils.createByteBuffer(bufferSize);
218 |
219 | while (true) {
220 | int bytes = rbc.read(buffer);
221 | if (bytes == -1)
222 | break;
223 | if (buffer.remaining() == 0)
224 | buffer = resizeBuffer(buffer, buffer.capacity() * 2);
225 | }
226 | }
227 |
228 | buffer.flip();
229 | return buffer;
230 | }
231 |
232 | private static int loadShaders(Resources resources, String vertFileName, String fragFileName) {
233 | try {
234 | ByteBuffer vs = readFile(resources, vertFileName, 4096);
235 | ByteBuffer fs = readFile(resources, fragFileName, 4096);
236 |
237 | return compileShaders(vs, fs);
238 | } catch (IOException e) {
239 | throw new RuntimeException(e);
240 | }
241 | }
242 |
243 | private class Gear {
244 |
245 | final FloatBuffer color;
246 |
247 | final int vao;
248 | private int vertexCount;
249 |
250 | private FloatBuffer gVertices;
251 | private FloatBuffer gNormals;
252 |
253 | private double
254 | currentNormalsX,
255 | currentNormalsY,
256 | currentNormalsZ;
257 |
258 | Gear(double inner_radius, double outer_radius, double width, int teeth, double tooth_depth, float[] color) {
259 | this.color = BufferUtils.createFloatBuffer(4);
260 | this.color.put(color).flip();
261 |
262 | gVertices = memAllocFloat(100000 / 4);
263 | gNormals = memAllocFloat(100000 / 4);
264 |
265 | double r0 = inner_radius;
266 | double r1 = outer_radius - tooth_depth / 2.0;
267 | double r2 = outer_radius + tooth_depth / 2.0;
268 |
269 | double da = 2.0 * PI / teeth / 4.0;
270 |
271 | setCurrentNormal(0.0, 0.0, 1.0);
272 |
273 | /* draw front face */
274 | for (int i = 0; i <= teeth; i++) {
275 | double angle = i * 2.0 * PI / teeth;
276 | double da3 = 4 * da;
277 |
278 | // step 1
279 | addVertex(r0 * cos(angle), r0 * sin(angle), width * 0.5);
280 | addVertex(r1 * cos(angle), r1 * sin(angle), width * 0.5);
281 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), width * 0.5);
282 |
283 | addVertex(r0 * cos(angle), r0 * sin(angle), width * 0.5);
284 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), width * 0.5);
285 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
286 |
287 | // Step 2
288 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
289 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), width * 0.5);
290 | addVertex(r1 * cos(angle - da3), r1 * sin(angle - da3), width * 0.5);
291 |
292 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
293 | addVertex(r1 * cos(angle - da3), r1 * sin(angle - da3), width * 0.5);
294 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), width * 0.5);
295 | }
296 |
297 | /* draw front sides of teeth */
298 | da = 2.0 * PI / teeth / 4.0;
299 | for (int i = 0; i < teeth; i++) {
300 | double angle = i * 2.0 * PI / teeth;
301 |
302 | addVertex(r1 * cos(angle), r1 * sin(angle), width * 0.5);
303 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
304 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
305 |
306 | addVertex(r1 * cos(angle), r1 * sin(angle), width * 0.5);
307 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
308 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
309 | }
310 |
311 | setCurrentNormal(0.0, 0.0, -1.0);
312 | double da3 = 4 * da;
313 |
314 | /* draw back face */
315 | for (int i = 0; i <= teeth; i++) {
316 | double angle = i * 2.0 * PI / teeth;
317 |
318 | addVertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
319 | addVertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
320 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
321 |
322 | addVertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
323 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
324 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), -width * 0.5);
325 |
326 |
327 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), -width * 0.5);
328 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
329 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), -width * 0.5);
330 |
331 | addVertex(r1 * cos(angle - da), r1 * sin(angle - da), -width * 0.5);
332 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), -width * 0.5);
333 | addVertex(r1 * cos(angle - da3), r1 * sin(angle - da3), -width * 0.5);
334 | }
335 |
336 | /* draw back sides of teeth */
337 | da = 2.0 * PI / teeth / 4.0;
338 | for (int i = 0; i < teeth; i++) {
339 | double angle = i * 2.0 * PI / teeth;
340 |
341 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
342 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
343 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
344 |
345 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
346 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
347 | addVertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
348 | }
349 |
350 | setCurrentNormal(0.0, 0.0, -1.0); // Copied from above
351 |
352 | /* draw outward faces of teeth */
353 | for (int i = 0; i < teeth; i++) {
354 | double angle = i * 2.0 * PI / teeth;
355 |
356 | setCurrentNormal(cos(angle), sin(angle), 0.0);
357 | double u = r2 * cos(angle + da) - r1 * cos(angle);
358 | double v = r2 * sin(angle + da) - r1 * sin(angle);
359 | double len = sqrt(u * u + v * v);
360 | u /= len;
361 | v /= len;
362 |
363 | // First quad
364 | addVertex(r1 * cos(angle), r1 * sin(angle), width * 0.5);
365 | addVertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5);
366 | setCurrentNormal(v, -u, 0.0);
367 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
368 |
369 | setCurrentNormal(cos(angle), sin(angle), 0.0);
370 | addVertex(r1 * cos(angle), r1 * sin(angle), width * 0.5);
371 | setCurrentNormal(v, -u, 0.0);
372 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
373 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
374 |
375 | // Second quad
376 | setCurrentNormal(v, -u, 0.0);
377 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
378 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5);
379 | setCurrentNormal(cos(angle), sin(angle), 0.0);
380 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
381 |
382 | setCurrentNormal(v, -u, 0.0);
383 | addVertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5);
384 | setCurrentNormal(cos(angle), sin(angle), 0.0);
385 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
386 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
387 |
388 | // Third quad
389 | setCurrentNormal(cos(angle), sin(angle), 0.0);
390 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
391 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5);
392 | u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da);
393 | v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da);
394 | setCurrentNormal(v, -u, 0.0);
395 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
396 |
397 | setCurrentNormal(cos(angle), sin(angle), 0.0);
398 | addVertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5);
399 | setCurrentNormal(v, -u, 0.0);
400 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
401 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
402 |
403 | // Fourth quad
404 | u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da);
405 | v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da);
406 | setCurrentNormal(v, -u, 0.0);
407 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
408 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5);
409 | setCurrentNormal(cos(angle), sin(angle), 0.0);
410 | setCurrentNormal(cos(angle + 4 * da), sin(angle + 4 * da), 0.0);
411 | addVertex(r1 * cos(angle + 4 * da), r1 * sin(angle + 4 * da), -width * 0.5);
412 |
413 | u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da);
414 | v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da);
415 | setCurrentNormal(v, -u, 0.0);
416 | addVertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5);
417 | setCurrentNormal(cos(angle), sin(angle), 0.0);
418 | setCurrentNormal(cos(angle + 4 * da), sin(angle + 4 * da), 0.0);
419 | addVertex(r1 * cos(angle + 4 * da), r1 * sin(angle + 4 * da), width * 0.5);
420 | addVertex(r1 * cos(angle + 4 * da), r1 * sin(angle + 4 * da), -width * 0.5);
421 |
422 | }
423 |
424 | /* draw inside radius cylinder */
425 | da3 = 4 * da;
426 | for (int i = 0; i <= teeth; i++) {
427 | double angle = i * 2.0 * PI / teeth;
428 |
429 | setCurrentNormal(-cos(angle), -sin(angle), 0.0);
430 | addVertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
431 | addVertex(r0 * cos(angle), r0 * sin(angle), width * 0.5);
432 | setCurrentNormal(-cos(angle - da), -sin(angle - da), 0.0);
433 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
434 |
435 | setCurrentNormal(-cos(angle), -sin(angle), 0.0);
436 | addVertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5);
437 | setCurrentNormal(-cos(angle - da), -sin(angle - da), 0.0);
438 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
439 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
440 |
441 |
442 | setCurrentNormal(-cos(angle - da), -sin(angle - da), 0.0);
443 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
444 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), width * 0.5);
445 | setCurrentNormal(-cos(angle - da3), -sin(angle - da3), 0.0);
446 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), width * 0.5);
447 |
448 | setCurrentNormal(-cos(angle - da), -sin(angle - da), 0.0);
449 | addVertex(r0 * cos(angle - da), r0 * sin(angle - da), -width * 0.5);
450 | setCurrentNormal(-cos(angle - da3), -sin(angle - da3), 0.0);
451 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), width * 0.5);
452 | addVertex(r0 * cos(angle - da3), r0 * sin(angle - da3), -width * 0.5);
453 | }
454 |
455 | // Build VAO and VBOs
456 | // Allocate and activate Vertex Array Object
457 | vao = glGenVertexArrays();
458 | glBindVertexArray(vao);
459 | // Allocate Vertex Buffer Objects
460 | int vertexBufferObjID = glGenBuffers();
461 | int normalsBufferObjID = glGenBuffers();
462 |
463 | // VBO for vertex data
464 | gVertices.limit(vertexCount * 3);
465 |
466 | glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID);
467 | glBufferData(GL_ARRAY_BUFFER, gVertices, GL_STATIC_DRAW);
468 | glVertexAttribPointer(glGetAttribLocation(program, "in_Position"), 3, GL_FLOAT, false, 0, 0);
469 | glEnableVertexAttribArray(glGetAttribLocation(program, "in_Position"));
470 |
471 | // VBO for normals data
472 | gNormals.limit(vertexCount * 3);
473 |
474 | glBindBuffer(GL_ARRAY_BUFFER, normalsBufferObjID);
475 | glBufferData(GL_ARRAY_BUFFER, gNormals, GL_STATIC_DRAW);
476 | glVertexAttribPointer(glGetAttribLocation(program, "in_Normal"), 3, GL_FLOAT, false, 0, 0);
477 | glEnableVertexAttribArray(glGetAttribLocation(program, "in_Normal"));
478 |
479 | memFree(gVertices);
480 | memFree(gNormals);
481 | }
482 |
483 | private void addVertex(double x, double y, double z) {
484 | gVertices.put(vertexCount * 3, (float) x);
485 | gVertices.put(vertexCount * 3 + 1, (float) y);
486 | gVertices.put(vertexCount * 3 + 2, (float) z);
487 | gNormals.put(vertexCount * 3, (float) currentNormalsX);
488 | gNormals.put(vertexCount * 3 + 1, (float) currentNormalsY);
489 | gNormals.put(vertexCount * 3 + 2, (float) currentNormalsZ);
490 | vertexCount += 1;
491 | }
492 |
493 | private void setCurrentNormal(double x, double y, double z) {
494 | currentNormalsX = x;
495 | currentNormalsY = y;
496 | currentNormalsZ = z;
497 | }
498 |
499 | }
500 |
501 | }
--------------------------------------------------------------------------------
/hellovulkan/src/main/java/org/lwjgl/demo/android/hellovulkan/HelloVulkan.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright LWJGL. All rights reserved.
3 | * License terms: https://www.lwjgl.org/license
4 | */
5 | package org.lwjgl.demo.android.hellovulkan;
6 |
7 | import org.lwjgl.*;
8 | import org.lwjgl.system.*;
9 | import org.lwjgl.vulkan.*;
10 |
11 | import java.nio.*;
12 |
13 | import static org.lwjgl.system.MemoryStack.*;
14 | import static org.lwjgl.system.MemoryUtil.*;
15 | import static org.lwjgl.vulkan.EXTDebugReport.*;
16 | import static org.lwjgl.vulkan.KHRAndroidSurface.*;
17 | import static org.lwjgl.vulkan.KHRSurface.*;
18 | import static org.lwjgl.vulkan.KHRSwapchain.*;
19 | import static org.lwjgl.vulkan.VK10.*;
20 |
21 | /*
22 | * Copyright (c) 2015-2016 The Khronos Group Inc.
23 | * Copyright (c) 2015-2016 Valve Corporation
24 | * Copyright (c) 2015-2016 LunarG, Inc.
25 | *
26 | * Licensed under the Apache License, Version 2.0 (the "License");
27 | * you may not use this file except in compliance with the License.
28 | * You may obtain a copy of the License at
29 | *
30 | * http://www.apache.org/licenses/LICENSE-2.0
31 | *
32 | * Unless required by applicable law or agreed to in writing, software
33 | * distributed under the License is distributed on an "AS IS" BASIS,
34 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 | * See the License for the specific language governing permissions and
36 | * limitations under the License.
37 | *
38 | * Author: Chia-I Wu
39 | * Author: Cody Northrop
40 | * Author: Courtney Goeltzenleuchter
41 | * Author: Ian Elliott
42 | * Author: Jon Ashburn
43 | * Author: Piers Daniell
44 | * Author: Gwan-gyeong Mun
45 | * Porter: Camilla Berglund
46 | */
47 |
48 | /**
49 | * Simple Vulkan demo. Ported from the GLFW vulkan test.
50 | */
51 | final class HelloVulkan {
52 |
53 | private static final boolean VALIDATE = false;
54 |
55 | private static final boolean USE_STAGING_BUFFER = false;
56 |
57 | private static final int DEMO_TEXTURE_COUNT = 1;
58 | private static final int VERTEX_BUFFER_BIND_ID = 0;
59 |
60 | private static final ByteBuffer KHR_surface = memASCII(VK_KHR_SURFACE_EXTENSION_NAME);
61 | private static final ByteBuffer KHR_android_surface = memASCII(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
62 |
63 | private static final ByteBuffer KHR_swapchain = memASCII(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
64 | private static final ByteBuffer EXT_debug_report = memASCII(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
65 |
66 | private static final byte[] fragShaderCode = {
67 | 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00,
68 | 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
69 | 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
70 | 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
71 | 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
72 | 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00,
73 | 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
74 | 0x09, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00,
75 | 0x04, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00,
76 | 0x02, 0x00, 0x00, 0x00, (byte) 0x90, 0x01, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00,
77 | 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x65, 0x70, 0x61, 0x72,
78 | 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6f,
79 | 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00,
80 | 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x69,
81 | 0x6e, 0x67, 0x5f, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f,
82 | 0x34, 0x32, 0x30, 0x70, 0x61, 0x63, 0x6b, 0x00, 0x05, 0x00, 0x04, 0x00,
83 | 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
84 | 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x75, 0x46, 0x72, 0x61,
85 | 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
86 | 0x0d, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x00, 0x05, 0x00, 0x05, 0x00,
87 | 0x11, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64,
88 | 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00,
89 | 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
90 | 0x0d, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
91 | 0x47, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
92 | 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x11, 0x00, 0x00, 0x00,
93 | 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00,
94 | 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00,
95 | 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00,
96 | 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
97 | 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
98 | 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
99 | 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
100 | 0x03, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x0a, 0x00, 0x00, 0x00,
101 | 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
102 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
103 | 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x0b, 0x00, 0x00, 0x00,
104 | 0x0a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00,
105 | 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
106 | 0x0c, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
107 | 0x17, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
108 | 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00,
109 | 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
110 | 0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
111 | 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
112 | 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, (byte) 0xf8, 0x00, 0x02, 0x00,
113 | 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00,
114 | 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
115 | 0x0f, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
116 | 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
117 | 0x0e, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
118 | 0x09, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, (byte) 0xfd, 0x00, 0x01, 0x00,
119 | 0x38, 0x00, 0x01, 0x00
120 | };
121 |
122 | private static final byte[] vertShaderCode = {
123 | 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00,
124 | 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
125 | 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
126 | 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
127 | 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
128 | 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00,
129 | 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
130 | 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
131 | 0x17, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00,
132 | 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, (byte) 0x90, 0x01, 0x00, 0x00,
133 | 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73,
134 | 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64,
135 | 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00,
136 | 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73,
137 | 0x68, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x6c, 0x61, 0x6e, 0x67, 0x75,
138 | 0x61, 0x67, 0x65, 0x5f, 0x34, 0x32, 0x30, 0x70, 0x61, 0x63, 0x6b, 0x00,
139 | 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e,
140 | 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00,
141 | 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x00, 0x00, 0x00, 0x00,
142 | 0x05, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x61, 0x74, 0x74, 0x72,
143 | 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x11, 0x00, 0x00, 0x00,
144 | 0x67, 0x6c, 0x5f, 0x50, 0x65, 0x72, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78,
145 | 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x11, 0x00, 0x00, 0x00,
146 | 0x00, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74,
147 | 0x69, 0x6f, 0x6e, 0x00, 0x06, 0x00, 0x07, 0x00, 0x11, 0x00, 0x00, 0x00,
148 | 0x01, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x69, 0x6e, 0x74,
149 | 0x53, 0x69, 0x7a, 0x65, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x07, 0x00,
150 | 0x11, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x43,
151 | 0x6c, 0x69, 0x70, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x00,
152 | 0x05, 0x00, 0x03, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
153 | 0x05, 0x00, 0x03, 0x00, 0x17, 0x00, 0x00, 0x00, 0x70, 0x6f, 0x73, 0x00,
154 | 0x05, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x56,
155 | 0x65, 0x72, 0x74, 0x65, 0x78, 0x49, 0x44, 0x00, 0x05, 0x00, 0x06, 0x00,
156 | 0x1d, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x49, 0x6e, 0x73, 0x74, 0x61,
157 | 0x6e, 0x63, 0x65, 0x49, 0x44, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
158 | 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
159 | 0x47, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00,
160 | 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00, 0x00,
161 | 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
162 | 0x48, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
163 | 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00,
164 | 0x11, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
165 | 0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x11, 0x00, 0x00, 0x00,
166 | 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00,
167 | 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
168 | 0x1c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00,
169 | 0x47, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
170 | 0x06, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00,
171 | 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
172 | 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
173 | 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
174 | 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00,
175 | 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
176 | 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
177 | 0x20, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
178 | 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00,
179 | 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00,
180 | 0x0d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
181 | 0x15, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
182 | 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00,
183 | 0x0f, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x04, 0x00,
184 | 0x10, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
185 | 0x1e, 0x00, 0x05, 0x00, 0x11, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
186 | 0x06, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
187 | 0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
188 | 0x3b, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00,
189 | 0x03, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00,
190 | 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
191 | 0x14, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
192 | 0x20, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
193 | 0x0d, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x16, 0x00, 0x00, 0x00,
194 | 0x17, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
195 | 0x19, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
196 | 0x20, 0x00, 0x04, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
197 | 0x14, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x1b, 0x00, 0x00, 0x00,
198 | 0x1c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
199 | 0x1b, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
200 | 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
201 | 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, (byte) 0xf8, 0x00, 0x02, 0x00,
202 | 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
203 | 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
204 | 0x09, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
205 | 0x0d, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00,
206 | 0x41, 0x00, 0x05, 0x00, 0x19, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00,
207 | 0x13, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
208 | 0x1a, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, (byte) 0xfd, 0x00, 0x01, 0x00,
209 | 0x38, 0x00, 0x01, 0x00
210 | };
211 |
212 | // buffers for handle output-params
213 | private final IntBuffer ip = memAllocInt(1);
214 | private final LongBuffer lp = memAllocLong(1);
215 | private final PointerBuffer pp = memAllocPointer(1);
216 |
217 | private PointerBuffer extension_names = memAllocPointer(64);
218 |
219 | private VkInstance inst;
220 | private VkPhysicalDevice gpu;
221 |
222 | private long msg_callback;
223 |
224 | private VkPhysicalDeviceProperties gpu_props = VkPhysicalDeviceProperties.malloc();
225 | private VkPhysicalDeviceFeatures gpu_features = VkPhysicalDeviceFeatures.malloc();
226 |
227 | private VkQueueFamilyProperties.Buffer queue_props;
228 |
229 | private int width = 300;
230 | private int height = 300;
231 | private float depthStencil = 1.0f;
232 | private float depthIncrement = -0.01f;
233 |
234 | private long surface;
235 |
236 | private int graphics_queue_node_index;
237 |
238 | private VkDevice device;
239 | private VkQueue queue;
240 |
241 | private int format;
242 | private int color_space;
243 |
244 | private VkPhysicalDeviceMemoryProperties memory_properties = VkPhysicalDeviceMemoryProperties.malloc();
245 |
246 | private long cmd_pool;
247 | private VkCommandBuffer draw_cmd;
248 |
249 | private long swapchain;
250 | private int swapchainImageCount;
251 | private SwapchainBuffers[] buffers;
252 | private int current_buffer;
253 |
254 | private VkCommandBuffer setup_cmd;
255 |
256 | private Depth depth = new Depth();
257 |
258 | private TextureObject[] textures = new TextureObject[DEMO_TEXTURE_COUNT];
259 |
260 | private Vertices vertices = new Vertices();
261 |
262 | private long desc_layout;
263 | private long pipeline_layout;
264 |
265 | private long render_pass;
266 |
267 | private long pipeline;
268 |
269 | private long desc_pool;
270 | private long desc_set;
271 |
272 | private LongBuffer framebuffers;
273 |
274 | HelloVulkan(long nativeWindow) {
275 | for (int i = 0; i < textures.length; i++) {
276 | textures[i] = new TextureObject();
277 | }
278 |
279 | demo_init_vk();
280 |
281 | try (MemoryStack stack = stackPush()) {
282 | // Create a WSI surface for the window:
283 | //glfwCreateWindowSurface(inst, window, null, lp);
284 | VkAndroidSurfaceCreateInfoKHR createInfo = VkAndroidSurfaceCreateInfoKHR.mallocStack(stack)
285 | .sType(VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR)
286 | .pNext(NULL)
287 | .flags(0)
288 | .window(nativeWindow);
289 | check(vkCreateAndroidSurfaceKHR(inst, createInfo, null, lp));
290 | surface = lp.get(0);
291 | }
292 | }
293 |
294 | private final VkDebugReportCallbackEXT dbgFunc = new VkDebugReportCallbackEXT() {
295 | @Override
296 | public int invoke(int flags, int objectType, long object, long location, int messageCode, long pLayerPrefix, long pMessage, long pUserData) {
297 | String type;
298 | if ((flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) != 0) {
299 | type = "INFORMATION";
300 | } else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0) {
301 | type = "WARNING";
302 | } else if ((flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) != 0) {
303 | type = "PERFORMANCE WARNING";
304 | } else if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0) {
305 | type = "ERROR";
306 | } else if ((flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) != 0) {
307 | type = "DEBUG";
308 | } else
309 | type = "UNKNOWN";
310 |
311 | System.err.format(
312 | "%s: [%s] Code %d : %s\n",
313 | type, memASCII(pLayerPrefix), messageCode, VkDebugReportCallbackEXT.getString(pMessage)
314 | );
315 |
316 | /*
317 | * false indicates that layer should not bail-out of an
318 | * API call that had validation failures. This may mean that the
319 | * app dies inside the driver due to invalid parameter(s).
320 | * That's what would happen without validation layers, so we'll
321 | * keep that behavior here.
322 | */
323 | return VK_FALSE;
324 | }
325 | };
326 |
327 | private static void check(int errcode) {
328 | if (errcode != 0)
329 | throw new IllegalStateException(String.format("Vulkan error [%d]", errcode));
330 | }
331 |
332 | /**
333 | * Return true if all layer names specified in {@code check_names} can be found in given {@code layer} properties.
334 | */
335 | private static boolean demo_check_layers(PointerBuffer check_names, VkLayerProperties.Buffer layers) {
336 | for (int i = 0; i < check_names.remaining(); i++) {
337 | boolean found = false;
338 |
339 | for (int j = 0; j < layers.capacity(); j++) {
340 | layers.position(j);
341 | if (check_names.getStringASCII(i).equals(layers.layerNameString())) {
342 | found = true;
343 | break;
344 | }
345 | }
346 |
347 | if (!found) {
348 | System.err.format("Cannot find layer: %s\n", check_names.getStringASCII(i));
349 | return false;
350 | }
351 | }
352 |
353 | return true;
354 | }
355 |
356 | private void demo_init_vk() {
357 | String[] instance_validation_layers_alt1 = {
358 | "VK_LAYER_LUNARG_standard_validation"
359 | };
360 |
361 | String[] instance_validation_layers_alt2 = {
362 | "VK_LAYER_GOOGLE_threading", "VK_LAYER_LUNARG_parameter_validation",
363 | "VK_LAYER_LUNARG_object_tracker", "VK_LAYER_LUNARG_image",
364 | "VK_LAYER_LUNARG_core_validation", "VK_LAYER_LUNARG_swapchain",
365 | "VK_LAYER_GOOGLE_unique_objects"
366 | };
367 |
368 | PointerBuffer instance_validation_layers = null;
369 | try (MemoryStack stack = stackPush()) {
370 | boolean validation_found = false;
371 | if (VALIDATE) {
372 | check(vkEnumerateInstanceLayerProperties(ip, null));
373 |
374 | if (ip.get(0) > 0) {
375 | VkLayerProperties.Buffer instance_layers = VkLayerProperties.mallocStack(ip.get(0), stack);
376 | check(vkEnumerateInstanceLayerProperties(ip, instance_layers));
377 |
378 | instance_validation_layers = stack.mallocPointer(instance_validation_layers_alt1.length);
379 | for (int i = 0; i < instance_validation_layers_alt1.length; i++) {
380 | instance_validation_layers.put(i, stack.ASCII(instance_validation_layers_alt1[i]));
381 | }
382 |
383 | validation_found = demo_check_layers(instance_validation_layers, instance_layers);
384 |
385 | if (!validation_found) {
386 | // use alternative set of validation layers
387 | instance_validation_layers = stack.mallocPointer(instance_validation_layers_alt2.length);
388 | for (int i = 0; i < instance_validation_layers_alt2.length; i++) {
389 | instance_validation_layers.put(i, stack.ASCII(instance_validation_layers_alt2[i]));
390 | }
391 |
392 | validation_found = demo_check_layers(instance_validation_layers, instance_layers);
393 | }
394 | }
395 |
396 | if (!validation_found) {
397 | throw new IllegalStateException("vkEnumerateInstanceLayerProperties failed to find required validation layer.");
398 | }
399 | }
400 |
401 | extension_names.put(KHR_surface);
402 | extension_names.put(KHR_android_surface);
403 |
404 | check(vkEnumerateInstanceExtensionProperties((String) null, ip, null));
405 |
406 | if (ip.get(0) != 0) {
407 | VkExtensionProperties.Buffer instance_extensions = VkExtensionProperties.mallocStack(ip.get(0), stack);
408 | check(vkEnumerateInstanceExtensionProperties((String) null, ip, instance_extensions));
409 |
410 | for (int i = 0; i < ip.get(0); i++) {
411 | instance_extensions.position(i);
412 | if (VK_EXT_DEBUG_REPORT_EXTENSION_NAME.equals(instance_extensions.extensionNameString())) {
413 | if (VALIDATE) {
414 | extension_names.put(EXT_debug_report);
415 | }
416 | }
417 | }
418 | }
419 |
420 | ByteBuffer APP_SHORT_NAME = stack.UTF8("tri");
421 |
422 | VkApplicationInfo app = VkApplicationInfo.callocStack(stack)
423 | .sType(VK_STRUCTURE_TYPE_APPLICATION_INFO)
424 | .pNext(NULL)
425 | .pApplicationName(APP_SHORT_NAME)
426 | .applicationVersion(1)
427 | .pEngineName(APP_SHORT_NAME)
428 | .engineVersion(1)
429 | .apiVersion(VK_API_VERSION_1_0);
430 |
431 | extension_names.flip();
432 | VkInstanceCreateInfo inst_info = VkInstanceCreateInfo.callocStack(stack)
433 | .sType(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO)
434 | .pNext(NULL)
435 | .flags(0)
436 | .pApplicationInfo(app)
437 | .ppEnabledLayerNames(instance_validation_layers)
438 | .ppEnabledExtensionNames(extension_names);
439 | extension_names.clear();
440 |
441 | VkDebugReportCallbackCreateInfoEXT dbgCreateInfo;
442 | if (VALIDATE) {
443 | dbgCreateInfo = VkDebugReportCallbackCreateInfoEXT.callocStack(stack)
444 | .sType(VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT)
445 | .pNext(NULL)
446 | .flags(VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT)
447 | .pfnCallback(dbgFunc)
448 | .pUserData(NULL);
449 |
450 | inst_info.pNext(dbgCreateInfo.address());
451 | }
452 |
453 | int err = vkCreateInstance(inst_info, null, pp);
454 | if (err == VK_ERROR_INCOMPATIBLE_DRIVER)
455 | throw new IllegalStateException("Cannot find a compatible Vulkan installable client driver (ICD).");
456 | else if (err == VK_ERROR_EXTENSION_NOT_PRESENT)
457 | throw new IllegalStateException("Cannot find a specified extension library. Make sure your layers path is set appropriately.");
458 | else if (err != 0)
459 | throw new IllegalStateException("vkCreateInstance failed. Do you have a compatible Vulkan installable client driver (ICD) installed?");
460 |
461 | inst = new VkInstance(pp.get(0), inst_info);
462 |
463 | /* Make initial call to query gpu_count, then second call for gpu info */
464 | check(vkEnumeratePhysicalDevices(inst, ip, null));
465 |
466 | if (ip.get(0) > 0) {
467 | PointerBuffer physical_devices = stack.mallocPointer(ip.get(0));
468 | check(vkEnumeratePhysicalDevices(inst, ip, physical_devices));
469 |
470 | /* For tri demo we just grab the first physical device */
471 | gpu = new VkPhysicalDevice(physical_devices.get(0), inst);
472 | } else {
473 | throw new IllegalStateException("vkEnumeratePhysicalDevices reported zero accessible devices.");
474 | }
475 |
476 | /* Look for device extensions */
477 | boolean swapchainExtFound = false;
478 | check(vkEnumerateDeviceExtensionProperties(gpu, (String) null, ip, null));
479 |
480 | if (ip.get(0) > 0) {
481 | VkExtensionProperties.Buffer device_extensions = VkExtensionProperties.mallocStack(ip.get(0), stack);
482 | check(vkEnumerateDeviceExtensionProperties(gpu, (String) null, ip, device_extensions));
483 |
484 | for (int i = 0; i < ip.get(0); i++) {
485 | device_extensions.position(i);
486 | if (VK_KHR_SWAPCHAIN_EXTENSION_NAME.equals(device_extensions.extensionNameString())) {
487 | swapchainExtFound = true;
488 | extension_names.put(KHR_swapchain);
489 | }
490 | }
491 | }
492 |
493 | if (!swapchainExtFound)
494 | throw new IllegalStateException("vkEnumerateDeviceExtensionProperties failed to find the " + VK_KHR_SWAPCHAIN_EXTENSION_NAME + " extension.");
495 |
496 | if (VALIDATE) {
497 | err = vkCreateDebugReportCallbackEXT(inst, dbgCreateInfo, null, lp);
498 | switch (err) {
499 | case VK_SUCCESS:
500 | msg_callback = lp.get(0);
501 | break;
502 | case VK_ERROR_OUT_OF_HOST_MEMORY:
503 | throw new IllegalStateException("CreateDebugReportCallback: out of host memory");
504 | default:
505 | throw new IllegalStateException("CreateDebugReportCallback: unknown failure");
506 | }
507 | }
508 |
509 | vkGetPhysicalDeviceProperties(gpu, gpu_props);
510 |
511 | // Query with NULL data to get count
512 | vkGetPhysicalDeviceQueueFamilyProperties(gpu, ip, null);
513 |
514 | queue_props = VkQueueFamilyProperties.malloc(ip.get(0));
515 | vkGetPhysicalDeviceQueueFamilyProperties(gpu, ip, queue_props);
516 | if (ip.get(0) == 0)
517 | throw new IllegalStateException();
518 |
519 | vkGetPhysicalDeviceFeatures(gpu, gpu_features);
520 |
521 | // Graphics queue and MemMgr queue can be separate.
522 | // TODO: Add support for separate queues, including synchronization,
523 | // and appropriate tracking for QueueSubmit
524 | }
525 | }
526 |
527 | void framebufferSizeChanged(int width, int height) {
528 | this.width = width;
529 | this.height = height;
530 |
531 | if (width != 0 && height != 0)
532 | demo_resize();
533 | }
534 |
535 | private void demo_init_device() {
536 | try (MemoryStack stack = stackPush()) {
537 | VkDeviceQueueCreateInfo.Buffer queue = VkDeviceQueueCreateInfo.mallocStack(1, stack)
538 | .sType(VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO)
539 | .pNext(NULL)
540 | .flags(0)
541 | .queueFamilyIndex(graphics_queue_node_index)
542 | .pQueuePriorities(stack.floats(0.0f));
543 |
544 | VkPhysicalDeviceFeatures features = VkPhysicalDeviceFeatures.callocStack(stack);
545 | if (gpu_features.shaderClipDistance()) {
546 | features.shaderClipDistance(true);
547 | }
548 |
549 | extension_names.flip();
550 | VkDeviceCreateInfo device = VkDeviceCreateInfo.mallocStack(stack)
551 | .sType(VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO)
552 | .pNext(NULL)
553 | .flags(0)
554 | .pQueueCreateInfos(queue)
555 | .ppEnabledLayerNames(null)
556 | .ppEnabledExtensionNames(extension_names)
557 | .pEnabledFeatures(features);
558 |
559 | check(vkCreateDevice(gpu, device, null, pp));
560 |
561 | this.device = new VkDevice(pp.get(0), gpu, device);
562 | }
563 | }
564 |
565 | void initSurface() {
566 | demo_init_vk_swapchain();
567 | demo_prepare();
568 | }
569 |
570 | private void demo_init_vk_swapchain() {
571 | try (MemoryStack stack = stackPush()) {
572 | // Iterate over each queue to learn whether it supports presenting:
573 | IntBuffer supportsPresent = stack.mallocInt(queue_props.capacity());
574 | int graphicsQueueNodeIndex;
575 | int presentQueueNodeIndex;
576 | for (int i = 0; i < supportsPresent.capacity(); i++) {
577 | supportsPresent.position(i);
578 | vkGetPhysicalDeviceSurfaceSupportKHR(gpu, i, surface, supportsPresent);
579 | }
580 |
581 | // Search for a graphics and a present queue in the array of queue
582 | // families, try to find one that supports both
583 | graphicsQueueNodeIndex = Integer.MAX_VALUE;
584 | presentQueueNodeIndex = Integer.MAX_VALUE;
585 | for (int i = 0; i < supportsPresent.capacity(); i++) {
586 | if ((queue_props.get(i).queueFlags() & VK_QUEUE_GRAPHICS_BIT) != 0) {
587 | if (graphicsQueueNodeIndex == Integer.MAX_VALUE) {
588 | graphicsQueueNodeIndex = i;
589 | }
590 |
591 | if (supportsPresent.get(i) == VK_TRUE) {
592 | graphicsQueueNodeIndex = i;
593 | presentQueueNodeIndex = i;
594 | break;
595 | }
596 | }
597 | }
598 | if (presentQueueNodeIndex == Integer.MAX_VALUE) {
599 | // If didn't find a queue that supports both graphics and present, then
600 | // find a separate present queue.
601 | for (int i = 0; i < supportsPresent.capacity(); ++i) {
602 | if (supportsPresent.get(i) == VK_TRUE) {
603 | presentQueueNodeIndex = i;
604 | break;
605 | }
606 | }
607 | }
608 |
609 | // Generate error if could not find both a graphics and a present queue
610 | if (graphicsQueueNodeIndex == Integer.MAX_VALUE || presentQueueNodeIndex == Integer.MAX_VALUE) {
611 | throw new IllegalStateException("Could not find a graphics and a present queue");
612 | }
613 |
614 | // TODO: Add support for separate queues, including presentation,
615 | // synchronization, and appropriate tracking for QueueSubmit.
616 | // NOTE: While it is possible for an application to use a separate graphics
617 | // and a present queues, this demo program assumes it is only using
618 | // one:
619 | if (graphicsQueueNodeIndex != presentQueueNodeIndex) {
620 | throw new IllegalStateException("Could not find a common graphics and a present queue");
621 | }
622 |
623 | graphics_queue_node_index = graphicsQueueNodeIndex;
624 |
625 | demo_init_device();
626 |
627 | vkGetDeviceQueue(device, graphics_queue_node_index, 0, pp);
628 | queue = new VkQueue(pp.get(0), device);
629 |
630 | // Get the list of VkFormat's that are supported:
631 | check(vkGetPhysicalDeviceSurfaceFormatsKHR(gpu, surface, ip, null));
632 |
633 | VkSurfaceFormatKHR.Buffer surfFormats = VkSurfaceFormatKHR.mallocStack(ip.get(0), stack);
634 | check(vkGetPhysicalDeviceSurfaceFormatsKHR(gpu, surface, ip, surfFormats));
635 |
636 | // If the format list includes just one entry of VK_FORMAT_UNDEFINED,
637 | // the surface has no preferred format. Otherwise, at least one
638 | // supported format will be returned.
639 | if (ip.get(0) == 1 && surfFormats.get(0).format() == VK_FORMAT_UNDEFINED) {
640 | format = VK_FORMAT_B8G8R8A8_UNORM;
641 | } else {
642 | assert ip.get(0) >= 1;
643 | format = surfFormats.get(0).format();
644 | }
645 | color_space = surfFormats.get(0).colorSpace();
646 |
647 | // Get Memory information and properties
648 | vkGetPhysicalDeviceMemoryProperties(gpu, memory_properties);
649 | }
650 | }
651 |
652 | private static class SwapchainBuffers {
653 | long image;
654 | VkCommandBuffer cmd;
655 | long view;
656 | }
657 |
658 | private void demo_set_image_layout(long image, int aspectMask, int old_image_layout, int new_image_layout, int srcAccessMask) {
659 | try (MemoryStack stack = stackPush()) {
660 | if (setup_cmd == null) {
661 | VkCommandBufferAllocateInfo cmd = VkCommandBufferAllocateInfo.mallocStack(stack)
662 | .sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO)
663 | .pNext(NULL)
664 | .commandPool(cmd_pool)
665 | .level(VK_COMMAND_BUFFER_LEVEL_PRIMARY)
666 | .commandBufferCount(1);
667 |
668 | check(vkAllocateCommandBuffers(device, cmd, pp));
669 | setup_cmd = new VkCommandBuffer(pp.get(0), device);
670 |
671 | VkCommandBufferBeginInfo cmd_buf_info = VkCommandBufferBeginInfo.mallocStack(stack)
672 | .sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO)
673 | .pNext(NULL)
674 | .flags(0)
675 | .pInheritanceInfo(null);
676 | check(vkBeginCommandBuffer(setup_cmd, cmd_buf_info));
677 | }
678 |
679 | VkImageMemoryBarrier.Buffer image_memory_barrier = VkImageMemoryBarrier.mallocStack(1, stack)
680 | .sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
681 | .pNext(NULL)
682 | .srcAccessMask(srcAccessMask)
683 | .dstAccessMask(0)
684 | .oldLayout(old_image_layout)
685 | .newLayout(new_image_layout)
686 | .srcQueueFamilyIndex(0)
687 | .dstQueueFamilyIndex(0)
688 | .image(image);
689 |
690 | image_memory_barrier.subresourceRange()
691 | .aspectMask(aspectMask)
692 | .baseMipLevel(0)
693 | .levelCount(1)
694 | .baseArrayLayer(0)
695 | .layerCount(1);
696 |
697 | switch (new_image_layout) {
698 | case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
699 | image_memory_barrier.dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT);
700 | break;
701 | case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
702 | image_memory_barrier.dstAccessMask(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT);
703 | break;
704 | case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:
705 | /* Make sure any Copy or CPU writes to image are flushed */
706 | image_memory_barrier.dstAccessMask(VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT);
707 | break;
708 | case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
709 | image_memory_barrier.srcAccessMask(VK_ACCESS_MEMORY_READ_BIT);
710 | /* Make sure anything that was copying from this image has completed */
711 | image_memory_barrier.dstAccessMask(VK_ACCESS_TRANSFER_READ_BIT);
712 | break;
713 | case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
714 | image_memory_barrier.dstAccessMask(VK_ACCESS_MEMORY_READ_BIT);
715 | break;
716 | }
717 |
718 | int src_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
719 | int dest_stages = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
720 |
721 | vkCmdPipelineBarrier(setup_cmd, src_stages, dest_stages, 0, null, null, image_memory_barrier);
722 | }
723 | }
724 |
725 | private void demo_prepare_buffers() {
726 | long oldSwapchain = swapchain;
727 |
728 | try (MemoryStack stack = stackPush()) {
729 | // Check the surface capabilities and formats
730 | VkSurfaceCapabilitiesKHR surfCapabilities = VkSurfaceCapabilitiesKHR.mallocStack(stack);
731 | check(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpu, surface, surfCapabilities));
732 |
733 | check(vkGetPhysicalDeviceSurfacePresentModesKHR(gpu, surface, ip, null));
734 |
735 | IntBuffer presentModes = stack.mallocInt(ip.get(0));
736 | check(vkGetPhysicalDeviceSurfacePresentModesKHR(gpu, surface, ip, presentModes));
737 |
738 | VkExtent2D swapchainExtent = VkExtent2D.mallocStack(stack);
739 | // width and height are either both 0xFFFFFFFF, or both not 0xFFFFFFFF.
740 | if (surfCapabilities.currentExtent().width() == 0xFFFFFFFF) {
741 | // If the surface size is undefined, the size is set to the size
742 | // of the images requested, which must fit within the minimum and
743 | // maximum values.
744 | swapchainExtent.width(width);
745 | swapchainExtent.height(height);
746 |
747 | if (swapchainExtent.width() < surfCapabilities.minImageExtent().width()) {
748 | swapchainExtent.width(surfCapabilities.minImageExtent().width());
749 | } else if (swapchainExtent.width() > surfCapabilities.maxImageExtent().width()) {
750 | swapchainExtent.width(surfCapabilities.maxImageExtent().width());
751 | }
752 |
753 | if (swapchainExtent.height() < surfCapabilities.minImageExtent().height()) {
754 | swapchainExtent.height(surfCapabilities.minImageExtent().height());
755 | } else if (swapchainExtent.height() > surfCapabilities.maxImageExtent().height()) {
756 | swapchainExtent.height(surfCapabilities.maxImageExtent().height());
757 | }
758 | } else {
759 | // If the surface size is defined, the swap chain size must match
760 | swapchainExtent.set(surfCapabilities.currentExtent());
761 | width = surfCapabilities.currentExtent().width();
762 | height = surfCapabilities.currentExtent().height();
763 | }
764 |
765 | int swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
766 |
767 | // Determine the number of VkImage's to use in the swap chain.
768 | // Application desires to only acquire 1 image at a time (which is
769 | // "surfCapabilities.minImageCount").
770 | int desiredNumOfSwapchainImages = surfCapabilities.minImageCount();
771 | // If maxImageCount is 0, we can ask for as many images as we want;
772 | // otherwise we're limited to maxImageCount
773 | if ((surfCapabilities.maxImageCount() > 0) &&
774 | (desiredNumOfSwapchainImages > surfCapabilities.maxImageCount())) {
775 | // Application must settle for fewer images than desired:
776 | desiredNumOfSwapchainImages = surfCapabilities.maxImageCount();
777 | }
778 |
779 | int preTransform;
780 | if ((surfCapabilities.supportedTransforms() & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) != 0) {
781 | preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
782 | } else {
783 | preTransform = surfCapabilities.currentTransform();
784 | }
785 |
786 | VkSwapchainCreateInfoKHR swapchain = VkSwapchainCreateInfoKHR.callocStack(stack)
787 | .sType(VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR)
788 | .surface(surface)
789 | .minImageCount(desiredNumOfSwapchainImages)
790 | .imageFormat(format)
791 | .imageColorSpace(color_space)
792 | .imageExtent(swapchainExtent)
793 | .imageArrayLayers(1)
794 | .imageUsage(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)
795 | .imageSharingMode(VK_SHARING_MODE_EXCLUSIVE)
796 | .preTransform(preTransform)
797 | .compositeAlpha(VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
798 | .presentMode(swapchainPresentMode)
799 | .clipped(true)
800 | .oldSwapchain(oldSwapchain);
801 |
802 | check(vkCreateSwapchainKHR(device, swapchain, null, lp));
803 | this.swapchain = lp.get(0);
804 |
805 | // If we just re-created an existing swapchain, we should destroy the old
806 | // swapchain at this point.
807 | // Note: destroying the swapchain also cleans up all its associated
808 | // presentable images once the platform is done with them.
809 | if (oldSwapchain != VK_NULL_HANDLE) {
810 | vkDeviceWaitIdle(device);
811 | vkDestroySwapchainKHR(device, oldSwapchain, null);
812 | }
813 |
814 | check(vkGetSwapchainImagesKHR(device, this.swapchain, ip, null));
815 | swapchainImageCount = ip.get(0);
816 |
817 | LongBuffer swapchainImages = stack.mallocLong(swapchainImageCount);
818 | check(vkGetSwapchainImagesKHR(device, this.swapchain, ip, swapchainImages));
819 |
820 | buffers = new SwapchainBuffers[swapchainImageCount];
821 |
822 | for (int i = 0; i < swapchainImageCount; i++) {
823 | buffers[i] = new SwapchainBuffers();
824 | buffers[i].image = swapchainImages.get(i);
825 |
826 | VkImageViewCreateInfo color_attachment_view = VkImageViewCreateInfo.mallocStack(stack)
827 | .sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
828 | .pNext(NULL)
829 | .flags(0)
830 | .image(buffers[i].image)
831 | .viewType(VK_IMAGE_VIEW_TYPE_2D)
832 | .format(format);
833 |
834 | color_attachment_view.components()
835 | .r(VK_COMPONENT_SWIZZLE_R)
836 | .g(VK_COMPONENT_SWIZZLE_G)
837 | .b(VK_COMPONENT_SWIZZLE_B)
838 | .a(VK_COMPONENT_SWIZZLE_A);
839 |
840 | color_attachment_view.subresourceRange()
841 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
842 | .baseMipLevel(0)
843 | .levelCount(1)
844 | .baseArrayLayer(0)
845 | .layerCount(1);
846 |
847 | check(vkCreateImageView(device, color_attachment_view, null, lp));
848 | buffers[i].view = lp.get(0);
849 | }
850 |
851 | current_buffer = 0;
852 | }
853 | }
854 |
855 | private static class Depth {
856 | int format;
857 |
858 | long image;
859 | long mem;
860 | long view;
861 | }
862 |
863 | private boolean memory_type_from_properties(int typeBits, int requirements_mask, VkMemoryAllocateInfo mem_alloc) {
864 | // Search memtypes to find first index with those properties
865 | for (int i = 0; i < VK_MAX_MEMORY_TYPES; i++) {
866 | if ((typeBits & 1) == 1) {
867 | // Type is available, does it match user properties?
868 | if ((memory_properties.memoryTypes().get(i).propertyFlags() & requirements_mask) == requirements_mask) {
869 | mem_alloc.memoryTypeIndex(i);
870 | return true;
871 | }
872 | }
873 | typeBits >>= 1;
874 | }
875 | // No memory types matched, return failure
876 | return false;
877 | }
878 |
879 | private void demo_prepare_depth() {
880 | depth.format = VK_FORMAT_D16_UNORM;
881 |
882 | try (MemoryStack stack = stackPush()) {
883 | VkImageCreateInfo image = VkImageCreateInfo.callocStack(stack)
884 | .sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO)
885 | .pNext(NULL)
886 | .imageType(VK_IMAGE_TYPE_2D)
887 | .format(depth.format)
888 | .mipLevels(1)
889 | .arrayLayers(1)
890 | .samples(VK_SAMPLE_COUNT_1_BIT)
891 | .tiling(VK_IMAGE_TILING_OPTIMAL)
892 | .usage(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT);
893 | image.extent()
894 | .width(width)
895 | .height(height)
896 | .depth(1);
897 |
898 | /* create image */
899 | check(vkCreateImage(device, image, null, lp));
900 | depth.image = lp.get(0);
901 |
902 | /* get memory requirements for this object */
903 | VkMemoryRequirements mem_reqs = VkMemoryRequirements.mallocStack(stack);
904 | vkGetImageMemoryRequirements(device, depth.image, mem_reqs);
905 |
906 | /* select memory size and type */
907 | VkMemoryAllocateInfo mem_alloc = VkMemoryAllocateInfo.mallocStack(stack)
908 | .sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
909 | .pNext(NULL)
910 | .allocationSize(mem_reqs.size())
911 | .memoryTypeIndex(0);
912 | boolean pass = memory_type_from_properties(mem_reqs.memoryTypeBits(),
913 | 0, /* No requirements */
914 | mem_alloc);
915 | assert (pass);
916 |
917 | /* allocate memory */
918 | check(vkAllocateMemory(device, mem_alloc, null, lp));
919 | depth.mem = lp.get(0);
920 |
921 | /* bind memory */
922 | check(vkBindImageMemory(device, depth.image, depth.mem, 0));
923 |
924 | demo_set_image_layout(depth.image, VK_IMAGE_ASPECT_DEPTH_BIT,
925 | VK_IMAGE_LAYOUT_UNDEFINED,
926 | VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
927 | 0);
928 |
929 | /* create image view */
930 | VkImageViewCreateInfo view = VkImageViewCreateInfo.callocStack(stack)
931 | .sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
932 | .pNext(NULL)
933 | .flags(0)
934 | .image(depth.image)
935 | .viewType(VK_IMAGE_VIEW_TYPE_2D)
936 | .format(depth.format);
937 | view.subresourceRange()
938 | .aspectMask(VK_IMAGE_ASPECT_DEPTH_BIT)
939 | .baseMipLevel(0)
940 | .levelCount(1)
941 | .baseArrayLayer(0)
942 | .layerCount(1);
943 |
944 | check(vkCreateImageView(device, view, null, lp));
945 | depth.view = lp.get(0);
946 | }
947 | }
948 |
949 | private static class TextureObject {
950 | long sampler;
951 |
952 | long image;
953 | int imageLayout;
954 |
955 | long mem;
956 | long view;
957 | int tex_width, tex_height;
958 | }
959 |
960 | private void demo_prepare_texture_image(
961 | int[] tex_colors,
962 | TextureObject tex_obj, int tiling,
963 | int usage, int required_props
964 | ) {
965 | int tex_format = VK_FORMAT_B8G8R8A8_UNORM;
966 | int tex_width = 2;
967 | int tex_height = 2;
968 | boolean pass;
969 |
970 | tex_obj.tex_width = tex_width;
971 | tex_obj.tex_height = tex_height;
972 |
973 | try (MemoryStack stack = stackPush()) {
974 | VkImageCreateInfo image_create_info = VkImageCreateInfo.callocStack(stack)
975 | .sType(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO)
976 | .pNext(NULL)
977 | .imageType(VK_IMAGE_TYPE_2D)
978 | .format(tex_format)
979 | .mipLevels(1)
980 | .arrayLayers(1)
981 | .samples(VK_SAMPLE_COUNT_1_BIT)
982 | .tiling(tiling)
983 | .usage(usage)
984 | .flags(0)
985 | .initialLayout(VK_IMAGE_LAYOUT_PREINITIALIZED);
986 | image_create_info.extent()
987 | .width(tex_width)
988 | .height(tex_height)
989 | .depth(1);
990 |
991 | check(vkCreateImage(device, image_create_info, null, lp));
992 | tex_obj.image = lp.get(0);
993 |
994 | VkMemoryRequirements mem_reqs = VkMemoryRequirements.mallocStack(stack);
995 | vkGetImageMemoryRequirements(device, tex_obj.image, mem_reqs);
996 | VkMemoryAllocateInfo mem_alloc = VkMemoryAllocateInfo.mallocStack(stack)
997 | .sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
998 | .pNext(NULL)
999 | .allocationSize(mem_reqs.size())
1000 | .memoryTypeIndex(0);
1001 | pass = memory_type_from_properties(mem_reqs.memoryTypeBits(), required_props, mem_alloc);
1002 | assert (pass);
1003 |
1004 | /* allocate memory */
1005 | check(vkAllocateMemory(device, mem_alloc, null, lp));
1006 | tex_obj.mem = lp.get(0);
1007 |
1008 | /* bind memory */
1009 | check(vkBindImageMemory(device, tex_obj.image, tex_obj.mem, 0));
1010 |
1011 | if ((required_props & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) != 0) {
1012 | VkImageSubresource subres = VkImageSubresource.mallocStack(stack)
1013 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
1014 | .mipLevel(0)
1015 | .arrayLayer(0);
1016 |
1017 | VkSubresourceLayout layout = VkSubresourceLayout.mallocStack(stack);
1018 | vkGetImageSubresourceLayout(device, tex_obj.image, subres, layout);
1019 |
1020 | check(vkMapMemory(device, tex_obj.mem, 0, mem_alloc.allocationSize(), 0, pp));
1021 |
1022 | for (int y = 0; y < tex_height; y++) {
1023 | IntBuffer row = memIntBuffer(pp.get(0) + layout.rowPitch() * y, tex_width);
1024 | for (int x = 0; x < tex_width; x++)
1025 | row.put(x, tex_colors[(x & 1) ^ (y & 1)]);
1026 | }
1027 |
1028 | vkUnmapMemory(device, tex_obj.mem);
1029 | }
1030 |
1031 | tex_obj.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1032 | demo_set_image_layout(tex_obj.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_PREINITIALIZED, tex_obj.imageLayout, VK_ACCESS_HOST_WRITE_BIT);
1033 | /* setting the image layout does not reference the actual memory so no need
1034 | * to add a mem ref */
1035 | }
1036 | }
1037 |
1038 | private void demo_destroy_texture_image(TextureObject tex_obj) {
1039 | /* clean up staging resources */
1040 | vkDestroyImage(device, tex_obj.image, null);
1041 | vkFreeMemory(device, tex_obj.mem, null);
1042 | }
1043 |
1044 | private void demo_flush_init_cmd() {
1045 | if (setup_cmd == null)
1046 | return;
1047 |
1048 | check(vkEndCommandBuffer(setup_cmd));
1049 |
1050 | try (MemoryStack stack = stackPush()) {
1051 | VkSubmitInfo submit_info = VkSubmitInfo.callocStack(stack)
1052 | .sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
1053 | .pCommandBuffers(pp.put(0, setup_cmd));
1054 |
1055 | check(vkQueueSubmit(queue, submit_info, VK_NULL_HANDLE));
1056 | }
1057 |
1058 | check(vkQueueWaitIdle(queue));
1059 |
1060 | vkFreeCommandBuffers(device, cmd_pool, pp);
1061 | setup_cmd = null;
1062 | }
1063 |
1064 | private void demo_prepare_textures() {
1065 | int tex_format = VK_FORMAT_B8G8R8A8_UNORM;
1066 | int[][] tex_colors = {{0xffff0000, 0xff00ff00}};
1067 |
1068 | try (MemoryStack stack = stackPush()) {
1069 | VkFormatProperties props = VkFormatProperties.mallocStack(stack);
1070 | vkGetPhysicalDeviceFormatProperties(gpu, tex_format, props);
1071 |
1072 | for (int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1073 | if ((props.linearTilingFeatures() & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0 && !USE_STAGING_BUFFER) {
1074 | /* Device can texture using linear textures */
1075 | demo_prepare_texture_image(
1076 | tex_colors[i], textures[i], VK_IMAGE_TILING_LINEAR,
1077 | VK_IMAGE_USAGE_SAMPLED_BIT,
1078 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
1079 | } else if ((props.optimalTilingFeatures() & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) != 0) {
1080 | /* Must use staging buffer to copy linear texture to optimized */
1081 | TextureObject staging_texture = new TextureObject();
1082 |
1083 | demo_prepare_texture_image(
1084 | tex_colors[i], staging_texture, VK_IMAGE_TILING_LINEAR,
1085 | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
1086 | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
1087 |
1088 | demo_prepare_texture_image(
1089 | tex_colors[i], textures[i],
1090 | VK_IMAGE_TILING_OPTIMAL,
1091 | (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT),
1092 | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
1093 |
1094 | demo_set_image_layout(staging_texture.image,
1095 | VK_IMAGE_ASPECT_COLOR_BIT,
1096 | staging_texture.imageLayout,
1097 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1098 | 0);
1099 |
1100 | demo_set_image_layout(textures[i].image,
1101 | VK_IMAGE_ASPECT_COLOR_BIT,
1102 | textures[i].imageLayout,
1103 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1104 | 0);
1105 |
1106 | VkImageCopy.Buffer copy_region = VkImageCopy.mallocStack(1, stack);
1107 | copy_region.srcSubresource()
1108 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
1109 | .mipLevel(0)
1110 | .baseArrayLayer(0)
1111 | .layerCount(1);
1112 | copy_region.srcOffset()
1113 | .x(0)
1114 | .y(0)
1115 | .z(0);
1116 | copy_region.dstSubresource()
1117 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
1118 | .mipLevel(0)
1119 | .baseArrayLayer(0)
1120 | .layerCount(1);
1121 | copy_region.dstOffset()
1122 | .x(0)
1123 | .y(0)
1124 | .z(0);
1125 | copy_region.extent()
1126 | .width(staging_texture.tex_width)
1127 | .height(staging_texture.tex_height)
1128 | .depth(1);
1129 |
1130 | vkCmdCopyImage(
1131 | setup_cmd, staging_texture.image,
1132 | VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, textures[i].image,
1133 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, copy_region
1134 | );
1135 |
1136 | demo_set_image_layout(textures[i].image,
1137 | VK_IMAGE_ASPECT_COLOR_BIT,
1138 | VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1139 | textures[i].imageLayout,
1140 | 0);
1141 |
1142 | demo_flush_init_cmd();
1143 |
1144 | demo_destroy_texture_image(staging_texture);
1145 | } else {
1146 | /* Can't support VK_FORMAT_B8G8R8A8_UNORM !? */
1147 | throw new IllegalStateException("No support for B8G8R8A8_UNORM as texture image format");
1148 | }
1149 |
1150 | VkSamplerCreateInfo sampler = VkSamplerCreateInfo.callocStack(stack)
1151 | .sType(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO)
1152 | .pNext(NULL)
1153 | .magFilter(VK_FILTER_NEAREST)
1154 | .minFilter(VK_FILTER_NEAREST)
1155 | .mipmapMode(VK_SAMPLER_MIPMAP_MODE_NEAREST)
1156 | .addressModeU(VK_SAMPLER_ADDRESS_MODE_REPEAT)
1157 | .addressModeV(VK_SAMPLER_ADDRESS_MODE_REPEAT)
1158 | .addressModeW(VK_SAMPLER_ADDRESS_MODE_REPEAT)
1159 | .mipLodBias(0.0f)
1160 | .anisotropyEnable(false)
1161 | .maxAnisotropy(1)
1162 | .compareOp(VK_COMPARE_OP_NEVER)
1163 | .minLod(0.0f)
1164 | .maxLod(0.0f)
1165 | .borderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE)
1166 | .unnormalizedCoordinates(false);
1167 |
1168 | /* create sampler */
1169 | check(vkCreateSampler(device, sampler, null, lp));
1170 | textures[i].sampler = lp.get(0);
1171 |
1172 | VkImageViewCreateInfo view = VkImageViewCreateInfo.mallocStack(stack)
1173 | .sType(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO)
1174 | .pNext(NULL)
1175 | .image(VK_NULL_HANDLE)
1176 | .viewType(VK_IMAGE_VIEW_TYPE_2D)
1177 | .format(tex_format)
1178 | .flags(0);
1179 | view.components()
1180 | .r(VK_COMPONENT_SWIZZLE_R)
1181 | .g(VK_COMPONENT_SWIZZLE_G)
1182 | .b(VK_COMPONENT_SWIZZLE_B)
1183 | .a(VK_COMPONENT_SWIZZLE_A);
1184 | view.subresourceRange()
1185 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
1186 | .baseMipLevel(0)
1187 | .levelCount(1)
1188 | .baseArrayLayer(0)
1189 | .layerCount(1);
1190 |
1191 | /* create image view */
1192 | view.image(textures[i].image);
1193 | check(vkCreateImageView(device, view, null, lp));
1194 | textures[i].view = lp.get(0);
1195 | }
1196 | }
1197 | }
1198 |
1199 | private static class Vertices {
1200 | long buf;
1201 | long mem;
1202 |
1203 | VkPipelineVertexInputStateCreateInfo vi = VkPipelineVertexInputStateCreateInfo.calloc();
1204 | VkVertexInputBindingDescription.Buffer vi_bindings = VkVertexInputBindingDescription.calloc(1);
1205 | VkVertexInputAttributeDescription.Buffer vi_attrs = VkVertexInputAttributeDescription.calloc(2);
1206 | }
1207 |
1208 | private void demo_prepare_vertices() {
1209 | float[][] vb = {
1210 | /* position texcoord */
1211 | {-1.0f, -1.0f, 0.25f, 0.0f, 0.0f},
1212 | {1.0f, -1.0f, 0.25f, 1.0f, 0.0f},
1213 | {0.0f, 1.0f, 1.0f, 0.5f, 1.0f},
1214 | };
1215 |
1216 | try (MemoryStack stack = stackPush()) {
1217 | VkBufferCreateInfo buf_info = VkBufferCreateInfo.callocStack(stack)
1218 | .sType(VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO)
1219 | .size(/*sizeof(vb)*/ vb.length * vb[0].length * 4)
1220 | .usage(VK_BUFFER_USAGE_VERTEX_BUFFER_BIT)
1221 | .sharingMode(VK_SHARING_MODE_EXCLUSIVE);
1222 |
1223 | check(vkCreateBuffer(device, buf_info, null, lp));
1224 | vertices.buf = lp.get(0);
1225 |
1226 | VkMemoryRequirements mem_reqs = VkMemoryRequirements.mallocStack(stack);
1227 | vkGetBufferMemoryRequirements(device, vertices.buf, mem_reqs);
1228 |
1229 | VkMemoryAllocateInfo mem_alloc = VkMemoryAllocateInfo.callocStack(stack)
1230 | .sType(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO)
1231 | .allocationSize(mem_reqs.size());
1232 | boolean pass = memory_type_from_properties(mem_reqs.memoryTypeBits(), VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mem_alloc);
1233 | assert (pass);
1234 |
1235 | check(vkAllocateMemory(device, mem_alloc, null, lp));
1236 | vertices.mem = lp.get(0);
1237 |
1238 | check(vkMapMemory(device, vertices.mem, 0, mem_alloc.allocationSize(), 0, pp));
1239 | FloatBuffer data = pp.getFloatBuffer(0, ((int) mem_alloc.allocationSize()) >> 2);
1240 | data
1241 | .put(vb[0])
1242 | .put(vb[1])
1243 | .put(vb[2])
1244 | .flip();
1245 | }
1246 |
1247 | vkUnmapMemory(device, vertices.mem);
1248 |
1249 | check(vkBindBufferMemory(device, vertices.buf, vertices.mem, 0));
1250 |
1251 | vertices.vi
1252 | .sType(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO)
1253 | .pNext(NULL)
1254 | .pVertexBindingDescriptions(vertices.vi_bindings)
1255 | .pVertexAttributeDescriptions(vertices.vi_attrs);
1256 |
1257 | vertices.vi_bindings.get(0)
1258 | .binding(VERTEX_BUFFER_BIND_ID)
1259 | .stride(vb[0].length * 4)
1260 | .inputRate(VK_VERTEX_INPUT_RATE_VERTEX);
1261 |
1262 | vertices.vi_attrs.get(0)
1263 | .binding(VERTEX_BUFFER_BIND_ID)
1264 | .location(0)
1265 | .format(VK_FORMAT_R32G32B32_SFLOAT)
1266 | .offset(0);
1267 |
1268 | vertices.vi_attrs.get(1)
1269 | .binding(VERTEX_BUFFER_BIND_ID)
1270 | .location(1)
1271 | .format(VK_FORMAT_R32G32_SFLOAT)
1272 | .offset(4 * 3);
1273 | }
1274 |
1275 | private void demo_prepare_descriptor_layout() {
1276 | try (MemoryStack stack = stackPush()) {
1277 | VkDescriptorSetLayoutCreateInfo descriptor_layout = VkDescriptorSetLayoutCreateInfo.mallocStack(stack)
1278 | .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO)
1279 | .pNext(NULL)
1280 | .flags(0)
1281 | .pBindings(
1282 | VkDescriptorSetLayoutBinding.callocStack(1, stack)
1283 | .binding(0)
1284 | .descriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
1285 | .descriptorCount(DEMO_TEXTURE_COUNT)
1286 | .stageFlags(VK_SHADER_STAGE_FRAGMENT_BIT)
1287 | );
1288 |
1289 | LongBuffer layouts = stack.mallocLong(1);
1290 | check(vkCreateDescriptorSetLayout(device, descriptor_layout, null, layouts));
1291 | desc_layout = layouts.get(0);
1292 |
1293 | VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = VkPipelineLayoutCreateInfo.callocStack(stack)
1294 | .sType(VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO)
1295 | .pNext(NULL)
1296 | .pSetLayouts(layouts);
1297 |
1298 | check(vkCreatePipelineLayout(device, pPipelineLayoutCreateInfo, null, lp));
1299 | pipeline_layout = lp.get(0);
1300 | }
1301 | }
1302 |
1303 | private void demo_prepare_render_pass() {
1304 | try (MemoryStack stack = stackPush()) {
1305 | VkAttachmentDescription.Buffer attachments = VkAttachmentDescription.mallocStack(2, stack);
1306 | attachments.get(0)
1307 | .flags(0)
1308 | .format(format)
1309 | .samples(VK_SAMPLE_COUNT_1_BIT)
1310 | .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR)
1311 | .storeOp(VK_ATTACHMENT_STORE_OP_STORE)
1312 | .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
1313 | .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
1314 | .initialLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
1315 | .finalLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
1316 | attachments.get(1)
1317 | .flags(0)
1318 | .format(depth.format)
1319 | .samples(VK_SAMPLE_COUNT_1_BIT)
1320 | .loadOp(VK_ATTACHMENT_LOAD_OP_CLEAR)
1321 | .storeOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
1322 | .stencilLoadOp(VK_ATTACHMENT_LOAD_OP_DONT_CARE)
1323 | .stencilStoreOp(VK_ATTACHMENT_STORE_OP_DONT_CARE)
1324 | .initialLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
1325 | .finalLayout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
1326 |
1327 | VkSubpassDescription.Buffer subpass = VkSubpassDescription.callocStack(1, stack)
1328 | .pipelineBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS)
1329 | .colorAttachmentCount(1)
1330 | .pColorAttachments(
1331 | VkAttachmentReference.mallocStack(1, stack)
1332 | .attachment(0)
1333 | .layout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
1334 | )
1335 | .pDepthStencilAttachment(
1336 | VkAttachmentReference.mallocStack(stack)
1337 | .attachment(1)
1338 | .layout(VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
1339 | );
1340 |
1341 | VkRenderPassCreateInfo rp_info = VkRenderPassCreateInfo.callocStack(stack)
1342 | .sType(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO)
1343 | .pAttachments(attachments)
1344 | .pSubpasses(subpass);
1345 |
1346 | check(vkCreateRenderPass(device, rp_info, null, lp));
1347 | render_pass = lp.get(0);
1348 | }
1349 | }
1350 |
1351 | private long demo_prepare_shader_module(byte[] code) {
1352 | try (MemoryStack stack = stackPush()) {
1353 | ByteBuffer pCode = memAlloc(code.length).put(code);
1354 | pCode.flip();
1355 |
1356 | VkShaderModuleCreateInfo moduleCreateInfo = VkShaderModuleCreateInfo.mallocStack(stack)
1357 | .sType(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO)
1358 | .pNext(NULL)
1359 | .flags(0)
1360 | .pCode(pCode);
1361 |
1362 | check(vkCreateShaderModule(device, moduleCreateInfo, null, lp));
1363 |
1364 | memFree(pCode);
1365 |
1366 | return lp.get(0);
1367 | }
1368 | }
1369 |
1370 | private void demo_prepare_pipeline() {
1371 | long vert_shader_module;
1372 | long frag_shader_module;
1373 | long pipelineCache;
1374 |
1375 | try (MemoryStack stack = stackPush()) {
1376 | VkGraphicsPipelineCreateInfo.Buffer pipeline = VkGraphicsPipelineCreateInfo.callocStack(1, stack);
1377 |
1378 | // Two stages: vs and fs
1379 | ByteBuffer main = stack.UTF8("main");
1380 |
1381 | VkPipelineShaderStageCreateInfo.Buffer shaderStages = VkPipelineShaderStageCreateInfo.callocStack(2, stack);
1382 | shaderStages.get(0)
1383 | .sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO)
1384 | .stage(VK_SHADER_STAGE_VERTEX_BIT)
1385 | .module(vert_shader_module = demo_prepare_shader_module(vertShaderCode))
1386 | .pName(main);
1387 | shaderStages.get(1)
1388 | .sType(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO)
1389 | .stage(VK_SHADER_STAGE_FRAGMENT_BIT)
1390 | .module(frag_shader_module = demo_prepare_shader_module(fragShaderCode))
1391 | .pName(main);
1392 |
1393 | VkPipelineDepthStencilStateCreateInfo ds = VkPipelineDepthStencilStateCreateInfo.callocStack(stack)
1394 | .sType(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO)
1395 | .depthTestEnable(true)
1396 | .depthWriteEnable(true)
1397 | .depthCompareOp(VK_COMPARE_OP_LESS_OR_EQUAL)
1398 | .depthBoundsTestEnable(false)
1399 | .stencilTestEnable(false);
1400 | ds.back()
1401 | .failOp(VK_STENCIL_OP_KEEP)
1402 | .passOp(VK_STENCIL_OP_KEEP)
1403 | .compareOp(VK_COMPARE_OP_ALWAYS);
1404 | ds.front(ds.back());
1405 |
1406 | pipeline
1407 | .sType(VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO)
1408 | .pStages(shaderStages)
1409 | .pVertexInputState(vertices.vi)
1410 | .pInputAssemblyState(
1411 | VkPipelineInputAssemblyStateCreateInfo.callocStack(stack)
1412 | .sType(VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO)
1413 | .topology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST))
1414 | .pViewportState(
1415 | VkPipelineViewportStateCreateInfo.callocStack(stack)
1416 | .sType(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO)
1417 | .viewportCount(1)
1418 | .scissorCount(1))
1419 | .pRasterizationState(
1420 | VkPipelineRasterizationStateCreateInfo.callocStack(stack)
1421 | .sType(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO)
1422 | .polygonMode(VK_POLYGON_MODE_FILL)
1423 | .cullMode(VK_CULL_MODE_BACK_BIT)
1424 | .frontFace(VK_FRONT_FACE_CLOCKWISE)
1425 | .depthClampEnable(false)
1426 | .rasterizerDiscardEnable(false)
1427 | .depthBiasEnable(false)
1428 | .lineWidth(1.0f))
1429 | .pMultisampleState(
1430 | VkPipelineMultisampleStateCreateInfo.callocStack(stack)
1431 | .sType(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO)
1432 | .pSampleMask(null)
1433 | .rasterizationSamples(VK_SAMPLE_COUNT_1_BIT))
1434 | .pDepthStencilState(ds)
1435 | .pColorBlendState(
1436 | VkPipelineColorBlendStateCreateInfo.callocStack(stack)
1437 | .sType(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO)
1438 | .pAttachments(
1439 | VkPipelineColorBlendAttachmentState.callocStack(1, stack)
1440 | .colorWriteMask(0xf)
1441 | .blendEnable(false)
1442 | ))
1443 | .pDynamicState(
1444 | VkPipelineDynamicStateCreateInfo.callocStack(stack)
1445 | .sType(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO)
1446 | .pDynamicStates(stack.ints(
1447 | VK_DYNAMIC_STATE_VIEWPORT,
1448 | VK_DYNAMIC_STATE_SCISSOR
1449 | )))
1450 | .layout(pipeline_layout)
1451 | .renderPass(render_pass);
1452 |
1453 | VkPipelineCacheCreateInfo pipelineCacheCI = VkPipelineCacheCreateInfo.callocStack(stack)
1454 | .sType(VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO);
1455 |
1456 | check(vkCreatePipelineCache(device, pipelineCacheCI, null, lp));
1457 | pipelineCache = lp.get(0);
1458 |
1459 | check(vkCreateGraphicsPipelines(device, pipelineCache, pipeline, null, lp));
1460 | this.pipeline = lp.get(0);
1461 |
1462 | vkDestroyPipelineCache(device, pipelineCache, null);
1463 |
1464 | vkDestroyShaderModule(device, frag_shader_module, null);
1465 | vkDestroyShaderModule(device, vert_shader_module, null);
1466 | }
1467 | }
1468 |
1469 | private void demo_prepare_descriptor_pool() {
1470 | try (MemoryStack stack = stackPush()) {
1471 | VkDescriptorPoolCreateInfo descriptor_pool = VkDescriptorPoolCreateInfo.callocStack(stack)
1472 | .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO)
1473 | .pNext(NULL)
1474 | .maxSets(1)
1475 | .pPoolSizes(
1476 | VkDescriptorPoolSize.mallocStack(1, stack)
1477 | .type(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
1478 | .descriptorCount(DEMO_TEXTURE_COUNT)
1479 | );
1480 |
1481 | check(vkCreateDescriptorPool(device, descriptor_pool, null, lp));
1482 | desc_pool = lp.get(0);
1483 | }
1484 | }
1485 |
1486 | private void demo_prepare_descriptor_set() {
1487 | try (MemoryStack stack = stackPush()) {
1488 | LongBuffer layouts = stack.longs(desc_layout);
1489 | VkDescriptorSetAllocateInfo alloc_info = VkDescriptorSetAllocateInfo.mallocStack(stack)
1490 | .sType(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO)
1491 | .pNext(NULL)
1492 | .descriptorPool(desc_pool)
1493 | .pSetLayouts(layouts);
1494 |
1495 | check(vkAllocateDescriptorSets(device, alloc_info, lp));
1496 | desc_set = lp.get(0);
1497 |
1498 | VkDescriptorImageInfo.Buffer tex_descs = VkDescriptorImageInfo.callocStack(DEMO_TEXTURE_COUNT, stack);
1499 | for (int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1500 | tex_descs.get(i)
1501 | .sampler(textures[i].sampler)
1502 | .imageView(textures[i].view)
1503 | .imageLayout(VK_IMAGE_LAYOUT_GENERAL);
1504 | }
1505 |
1506 | VkWriteDescriptorSet.Buffer write = VkWriteDescriptorSet.callocStack(1, stack)
1507 | .sType(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET)
1508 | .dstSet(desc_set)
1509 | .descriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
1510 | .pImageInfo(tex_descs);
1511 |
1512 | vkUpdateDescriptorSets(device, write, null);
1513 | }
1514 | }
1515 |
1516 | private void demo_prepare_framebuffers() {
1517 | try (MemoryStack stack = stackPush()) {
1518 | LongBuffer attachments = stack.longs(0, depth.view);
1519 |
1520 | VkFramebufferCreateInfo fb_info = VkFramebufferCreateInfo.mallocStack(stack)
1521 | .sType(VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO)
1522 | .pNext(NULL)
1523 | .flags(0)
1524 | .renderPass(render_pass)
1525 | .pAttachments(attachments)
1526 | .width(width)
1527 | .height(height)
1528 | .layers(1);
1529 |
1530 | framebuffers = memAllocLong(swapchainImageCount);
1531 |
1532 | for (int i = 0; i < swapchainImageCount; i++) {
1533 | attachments.put(0, buffers[i].view);
1534 | check(vkCreateFramebuffer(device, fb_info, null, lp));
1535 | framebuffers.put(i, lp.get(0));
1536 | }
1537 | }
1538 | }
1539 |
1540 | private void demo_prepare() {
1541 | try (MemoryStack stack = stackPush()) {
1542 | VkCommandPoolCreateInfo cmd_pool_info = VkCommandPoolCreateInfo.mallocStack(stack)
1543 | .sType(VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO)
1544 | .pNext(NULL)
1545 | .flags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)
1546 | .queueFamilyIndex(graphics_queue_node_index);
1547 |
1548 | check(vkCreateCommandPool(device, cmd_pool_info, null, lp));
1549 |
1550 | cmd_pool = lp.get(0);
1551 |
1552 | VkCommandBufferAllocateInfo cmd = VkCommandBufferAllocateInfo.mallocStack(stack)
1553 | .sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO)
1554 | .pNext(NULL)
1555 | .commandPool(cmd_pool)
1556 | .level(VK_COMMAND_BUFFER_LEVEL_PRIMARY)
1557 | .commandBufferCount(1);
1558 |
1559 | check(vkAllocateCommandBuffers(device, cmd, pp));
1560 | }
1561 |
1562 | draw_cmd = new VkCommandBuffer(pp.get(0), device);
1563 |
1564 | demo_prepare_buffers();
1565 | demo_prepare_depth();
1566 | demo_prepare_textures();
1567 | demo_prepare_vertices();
1568 | demo_prepare_descriptor_layout();
1569 | demo_prepare_render_pass();
1570 | demo_prepare_pipeline();
1571 |
1572 | demo_prepare_descriptor_pool();
1573 | demo_prepare_descriptor_set();
1574 |
1575 | demo_prepare_framebuffers();
1576 | }
1577 |
1578 | private void demo_draw_build_cmd() {
1579 | try (MemoryStack stack = stackPush()) {
1580 | VkCommandBufferBeginInfo cmd_buf_info = VkCommandBufferBeginInfo.mallocStack(stack)
1581 | .sType(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO)
1582 | .pNext(NULL)
1583 | .flags(0)
1584 | .pInheritanceInfo(null);
1585 |
1586 | check(vkBeginCommandBuffer(draw_cmd, cmd_buf_info));
1587 |
1588 | VkClearValue.Buffer clear_values = VkClearValue.mallocStack(2, stack);
1589 | clear_values.get(0).color()
1590 | .float32(0, 0.2f)
1591 | .float32(1, 0.2f)
1592 | .float32(2, 0.2f)
1593 | .float32(3, 0.2f);
1594 | clear_values.get(1).depthStencil()
1595 | .depth(depthStencil)
1596 | .stencil(0);
1597 |
1598 | VkRenderPassBeginInfo rp_begin = VkRenderPassBeginInfo.mallocStack(stack)
1599 | .sType(VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO)
1600 | .pNext(NULL)
1601 | .renderPass(render_pass)
1602 | .framebuffer(framebuffers.get(current_buffer))
1603 | .pClearValues(clear_values);
1604 | rp_begin.renderArea().offset()
1605 | .x(0)
1606 | .y(0);
1607 | rp_begin.renderArea().extent()
1608 | .width(width)
1609 | .height(height);
1610 |
1611 | // We can use LAYOUT_UNDEFINED as a wildcard here because we don't care what
1612 | // happens to the previous contents of the image
1613 | VkImageMemoryBarrier.Buffer image_memory_barrier = VkImageMemoryBarrier.mallocStack(1, stack)
1614 | .sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
1615 | .pNext(NULL)
1616 | .srcAccessMask(0)
1617 | .dstAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
1618 | .oldLayout(VK_IMAGE_LAYOUT_UNDEFINED)
1619 | .newLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
1620 | .srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
1621 | .dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
1622 | .image(buffers[current_buffer].image)
1623 | .subresourceRange(VkImageSubresourceRange.mallocStack(stack).set(VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1));
1624 |
1625 | vkCmdPipelineBarrier(draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, null, null, image_memory_barrier);
1626 | vkCmdBeginRenderPass(draw_cmd, rp_begin, VK_SUBPASS_CONTENTS_INLINE);
1627 |
1628 | vkCmdBindPipeline(draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1629 |
1630 | lp.put(0, desc_set);
1631 | vkCmdBindDescriptorSets(draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline_layout, 0, lp, null);
1632 |
1633 | VkViewport.Buffer viewport = VkViewport.callocStack(1, stack)
1634 | .height(height)
1635 | .width(width)
1636 | .minDepth(0.0f)
1637 | .maxDepth(1.0f);
1638 | vkCmdSetViewport(draw_cmd, 0, viewport);
1639 |
1640 | VkRect2D.Buffer scissor = VkRect2D.callocStack(1, stack);
1641 | scissor.extent()
1642 | .width(width)
1643 | .height(height);
1644 | scissor.offset()
1645 | .x(0)
1646 | .y(0);
1647 | vkCmdSetScissor(draw_cmd, 0, scissor);
1648 |
1649 | lp.put(0, 0);
1650 | LongBuffer pBuffers = stack.longs(vertices.buf);
1651 | vkCmdBindVertexBuffers(draw_cmd, VERTEX_BUFFER_BIND_ID, pBuffers, lp);
1652 |
1653 | vkCmdDraw(draw_cmd, 3, 1, 0, 0);
1654 | vkCmdEndRenderPass(draw_cmd);
1655 |
1656 | VkImageMemoryBarrier.Buffer prePresentBarrier = VkImageMemoryBarrier.mallocStack(1, stack)
1657 | .sType(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER)
1658 | .pNext(NULL)
1659 | .srcAccessMask(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT)
1660 | .dstAccessMask(VK_ACCESS_MEMORY_READ_BIT)
1661 | .oldLayout(VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL)
1662 | .newLayout(VK_IMAGE_LAYOUT_PRESENT_SRC_KHR)
1663 | .srcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
1664 | .dstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
1665 | .image(buffers[current_buffer].image);
1666 |
1667 | prePresentBarrier.subresourceRange()
1668 | .aspectMask(VK_IMAGE_ASPECT_COLOR_BIT)
1669 | .baseMipLevel(0)
1670 | .levelCount(1)
1671 | .baseArrayLayer(0)
1672 | .layerCount(1);
1673 |
1674 | vkCmdPipelineBarrier(draw_cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, null, null, prePresentBarrier);
1675 |
1676 | check(vkEndCommandBuffer(draw_cmd));
1677 | }
1678 | }
1679 |
1680 | private boolean demo_draw() {
1681 | try (MemoryStack stack = stackPush()) {
1682 | VkSemaphoreCreateInfo semaphoreCreateInfo = VkSemaphoreCreateInfo.mallocStack(stack)
1683 | .sType(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO)
1684 | .pNext(NULL)
1685 | .flags(0);
1686 |
1687 | check(vkCreateSemaphore(device, semaphoreCreateInfo, null, lp));
1688 | long imageAcquiredSemaphore = lp.get(0);
1689 |
1690 | check(vkCreateSemaphore(device, semaphoreCreateInfo, null, lp));
1691 | long drawCompleteSemaphore = lp.get(0);
1692 |
1693 | // Get the index of the next available swapchain image:
1694 | int err = vkAcquireNextImageKHR(device, swapchain, ~0L,
1695 | imageAcquiredSemaphore,
1696 | NULL, // TODO: Show use of fence
1697 | ip);
1698 | if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1699 | // demo->swapchain is out of date (e.g. the window was resized) and
1700 | // must be recreated:
1701 | demo_resize();
1702 | demo_draw();
1703 | vkDestroySemaphore(device, drawCompleteSemaphore, null);
1704 | vkDestroySemaphore(device, imageAcquiredSemaphore, null);
1705 | return true;
1706 | } else if (err == VK_SUBOPTIMAL_KHR) {
1707 | // demo->swapchain is not as optimal as it could be, but the platform's
1708 | // presentation engine will still present the image correctly.
1709 | } else if (err != 0) {
1710 | //System.err.println("vkAcquireNextImageKHR failed: " + err);
1711 | return true;
1712 | //check(err);
1713 | }
1714 | current_buffer = ip.get(0);
1715 |
1716 | demo_flush_init_cmd();
1717 |
1718 | // Wait for the present complete semaphore to be signaled to ensure
1719 | // that the image won't be rendered to until the presentation
1720 | // engine has fully released ownership to the application, and it is
1721 | // okay to render to the image.
1722 |
1723 | demo_draw_build_cmd();
1724 | LongBuffer lp2 = stack.mallocLong(1);
1725 | VkSubmitInfo submit_info = VkSubmitInfo.mallocStack(stack)
1726 | .sType(VK_STRUCTURE_TYPE_SUBMIT_INFO)
1727 | .pNext(NULL)
1728 | .waitSemaphoreCount(1)
1729 | .pWaitSemaphores(lp.put(0, imageAcquiredSemaphore))
1730 | .pWaitDstStageMask(ip.put(0, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT))
1731 | .pCommandBuffers(pp.put(0, draw_cmd))
1732 | .pSignalSemaphores(lp2.put(0, drawCompleteSemaphore));
1733 |
1734 | check(vkQueueSubmit(queue, submit_info, VK_NULL_HANDLE));
1735 |
1736 | VkPresentInfoKHR present = VkPresentInfoKHR.callocStack(stack)
1737 | .sType(VK_STRUCTURE_TYPE_PRESENT_INFO_KHR)
1738 | .pNext(NULL)
1739 | .waitSemaphoreCount(1)
1740 | .pWaitSemaphores(lp2)
1741 | .swapchainCount(1)
1742 | .pSwapchains(lp.put(0, swapchain))
1743 | .pImageIndices(ip.put(0, current_buffer));
1744 |
1745 | err = vkQueuePresentKHR(queue, present);
1746 | if (err == VK_ERROR_OUT_OF_DATE_KHR) {
1747 | // demo->swapchain is out of date (e.g. the window was resized) and
1748 | // must be recreated:
1749 | //demo_resize();
1750 | } else if (err == VK_SUBOPTIMAL_KHR) {
1751 | // demo->swapchain is not as optimal as it could be, but the platform's
1752 | // presentation engine will still present the image correctly.
1753 | } else {
1754 | check(err);
1755 | }
1756 |
1757 | check(vkQueueWaitIdle(queue));
1758 |
1759 | vkDestroySemaphore(device, drawCompleteSemaphore, null);
1760 | vkDestroySemaphore(device, imageAcquiredSemaphore, null);
1761 | return err == 0;
1762 | }
1763 | }
1764 |
1765 | private void demo_destroy_context() {
1766 | for (int i = 0; i < swapchainImageCount; i++) {
1767 | vkDestroyFramebuffer(device, framebuffers.get(i), null);
1768 | }
1769 | memFree(framebuffers);
1770 | vkDestroyDescriptorPool(device, desc_pool, null);
1771 |
1772 | if (setup_cmd != null) {
1773 | vkFreeCommandBuffers(device, cmd_pool, setup_cmd);
1774 | }
1775 | vkFreeCommandBuffers(device, cmd_pool, draw_cmd);
1776 | vkDestroyCommandPool(device, cmd_pool, null);
1777 |
1778 | vkDestroyPipeline(device, pipeline, null);
1779 | vkDestroyRenderPass(device, render_pass, null);
1780 | vkDestroyPipelineLayout(device, pipeline_layout, null);
1781 | vkDestroyDescriptorSetLayout(device, desc_layout, null);
1782 |
1783 | vkDestroyBuffer(device, vertices.buf, null);
1784 | vkFreeMemory(device, vertices.mem, null);
1785 |
1786 | for (int i = 0; i < DEMO_TEXTURE_COUNT; i++) {
1787 | vkDestroyImageView(device, textures[i].view, null);
1788 | vkDestroyImage(device, textures[i].image, null);
1789 | vkFreeMemory(device, textures[i].mem, null);
1790 | vkDestroySampler(device, textures[i].sampler, null);
1791 | }
1792 |
1793 | for (int i = 0; i < swapchainImageCount; i++) {
1794 | vkDestroyImageView(device, buffers[i].view, null);
1795 | }
1796 |
1797 | vkDestroyImageView(device, depth.view, null);
1798 | vkDestroyImage(device, depth.image, null);
1799 | vkFreeMemory(device, depth.mem, null);
1800 |
1801 | buffers = null;
1802 | }
1803 |
1804 | private void demo_resize() {
1805 | // In order to properly resize the window, we must re-create the swapchain
1806 | // AND redo the command buffers, etc.
1807 | //
1808 | // First, perform part of the demo_cleanup() function:
1809 | demo_destroy_context();
1810 |
1811 | // Second, re-perform the demo_prepare() function, which will re-create the
1812 | // swapchain:
1813 | demo_prepare();
1814 | }
1815 |
1816 | private int c = 0;
1817 | private long t = System.nanoTime();
1818 |
1819 | boolean drawFrame() {
1820 | boolean result = demo_draw();
1821 |
1822 | if (depthStencil > 0.99f)
1823 | depthIncrement = -0.001f;
1824 | if (depthStencil < 0.8f)
1825 | depthIncrement = 0.001f;
1826 |
1827 | depthStencil += depthIncrement;
1828 |
1829 | c++;
1830 | if (System.nanoTime() - t > 1000 * 1000 * 1000) {
1831 | System.out.println(c);
1832 | t = System.nanoTime();
1833 | c = 0;
1834 | }
1835 |
1836 | // Wait for work to finish before updating MVP.
1837 | vkDeviceWaitIdle(device);
1838 | return result;
1839 | }
1840 |
1841 | void destroy() {
1842 | demo_destroy_context();
1843 |
1844 | vertices.vi.free();
1845 | vertices.vi_bindings.free();
1846 | vertices.vi_attrs.free();
1847 |
1848 | vkDestroySwapchainKHR(device, swapchain, null);
1849 | vkDestroyDevice(device, null);
1850 |
1851 | vkDestroySurfaceKHR(inst, surface, null);
1852 |
1853 | if (msg_callback != NULL)
1854 | vkDestroyDebugReportCallbackEXT(inst, msg_callback, null);
1855 | dbgFunc.free();
1856 | vkDestroyInstance(inst, null);
1857 |
1858 | gpu_features.free();
1859 | gpu_props.free();
1860 | queue_props.free();
1861 | memory_properties.free();
1862 |
1863 | memFree(extension_names);
1864 |
1865 | memFree(pp);
1866 | memFree(lp);
1867 | memFree(ip);
1868 | }
1869 |
1870 | }
--------------------------------------------------------------------------------