diff --git a/android/build/filament-tasks.gradle b/android/build/filament-tasks.gradle index c54cfe6030..4ee59b3e5a 100644 --- a/android/build/filament-tasks.gradle +++ b/android/build/filament-tasks.gradle @@ -9,6 +9,8 @@ import java.nio.file.Paths import org.gradle.internal.os.OperatingSystem +import org.gradle.api.logging.Logger; +import org.gradle.api.logging.LogLevel; def filamentToolsPath = file("../../../../out/release/filament") if (project.hasProperty("filament_tools_dir")) { @@ -24,6 +26,31 @@ if (!matcFullPath.any { path -> file(path).exists() }) { "/bin. Ensure Filament has been built/installed before building this app.") } + +class LogOutputStream extends ByteArrayOutputStream { + private final Logger logger; + private final LogLevel level; + + public LogOutputStream(Logger logger, LogLevel level) { + this.logger = logger; + this.level = level; + } + + public Logger getLogger() { + return logger; + } + + public LogLevel getLevel() { + return level; + } + + @Override + public void flush() { + logger.log(level, toString()); + reset(); + } +} + // Custom task to compile material files using matc // This task handles incremental builds class MaterialCompiler extends DefaultTask { @@ -46,7 +73,17 @@ class MaterialCompiler extends DefaultTask { inputs.outOfDate { InputFileDetails outOfDate -> def file = outOfDate.file + + def out = new LogOutputStream(logger, LogLevel.INFO) + def err = new LogOutputStream(logger, LogLevel.ERROR) + + def header = ("Compiling material " + file + "\n").getBytes() + err.write(header) + out.write(header) + project.exec { + standardOutput out + errorOutput err executable "${matcPath}" args('-O', '-p', 'mobile', '-o', getOutputFile(file), file) } diff --git a/android/filament-android/CMakeLists.txt b/android/filament-android/CMakeLists.txt index 01ad24eb24..8522ded64b 100644 --- a/android/filament-android/CMakeLists.txt +++ b/android/filament-android/CMakeLists.txt @@ -46,6 +46,7 @@ add_library(filament-jni SHARED src/main/cpp/LightManager.cpp src/main/cpp/Material.cpp src/main/cpp/MaterialInstance.cpp + src/main/cpp/MathUtils.cpp src/main/cpp/RenderableManager.cpp src/main/cpp/Renderer.cpp src/main/cpp/Scene.cpp diff --git a/android/filament-android/src/main/cpp/MathUtils.cpp b/android/filament-android/src/main/cpp/MathUtils.cpp new file mode 100644 index 0000000000..05b33fbd7b --- /dev/null +++ b/android/filament-android/src/main/cpp/MathUtils.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +using namespace math; + +extern "C" JNIEXPORT void JNICALL +Java_com_google_android_filament_MathUtils_nPackTangentFrame(JNIEnv *env, jclass, + jfloat tangentX, jfloat tangentY, jfloat tangentZ, + jfloat bitangentX, jfloat bitangentY, jfloat bitangentZ, + jfloat normalX, jfloat normalY, jfloat normalZ, + jfloatArray quaternion_, jint offset) { + + float3 tangent{tangentX, tangentY, tangentZ}; + float3 bitangent{bitangentX, bitangentY, bitangentZ}; + float3 normal{normalX, normalY, normalZ}; + quatf q = mat3f::packTangentFrame({tangent, bitangent, normal}); + + env->SetFloatArrayRegion(quaternion_, offset, 4, + reinterpret_cast(&q)); +} diff --git a/android/filament-android/src/main/java/com/google/android/filament/MathUtils.java b/android/filament-android/src/main/java/com/google/android/filament/MathUtils.java new file mode 100644 index 0000000000..25abfe4652 --- /dev/null +++ b/android/filament-android/src/main/java/com/google/android/filament/MathUtils.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.android.filament; + +import android.support.annotation.IntRange; +import android.support.annotation.NonNull; +import android.support.annotation.Size; + +public final class MathUtils { + private MathUtils() { } + + public static void packTangentFrame( + float tangentX, float tangentY, float tangentZ, + float bitangentX, float bitangentY, float bitangentZ, + float normalX, float normalY, float normalZ, + @NonNull @Size(min = 4) float[] quaternion) { + nPackTangentFrame( + tangentX, tangentY, tangentZ, + bitangentX, bitangentY, bitangentZ, + normalX, normalY, normalZ, quaternion, 0); + } + + public static void packTangentFrame( + float tangentX, float tangentY, float tangentZ, + float bitangentX, float bitangentY, float bitangentZ, + float normalX, float normalY, float normalZ, + @NonNull @Size(min = 4) float[] quaternion, @IntRange(from = 0) int offset) { + nPackTangentFrame(tangentX, tangentY, tangentZ, + bitangentX, bitangentY, bitangentZ, + normalX, normalY, normalZ, quaternion, offset); + } + + private static native void nPackTangentFrame( + float tangentX, float tangentY, float tangentZ, + float bitangentX, float bitangentY, float bitangentZ, + float normalX, float normalY, float normalZ, + @NonNull @Size(min = 4) float[] quaternion, @IntRange(from = 0) int offset); +} diff --git a/android/samples/README.md b/android/samples/README.md index b93c95e5b7..3ebac59244 100644 --- a/android/samples/README.md +++ b/android/samples/README.md @@ -3,7 +3,8 @@ This directory contains several sample Android applications that demonstrate how to use the Filament APIs: -- `hello-triangle`: Minimal example showing how to setup a rendering surface for Filament +- `hello-triangle`: Minimal example showing how to setup a rendering surface for Filament +- `lit-cube`: Shows how to create a light and a mesh with the attributes required for lighting ## Prerequisites diff --git a/android/samples/hello-triangle/.gitignore b/android/samples/hello-triangle/.gitignore index 58c0c92c56..298586a99a 100644 --- a/android/samples/hello-triangle/.gitignore +++ b/android/samples/hello-triangle/.gitignore @@ -8,4 +8,5 @@ .DS_Store /build /captures +/app/src/main/assets/materials/*.filamat .externalNativeBuild diff --git a/android/samples/hello-triangle/app/src/main/assets/materials/baked_color.filamat b/android/samples/hello-triangle/app/src/main/assets/materials/baked_color.filamat deleted file mode 100644 index b67b1a5ba8..0000000000 Binary files a/android/samples/hello-triangle/app/src/main/assets/materials/baked_color.filamat and /dev/null differ diff --git a/android/samples/lit-cube/.gitignore b/android/samples/lit-cube/.gitignore new file mode 100644 index 0000000000..298586a99a --- /dev/null +++ b/android/samples/lit-cube/.gitignore @@ -0,0 +1,12 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +/.idea/caches +/.idea/gradle.xml +.DS_Store +/build +/captures +/app/src/main/assets/materials/*.filamat +.externalNativeBuild diff --git a/android/samples/lit-cube/app/.gitignore b/android/samples/lit-cube/app/.gitignore new file mode 100644 index 0000000000..796b96d1c4 --- /dev/null +++ b/android/samples/lit-cube/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/android/samples/lit-cube/app/build.gradle b/android/samples/lit-cube/app/build.gradle new file mode 100644 index 0000000000..293364d567 --- /dev/null +++ b/android/samples/lit-cube/app/build.gradle @@ -0,0 +1,72 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' + +apply from: '../../../build/filament-tasks.gradle' + +preBuild.dependsOn compileMaterials + +android { + compileSdkVersion 28 + defaultConfig { + applicationId "com.google.android.filament.litcube" + minSdkVersion 21 + targetSdkVersion 28 + versionCode 1 + versionName "1.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + // Filament comes with native code, the following declarations + // can be used to generate architecture specific APKs + flavorDimensions 'cpuArch' + productFlavors { + arm8 { + dimension 'cpuArch' + ndk { + abiFilters 'arm64-v8a' + } + } + arm7 { + dimension 'cpuArch' + ndk { + abiFilters 'armeabi-v7a' + } + } + x86_64 { + dimension 'cpuArch' + ndk { + abiFilters 'x86_64' + } + } + x86 { + dimension 'cpuArch' + ndk { + abiFilters 'x86' + } + } + universal { + dimension 'cpuArch' + } + } + + // We use the .filamat extension for materials compiled with matc + // Telling aapt to not compress them allows to load them efficiently + aaptOptions { + noCompress 'filamat' + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + + // Depend on Filament + implementation 'com.google.android.filament:filament-android' +} diff --git a/android/samples/lit-cube/app/proguard-rules.pro b/android/samples/lit-cube/app/proguard-rules.pro new file mode 100644 index 0000000000..f1b424510d --- /dev/null +++ b/android/samples/lit-cube/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/android/samples/lit-cube/app/src/main/AndroidManifest.xml b/android/samples/lit-cube/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..6e6967cfcc --- /dev/null +++ b/android/samples/lit-cube/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + diff --git a/android/samples/lit-cube/app/src/main/java/com/google/android/filament/litcube/MainActivity.kt b/android/samples/lit-cube/app/src/main/java/com/google/android/filament/litcube/MainActivity.kt new file mode 100644 index 0000000000..df07514b70 --- /dev/null +++ b/android/samples/lit-cube/app/src/main/java/com/google/android/filament/litcube/MainActivity.kt @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.android.filament.litcube + +import android.animation.ValueAnimator +import android.app.Activity +import android.opengl.Matrix +import android.os.Bundle +import android.view.Choreographer +import android.view.Surface +import android.view.SurfaceView +import android.view.animation.LinearInterpolator + +import com.google.android.filament.* +import com.google.android.filament.RenderableManager.* +import com.google.android.filament.VertexBuffer.* +import com.google.android.filament.android.UiHelper + +import java.io.IOException +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.channels.Channels + +class MainActivity : Activity() { + // Make sure to initialize Filament first + // This loads the JNI library needed by most API calls + companion object { + init { + Filament.init() + } + } + + // The View we want to render into + private lateinit var surfaceView: SurfaceView + // UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture + private lateinit var uiHelper: UiHelper + // Choreographer is used to schedule new frames + private lateinit var choreographer: Choreographer + + // Engine creates and destroys Filament resources + // Each engine must be accessed from a single thread of your choosing + // Resources cannot be shared across engines + private lateinit var engine: Engine + // A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.) + private lateinit var renderer: Renderer + // A scene holds all the renderable, lights, etc. to be drawn + private lateinit var scene: Scene + // A view defines a viewport, a scene and a camera for rendering + private lateinit var view: View + // Should be pretty obvious :) + private lateinit var camera: Camera + + private lateinit var material: Material + private lateinit var materialInstance: MaterialInstance + private lateinit var vertexBuffer: VertexBuffer + private lateinit var indexBuffer: IndexBuffer + + // Filament entity representing a renderable object + @Entity private var renderable = 0 + @Entity private var light = 0 + + // A swap chain is Filament's representation of a surface + private var swapChain: SwapChain? = null + + // Performs the rendering and schedules new frames + private val frameScheduler = FrameCallback() + + private val animator = ValueAnimator.ofFloat(0.0f, 360.0f) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + surfaceView = SurfaceView(this) + setContentView(surfaceView) + + choreographer = Choreographer.getInstance() + + setupSurfaceView() + setupFilament() + setupView() + setupScene() + } + + private fun setupSurfaceView() { + uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) + uiHelper.renderCallback = SurfaceCallback() + + // NOTE: To choose a specific rendering resolution, add the following line: + // uiHelper.setDesiredSize(1280, 720) + + uiHelper.attachTo(surfaceView) + } + + private fun setupFilament() { + engine = Engine.create() + renderer = engine.createRenderer() + scene = engine.createScene() + view = engine.createView() + camera = engine.createCamera() + } + + private fun setupView() { + // Clear the background to middle-grey + // Setting up a clear color is useful for debugging but usually + // unnecessary when using a skybox + view.setClearColor(0.035f, 0.035f, 0.035f, 1.0f) + + // NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference + // view.isPostProcessingEnabled = false + + // Tell the view which camera we want to use + view.camera = camera + + // Tell the view which scene we want to render + view.scene = scene + } + + private fun setupScene() { + loadMaterial() + setupMaterial() + createMesh() + + // To create a renderable we first create a generic entity + renderable = EntityManager.get().create() + + // We then create a renderable component on that entity + // A renderable is made of several primitives; in this case we declare only 1 + // If we wanted each face of the cube to have a different material, we could + // declare 6 primitives (1 per face) and give each of them a different material + // instance, setup with different parameters + RenderableManager.Builder(1) + // Overall bounding box of the renderable + .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f)) + // Sets the mesh data of the first primitive, 6 faces of 6 indices each + .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6) + // Sets the material of the first primitive + .material(0, materialInstance) + .build(engine, renderable) + + // Add the entity to the scene to render it + scene.addEntity(renderable) + + // We now need a light, let's create a directional light + light = EntityManager.get().create() + + // Create a color from a temperature (5,500K) + val (r, g, b) = Colors.cct(5_500.0f) + LightManager.Builder(LightManager.Type.DIRECTIONAL) + .color(r, g, b) + // Intensity of the sun in lux on a clear day + .intensity(110_000.0f) + // The direction is normalized on our behalf + .direction(0.0f, -0.5f, 1.0f) + .castShadows(true) + .build(engine, light) + + // Add the entity to the scene to light it + scene.addEntity(light) + + // Set the exposure on the camera, this exposure follows the sunny f/16 rule + // Since we've defined a light that has the same intensity as the sun, it + // guarantees a proper exposure + camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f) + + // Move the camera back to see the object + camera.lookAt(0.0, 3.0, -4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) + + startAnimation() + } + + private fun loadMaterial() { + readAsset("materials/lit.filamat")?.let { + material = Material.Builder().payload(it, it.remaining()).build(engine) + } + } + + private fun setupMaterial() { + // Create an instance of the material to set different parameters on it + materialInstance = material.createInstance() + // Specify that our color is in sRGB so the conversion to linear + // is done automatically for us. If you already have a linear color + // you can pass it directly, or use Colors.RgbType.LINEAR + materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f) + // The default value is always 0, but it doesn't hurt to be clear about our intentions + // Here we are defining a dielectric material + materialInstance.setParameter("metallic", 0.0f) + // We increase the roughness to spread the specular highlights + materialInstance.setParameter("roughness", 0.3f) + } + + private fun createMesh() { + val floatSize = 4 + val shortSize = 2 + // A vertex is a position + a tangent frame: + // 3 floats for XYZ position, 4 floats for normal+tangents (quaternion) + val vertexSize = 3 * floatSize + 4 * floatSize + + // Define a vertex and a function to put a vertex in a ByteBuffer + @Suppress("ArrayInDataClass") + data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray) + fun ByteBuffer.put(v: Vertex): ByteBuffer { + putFloat(v.x) + putFloat(v.y) + putFloat(v.z) + v.tangents.forEach { putFloat(it) } + return this + } + + // 6 faces, 4 vertices per face + val vertexCount = 6 * 4 + + // Create tangent frames, one per face + val tfPX = FloatArray(4) + val tfNX = FloatArray(4) + val tfPY = FloatArray(4) + val tfNY = FloatArray(4) + val tfPZ = FloatArray(4) + val tfNZ = FloatArray(4) + + MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX) + MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX) + MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY) + MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY) + MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ) + MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ) + + val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) + // It is important to respect the native byte order + .order(ByteOrder.nativeOrder()) + // Face -Z + .put(Vertex(-1.0f, -1.0f, -1.0f, tfNZ)) + .put(Vertex(-1.0f, 1.0f, -1.0f, tfNZ)) + .put(Vertex( 1.0f, 1.0f, -1.0f, tfNZ)) + .put(Vertex( 1.0f, -1.0f, -1.0f, tfNZ)) + // Face +X + .put(Vertex( 1.0f, -1.0f, -1.0f, tfPX)) + .put(Vertex( 1.0f, 1.0f, -1.0f, tfPX)) + .put(Vertex( 1.0f, 1.0f, 1.0f, tfPX)) + .put(Vertex( 1.0f, -1.0f, 1.0f, tfPX)) + // Face +Z + .put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ)) + .put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ)) + .put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ)) + .put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ)) + // Face -X + .put(Vertex(-1.0f, -1.0f, 1.0f, tfNX)) + .put(Vertex(-1.0f, 1.0f, 1.0f, tfNX)) + .put(Vertex(-1.0f, 1.0f, -1.0f, tfNX)) + .put(Vertex(-1.0f, -1.0f, -1.0f, tfNX)) + // Face -Y + .put(Vertex(-1.0f, -1.0f, -1.0f, tfNY)) + .put(Vertex(-1.0f, -1.0f, 1.0f, tfNY)) + .put(Vertex( 1.0f, -1.0f, 1.0f, tfNY)) + .put(Vertex( 1.0f, -1.0f, -1.0f, tfNY)) + // Face +Y + .put(Vertex(-1.0f, 1.0f, -1.0f, tfPY)) + .put(Vertex(-1.0f, 1.0f, 1.0f, tfPY)) + .put(Vertex( 1.0f, 1.0f, 1.0f, tfPY)) + .put(Vertex( 1.0f, 1.0f, -1.0f, tfPY)) + // Make sure the cursor is pointing in the right place in the byte buffer + .flip() + + // Declare the layout of our mesh + vertexBuffer = VertexBuffer.Builder() + .bufferCount(1) + .vertexCount(vertexCount) + // Because we interleave position and color data we must specify offset and stride + // We could use de-interleaved data by declaring two buffers and giving each + // attribute a different buffer index + .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) + .attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize) + .build(engine) + + // Feed the vertex data to the mesh + // We only set 1 buffer because the data is interleaved + vertexBuffer.setBufferAt(engine, 0, vertexData) + + // Create the indices + val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize) + .order(ByteOrder.nativeOrder()) + (0..5).forEach { + val i = (it * 4).toShort() + indexData + .putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort()) + .putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort()) + } + indexData.flip() + + // 6 faces, 2 triangles per face, + indexBuffer = IndexBuffer.Builder() + .indexCount(vertexCount * 2) + .bufferType(IndexBuffer.Builder.IndexType.USHORT) + .build(engine) + indexBuffer.setBuffer(engine, indexData) + } + + private fun startAnimation() { + // Animate the triangle + animator.interpolator = LinearInterpolator() + animator.duration = 6000 + animator.repeatMode = ValueAnimator.RESTART + animator.repeatCount = ValueAnimator.INFINITE + animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { + val transformMatrix = FloatArray(16) + override fun onAnimationUpdate(a: ValueAnimator) { + Matrix.setRotateM(transformMatrix, 0, a.animatedValue as Float, 0.0f, 1.0f, 0.0f) + val tcm = engine.transformManager + tcm.setTransform(tcm.getInstance(renderable), transformMatrix) + } + }) + animator.start() + } + + override fun onResume() { + super.onResume() + choreographer.postFrameCallback(frameScheduler) + animator.start() + } + + override fun onPause() { + super.onPause() + choreographer.removeFrameCallback(frameScheduler) + animator.cancel() + } + + override fun onDestroy() { + super.onDestroy() + // Always detach the surface before destroying the engine + uiHelper.detach() + + // This ensures that all the commands we've sent to Filament have + // been processed before we attempt to destroy anything + Fence.waitAndDestroy(engine.createFence(Fence.Type.SOFT), Fence.Mode.FLUSH) + + // Cleanup all resources + engine.destroyEntity(light) + engine.destroyEntity(renderable) + engine.destroyRenderer(renderer) + engine.destroyVertexBuffer(vertexBuffer) + engine.destroyIndexBuffer(indexBuffer) + engine.destroyMaterialInstance(materialInstance) + engine.destroyMaterial(material) + engine.destroyView(view) + engine.destroyScene(scene) + engine.destroyCamera(camera) + + // Destroying the engine will free up any resource you may have forgotten + // to destroy, but it's recommended to do the cleanup properly + engine.destroy() + } + + inner class FrameCallback : Choreographer.FrameCallback { + override fun doFrame(frameTimeNanos: Long) { + // Schedule the next frame + choreographer.postFrameCallback(this) + + // This check guarantees that we have a swap chain + if (uiHelper.isReadyToRender) { + // If beginFrame() returns false you should skip the frame + // This means you are sending frames too quickly to the GPU + if (renderer.beginFrame(swapChain!!)) { + renderer.render(view) + renderer.endFrame() + } + } + } + } + + inner class SurfaceCallback : UiHelper.RendererCallback { + override fun onNativeWindowChanged(surface: Surface) { + swapChain?.let { engine.destroySwapChain(it) } + swapChain = engine.createSwapChain(surface) + } + + override fun onDetachedFromSurface() { + swapChain?.let { + engine.destroySwapChain(it) + // Required to ensure we don't return before Filament is done executing the + // destroySwapChain command, otherwise Android might destroy the Surface + // too early + engine.flushAndWait() + swapChain = null + } + } + + override fun onResized(width: Int, height: Int) { + val aspect = width.toDouble() / height.toDouble() + camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL) + + view.viewport = Viewport(0, 0, width, height) + } + } + + private fun readAsset(assetName: String): ByteBuffer? { + var dst: ByteBuffer? = null + try { + assets.openFd(assetName).use { fd -> + val input = fd.createInputStream() + + dst = ByteBuffer.allocate(fd.length.toInt()) + + val src = Channels.newChannel(input) + + src.read(dst) + src.close() + dst!!.rewind() + } + } catch (e: IOException) { + e.printStackTrace() + } + + return dst + } +} diff --git a/android/samples/lit-cube/app/src/main/materials/lit.mat b/android/samples/lit-cube/app/src/main/materials/lit.mat new file mode 100644 index 0000000000..fbf71fa278 --- /dev/null +++ b/android/samples/lit-cube/app/src/main/materials/lit.mat @@ -0,0 +1,53 @@ +// Simple lit material that defines 3 parameters: +// - baseColor +// - roughness +// - metallic +// +// These parameters can be used by the application to change the appearance of the material. +// +// This source material must be compiled to a binary material using the matc tool. +// The command used to compile this material is: +// matc -p mobile -a opengl -O -o app/src/main/assets/lit.filamat app/src/materials/lit.mat +// +// See build.gradle for an example of how to compile materials automatically +// Please refer to the documentation for more information about matc and the materials system. + +material { + name : lit, + + // Dynamic lighting is enabled on this material + shadingModel : lit, + + // We don't need to declare a "requires" array, lit materials + // always requires the "tangents" vertex attribute (the normal + // is required for lighting, tangent/bitangent for normal mapping + // and anisotropy) + + // List of parameters exposed by this material + parameters : [ + // The color must be passed in linear space, not sRGB + { + type : float3, + name : baseColor + }, + { + type : float, + name : roughness + }, + { + type : float, + name : metallic + } + ], +} + +fragment { + void material(inout MaterialInputs material) { + prepareMaterial(material); + + // Nothing fancy here, we simply copy the parameters + material.baseColor.rgb = materialParams.baseColor; + material.roughness = materialParams.roughness; + material.metallic = materialParams.metallic; + } +} diff --git a/android/samples/lit-cube/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/android/samples/lit-cube/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000000..b1517edf49 --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/android/samples/lit-cube/app/src/main/res/drawable/ic_launcher_background.xml b/android/samples/lit-cube/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000000..88e31872fe --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,171 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000000..6d5e5d094c --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000000..6d5e5d094c --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000..a2f5908281 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000000..1b52399808 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000..ff10afd6e1 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000000..115a4c768a Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000..dcd3cd8083 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000000..459ca609d3 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000..8ca12fe024 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000..8e19b410a1 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000..b824ebdd48 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000..4c19a13c23 Binary files /dev/null and b/android/samples/lit-cube/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/android/samples/lit-cube/app/src/main/res/values/colors.xml b/android/samples/lit-cube/app/src/main/res/values/colors.xml new file mode 100644 index 0000000000..5a077b3a78 --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/android/samples/lit-cube/app/src/main/res/values/strings.xml b/android/samples/lit-cube/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000..1b86ac0a01 --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Lit Cube + diff --git a/android/samples/lit-cube/app/src/main/res/values/styles.xml b/android/samples/lit-cube/app/src/main/res/values/styles.xml new file mode 100644 index 0000000000..a7a06158ff --- /dev/null +++ b/android/samples/lit-cube/app/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/android/samples/lit-cube/build.gradle b/android/samples/lit-cube/build.gradle new file mode 100644 index 0000000000..51001877c4 --- /dev/null +++ b/android/samples/lit-cube/build.gradle @@ -0,0 +1,27 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + ext.kotlin_version = '1.2.60' + repositories { + google() + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:3.1.4' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + jcenter() + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/samples/lit-cube/gradle.properties b/android/samples/lit-cube/gradle.properties new file mode 100644 index 0000000000..743d692ce1 --- /dev/null +++ b/android/samples/lit-cube/gradle.properties @@ -0,0 +1,13 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx1536m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true diff --git a/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.jar b/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..7a3265ee94 Binary files /dev/null and b/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.properties b/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..d4da7d2692 --- /dev/null +++ b/android/samples/lit-cube/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Aug 28 15:45:13 PDT 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip diff --git a/android/samples/lit-cube/gradlew b/android/samples/lit-cube/gradlew new file mode 100755 index 0000000000..cccdd3d517 --- /dev/null +++ b/android/samples/lit-cube/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/android/samples/lit-cube/gradlew.bat b/android/samples/lit-cube/gradlew.bat new file mode 100644 index 0000000000..e95643d6a2 --- /dev/null +++ b/android/samples/lit-cube/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/samples/lit-cube/settings.gradle b/android/samples/lit-cube/settings.gradle new file mode 100644 index 0000000000..466fef9302 --- /dev/null +++ b/android/samples/lit-cube/settings.gradle @@ -0,0 +1,3 @@ +includeBuild '../../filament-android' + +include ':app' diff --git a/samples/material_sandbox.cpp b/samples/material_sandbox.cpp index 9b3c04ae59..749acacca4 100644 --- a/samples/material_sandbox.cpp +++ b/samples/material_sandbox.cpp @@ -502,7 +502,7 @@ static void gui(filament::Engine* engine, filament::View*) { auto lightInstance = lcm.getInstance(g_light); lcm.setColor(lightInstance, g_lightColor); lcm.setIntensity(lightInstance, g_lightIntensity); - lcm.setDirection(lightInstance, normalize(g_lightDirection)); + lcm.setDirection(lightInstance, g_lightDirection); lcm.setSunAngularRadius(lightInstance, g_sunAngularRadius); lcm.setSunHaloSize(lightInstance, g_sunHaloSize); lcm.setSunHaloFalloff(lightInstance, g_sunHaloFalloff);