SlideShare a Scribd company logo
1 of 81
Download to read offline
The Go gopher was designed by Renée French.
The gopher stickers was made by Takuya Ueda.
Licensed under the Creative Commons 3.0 Attributions license.
Go for Mobile Games
GopherCon 2016, Denver
11th July 2016
Takuya Ueda @tenntenn
KLab Inc.
Slide URL: https://goo.gl/cIvTb5
Slide URL: https://goo.gl/cIvTb5
What is this talk about?
● The Basics of Go Mobile
○ Cross-compile and Android device
○ SDK Apps and Native Apps
● Go for Mobile Game
○ Event handling
○ 2D scene graph
● Advanced Topics
○ Distribute apps on Google Play
○ How to use Android API from Go
2
Slide URL: https://goo.gl/cIvTb5
The Basics of Go Mobile
3
● Run on Android Devices
● Cross-compile and cgo
● SDK Apps and Native Apps
Slide URL: https://goo.gl/cIvTb5
Cross-compile
● GOOS and GOARCH
○ Go can cross-compile
○ GOOS indicates target OS
○ GOARCH indicates target architecture
4
# Build for 32bit Windows
$ GOOS=windows GOARCH=386 go build
# Build for arm Linux
$ GOOS=linux GOARCH=arm go build
A linux/arm binary also works on android devices.
The Basics of Go Mobile / Cross-compile and cgo
Slide URL: https://goo.gl/cIvTb5
Webserver on Android Devices
Watch at Youtube Source Code
Android
Shell on Mac
adb shell
The Basics of Go Mobile / Webserver on Androind Devices 5
Slide URL: https://goo.gl/cIvTb5
cgo
● C codes into Go codes
import "unsafe"
/*
#include <stdio.h>
#include <stdlib.h>
void hello(char *s) { printf("Hello, %sn", s); }
*/
import "C"
func main() {
str := C.CString("GopherCon")
C.hello(str)
C.free(unsafe.Pointer(str))
}
Comments before import "C"
would be built as C codes
Call C’s function from Go code
The Basics of Go Mobile / Cross Compile and cgo 6
Slide URL: https://goo.gl/cIvTb5
cgo for Android
● cgo codes also can be cross-compiled
7
$ CGO_ENABLED=1
CC=arm-linux-androideabi-gcc
GOOS=android
GOARCH=arm
GOARM=7
go build -buildmode=pie hellocgo.go
$ adb push hellocgo /data/local/tmp
$ chmod 755 /data/local/tmp/hellocgo
$ /data/local/tmp/hellocgo
Hello, GopherCon
GOOS should be android
when CGO_ENABLED is 1.
Enable cgo at cross-compiling
adb shell
PC
The Basics of Go Mobile / Cross Compile and cgo
Slide URL: https://goo.gl/cIvTb5
buildmode
● Change output formats
○ archive, c-archive
■ build to C archive (.a file)
○ shared, c-shared
■ build to shared library (.so file)
○ exe
■ build to executable file
○ pie
■ build to PIE style executable file
archive and shared ignore
main package
Go can build to .so files for Android
8The Basics of Go Mobile / Cross Compile and cgo
Slide URL: https://goo.gl/cIvTb5
Go Mobile
● What is Go Mobile?
○ Go Mobile is a toolkit for Mobile Platform (Android and
iOS) with Go.
● How Go Mobile works?
○ Go Mobile provides bindings of Android and iOS
through cgo.
9
Go C
Java
Obj-C
JNIcgo
Android
iOS
The Basics of Go Mobile / Go Mobile
Slide URL: https://goo.gl/cIvTb5
Go Mobile
The Basics of Go Mobile / Go Mobile 10
https://github.com/golang/mobile
Slide URL: https://goo.gl/cIvTb5
Installation
● Install gomobile comand
● Initialize the build tool chain
○ gomobile init initializes the build tool chain for
mobile apps. Android NDK is also installed.
11
$ gomobile init -v
$ ls $GOPATH/pkg/gomobile
android-ndk-r12 pkg_android_386 pkg_android_arm
pkg_darwin_amd64 pkg_darwin_arm64 dl
pkg_android_amd64 pkg_android_arm64 pkg_darwin_arm version
$ go get golang.org/x/mobile/cmd/gomobile
The Basics of Go Mobile / Installation
Slide URL: https://goo.gl/cIvTb5
gomobile command
gomobile command provides sub-commands.
● Sub-commands
12
bind build a library for Android and iOS
build compile Android APK and iOS app
clean remove object files and cached gomobile files
init install android compiler toolchain
install compile android APK and install on device
version print version
The Basics of Go Mobile / gomobile command
Slide URL: https://goo.gl/cIvTb5
SDK Apps and Native Apps
Go Mobile provides two ways to develop mobile
apps.
■ SDK Apps
● Write common funcations in Go as a library
● Write UI and platform dependent functions in Java for
Android and Objective-C/Swift for iOS
■ Native Apps
● Write UI and all codes in Go
13The Basics of Go Mobile / SDK Apps and Native Apps
Slide URL: https://goo.gl/cIvTb5
Go
aar file
SDK Apps and Native Apps
Binding Classes (Java)
Shared library (.so)
Java
● SDK Apps for Android
● Native Apps for Android
apk file
Go
GoNativeActivity
Shared library (.so)
UI, IAB, ...
As a library
UI, audio, ...
gomobile bind
gomobile build
The Basics of Go Mobile / SDK Apps and Native Apps 14
Slide URL: https://goo.gl/cIvTb5
Go
aar file
SDK Apps and Native Apps
Binding Classes (Java)
Shared library (.so)
Java
● SDK Apps for Android
● Native Apps for Android
apk file
Go
GoNativeActivity
Shared library (.so)
UI, IAB, ...
As a library
UI, audio, ...
gomobile bind
gomobile build
The Basics of Go Mobile / SDK Apps and Native Apps 15
Slide URL: https://goo.gl/cIvTb5
SDK App example: Ivy
● Ivy big number calculator (source code)
○ Interpriter for APL-like language
○ Android App and iOS App use a same engine
○ The engine is written in Go by Rob Pike
16
Google Play App Store
The Basics of Go Mobile / SDK App example: Ivy
Slide URL: https://goo.gl/cIvTb5
gomobile bind
● Generate an Android Archive (.aar)
○ Including a shared library (.so) written in Go
○ Including a JAR file which is bult Java bindings
● Develop with Android Studio Plugin
○ Runs gomobile bind
○ Links to a generated .aar file
$ gomobile bind [-target ios|android] mypkg
17The Basics of Go Mobile / gomobile bind
Slide URL: https://goo.gl/cIvTb5
Contents of AAR
18The Basics of Go Mobile / Contents of AAR
$ gomobile bind sample
$ unzip -Z1 sample.aar
AndroidManifest.xml
proguard.txt
classes.jar
jni/armeabi-v7a/libgojni.so
jni/arm64-v8a/libgojni.so
jni/x86/libgojni.so
jni/x86_64/libgojni.so
R.txt
res/
Compiled Java code
Compiled
Go/C code
Slide URL: https://goo.gl/cIvTb5
Binding
Use SDK from Application
19The Basics of Go Mobile / Use SDK from Application
Java code
Application Code
(Java)
C code
Go/cgo
JNI Generated by
gomobile bind
SDK Code
(Go)
cgo
Slide URL: https://goo.gl/cIvTb5
Binding Go and Java
20The Basics of Go Mobile / Binding Go and Java
Package Abstrct Class
Struct Inner Class
Struct Field
Getter/Setter
(Native)
Method Method
(Native)
Pacakge Function Static Method
Go Java
Slide URL: https://goo.gl/cIvTb5
Binding Go and Java
21The Basics of Go Mobile / Binding Go and Java
package sample
func Hello() string { return "Hello" }
type MyStruct struct { Str string }
func (s MyStruct) MyMethod() string { return s.Str }
public abstract class Sample {
// ...
private Sample() {} // uninstantiable
public static final class MyStruct extends Seq.Proxy {
public final native String getStr();
public final native void setStr(String v);
public native String MyMethod();
// ...
}
public static native String Hello();
}
Java
Go
Struct
Field
Method
Package Function
Slide URL: https://goo.gl/cIvTb5
Type restrictions
The Basics of Go Mobile / 22
● Signed integer and floating point type
● String and boolean type
● Byte slice type
● Any functions
○ parameter and result types must be supported types
○ results are 0, 1 or 2 (2nd result must be an error type)
● Any struct type
○ all fields and methods must be supported types
● Any interface
○ all methods must be supported types
Slide URL: https://goo.gl/cIvTb5
Go
aar file
SDK Apps and Native Apps
Binding Classes (Java)
Shared library (.so)
Java
● SDK Apps for Android
● Native Apps for Android
apk file
Go
GoNativeActivity
Shared library (.so)
UI, IAB, ...
As a library
UI, audio, ...
gomobile bind
gomobile build
The Basics of Go Mobile / SDK Apps and Native Apps 23
Slide URL: https://goo.gl/cIvTb5
gomobile build and gomobile install
● Generate an .apk file
○ Including a shared library (.so) written in Go
○ Including a dex file which is bult GoNativeActivity
● Build and Install
○ Run gomobile build and adb install
○ Android Only
$ gomobile build [-target ios|android] mainpkg
24The Basics of Go Mobile / gomobile build and gomobile install
$ gomobile install [-target ios|android] mainpkg
Slide URL: https://goo.gl/cIvTb5
Contents of APK
25The Basics of Go Mobile / Contents of APK
$ gomobile build golang.org/x/mobile/example/flappy
$ unzip -Z1 flappy.apk
AndroidManifest.xml
classes.dex
lib/armeabi-v7a/libflappy.so
lib/arm64-v8a/libflappy.so
lib/x86/libflappy.so
lib/x86_64/libflappy.so
assets/README
assets/sprite.png
META-INF/MANIFEST.MF
META-INF/CERT.SF
META-INF/CERT.RSA
Compiled GoNativeActivity.java
Compiled
Go/C code
Slide URL: https://goo.gl/cIvTb5
x/mobile/app
How Native App works?
26The Basics of Go Mobile / How Native App works?
GoNativeActivity
C code
Go/cgo
JNI
Application Code
(Go)
cgo
exntends
NativeActivity
Slide URL: https://goo.gl/cIvTb5
Go for Mobile Game
27
● Basic event loop and paint events
● Size Event and Lifecycle Event
● 2D Scene Graph
● Touch Event
Slide URL: https://goo.gl/cIvTb5
Go for Mobile Game
Go for Mobile Game / Go for Mobile Game 28
● Flappy Gopher
○ by Andrew Gerrand
○ for Go Conference 2015 Winter
○ Source Code
● How it works?
○ gomobile build
○ render images and animate
○ handle touch events
$ go get golang.org/x/mobile/cmd/gomobile && gomobile init
$ gomobile install golang.org/x/mobile/example/flappy
Slide URL: https://goo.gl/cIvTb5
Packages
● Rendering
○ OpenGL ES2 : gl, exp/gl/glutil
○ 2D Scene Graph : exp/sprite
● Event
○ Touch Event : event/touch
○ Lifecycle Event : event/lifecycle
● Sensors : exp/sensor
○ Accelerometer, Gyroscope, Magnetometer
● Audio : exp/audio
Go for Mobile Game / Packages 29
Package Name
Slide URL: https://goo.gl/cIvTb5
app.Main
● app.Main receives an entry point function
Go for Mobile Game / app.Main 30
func main() {
app.Main(func(a app.App) {
// Event Loop
})
}
Slide URL: https://goo.gl/cIvTb5
Event Loop
● Receive events through a channel
Go for Mobile Game / Event Loop 31
Event Loop
Paint Event
Touch Event
Life Cycle Event
Switch
by Event Types
CASE
CASE
CASE
Slide URL: https://goo.gl/cIvTb5
Event Channel
● Receive events from App.Events() channel
Go for Mobile Game / Event Channel 32
// Events() <-chan interface{}
for e := range a.Events() { // a is app.App
switch e := a.Filter(e).(type) {
case paint.Event:
case touch.Event:
case lifecycle.Event:
}
}
Slide URL: https://goo.gl/cIvTb5
Event Types
Go for Mobile Game / Event Types 33
paint.Event Rendering event
touch.Event Screen touch event
lifecycle.Event
App’s lifecycle event
Such as OnStart and OnStop on Android
size.Event
dimension, physical resolution and orientation
changed event
mouse.Event Mouse event
key.Event Only hardware keyboard event
Slide URL: https://goo.gl/cIvTb5
How to render images
Go for Mobile Game / How to render images 34
● Construct a scene graph
○ exp/sprite package provides 2D scene graph
● Load a texture
○ asset package loads a image as a texture
● Set a sub-texture to a node
○ A node of scene graph can be set a sub-texture (part of
a texture)
● Render a scene graph
○ sprite.Engine type has Render method
Slide URL: https://goo.gl/cIvTb5
2D scene graph
Go for Mobile Game / 2D scene graph 35
scene
gopher
Rendering
Engine
ground1
Node
TextureSub-texture
Game SceneScene Graph Render
Set Load
Slide URL: https://goo.gl/cIvTb5
Construct a scene graph
● Create a rendering engine
● Create and register a node
● Append a child node
Go for Mobile Game / Construct a scene graph 36
images = glutil.NewImages(glctx)
eng = glsprite.Engine(images)
node := &sprite.Node{}
eng.Register(node)
parentNode.AppendChild(childNode)
glctx is
a OpenGL context
images maintains
shared state used
by texutres
Slide URL: https://goo.gl/cIvTb5
Load a texture
● Open an asset
● Decode an image
● Load a texture to rendering engine
Go for Mobile Game / Load a texture 37
a, err := asset.Open("gopher.png")
img, err := image.Decode(a)
tex, err := eng.LoadTexture(img)
asset files are put into
assets directory
use image package from
standard packages
Slide URL: https://goo.gl/cIvTb5
Set a sub-texture
● Create a sub-texture
● Set a sub-texture to a node
Go for Mobile Game / Set a sub-texture 38
subtex := sprite.Subtex {
T:tex,
R:iamge.Rect(128, 0, 128, 128)
}
eng.SetSubTex(node, subtex)
Bounds on a source texture
Slide URL: https://goo.gl/cIvTb5
Render a scene graph
● Render receives a root node of a scene graph
Go for Mobile Game / Render a scene graph 39
// compute current frame in 60FPS
since := time.Since(startTime)
now := clock.Time(since * 60 / time.Second)
// scene *sprite.Node
// now clock.Time
// sz event.Size
eng.Render(scene, now, sz)
Root Node
Screen Size and Orientation
Slide URL: https://goo.gl/cIvTb5
Handling Events
Go for Mobile Game / Handling Events 40
Handle Size Event
Handle Lifecycle Event
Handle Paint Event
Get Screen Size and
Orientation
Get OpenGL Context
and Construct a Scene Graph
Render a Scene Graph
Slide URL: https://goo.gl/cIvTb5
Handle Size Event
Go for Mobile Game / Handle Size Event 41
app.Main(func(a app.App) {
var glctx gl.Context
var sz size.Event
for e := range a.Events() {
switch e := a.Filter(e).(type) {
case size.Event:
sz = e
// ...
}
}
})
type Event struct {
WidthPx, HeightPx int
WidthPt, HeightPt geom.Pt
PixelsPerPt float32
Orientation Orientation
}
Slide URL: https://goo.gl/cIvTb5
Handle Lifecycle Event
Go for Mobile Game / Handle Lifecycle Event 42
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
glctx, _ = e.DrawContext.(gl.Context)
onStart(glctx)
a.Send(paint.Event{})
case lifecycle.CrossOff:
onStop()
glctx = nil
}
Get a OpenGL Context
StageDead
StageAlive
StageVisible
StageFocused
Slide URL: https://goo.gl/cIvTb5
Handle Lifecycle Event
Go for Mobile Game / Handle Lifecycle Event 43
StageDead
StageAlive
StageVisible
StageFocused
From
To
type Event struct {
From, To Stage
DrawContext interface{}
}
lifecycle.Event
e.Crosses(StageVisible)
== CrossOn
Slide URL: https://goo.gl/cIvTb5
Handle Lifecycle Event
Go for Mobile Game / Handle Lifecycle Event 44
StageDead
StageAlive
StageVisible
StageFocused
To
From
type Event struct {
From, To Stage
DrawContext interface{}
}
lifecycle.Event
e.Crosses(StageAlive)
== CrossOff
Slide URL: https://goo.gl/cIvTb5
Handle Paint Event
Go for Mobile Game / Handle Paint Event 45
Arrange Nodes
Set Sub-texture
Render Scene Graph
Set an Affine Transformation
Matrix Relative to Parent Node
Change images for animations
Slide URL: https://goo.gl/cIvTb5
Arrange a Scene Graph Node
Go for Mobile Game / Arrange a Scene Graph Node 46
type Arranger interface{
Arrange(e Engine, n *Node, t clock.Time)
}
// For convinience, arrangeFunc implements Arrange interface
type arrangeFunc func(e Engine, n *Node, t clock.Time)
func (f arrangeFunc) Arrange(e Engine, n *Node, t clock.Time) {
f(e, n, t)
}
● sprite.Arrranger has Arrange method
which is called each frame by rendering engine
Slide URL: https://goo.gl/cIvTb5
Set Arranger to a Scene Graph Node
Go for Mobile Game / Set Arranger to a Scene Graph Node 47
// Called each frame
func arrange(e sprite.Engine,
n *sprite.Node,
t clock.Time) {
// Node manupulation
}
// Set a Arranger interface to a node
node.Arranger = arrangerFunc(arrange)
Slide URL: https://goo.gl/cIvTb5
Affine Transformation Matrix
Go for Mobile Game / Affine Transformation Matrix 48
// Scale(2,2) and Translate(5,5)
eng.SetTransform(node, f32.Affine{
{2, 0, 5},
{0, 2, 5},
})
● A scene graph node can set a affine transform
matrix to compute position, scale and rotation
angle
Slide URL: https://goo.gl/cIvTb5
Affine Transform
Go for Mobile Game / Affine Transform 49
● Affine transform from the root node to the child
node
root
n
Translate(5,5)
Scale(2,2)
Translate(10,10)
Scale(100,100)
pos: (5,5)
size: 2pt x 2pt
pos: (25,25)
size: 200pt x 200pt
1pt = 1/72 inch
Base size is 1pt x 1pt
Base position is (0,0)
Base rotation angle is 0
Slide URL: https://goo.gl/cIvTb5
Affine Transform
Go for Mobile Game / Affine Transform 50
root
n
pos: (5,5)
size: 2pt x 2pt
pos: (25,25)
size: 200pt x 200pt
eng.SetTransform(root,
f32.Affine{
{2, 0, 5},
{0, 2, 5},
})
eng.SetTransform(n,
f32.Affine{
{100, 0, 10},
{0, 100, 10},
})
pos: (0,0)
size: 1pt x 1pt
Slide URL: https://goo.gl/cIvTb5
Handle Touch Event
Go for Mobile Game / Handle Touch Event 51
type Event struct {
// Touch location in pixels.
X, Y float32
// Sequence number for each touch.
Sequence Sequence
// Type is the touch type.
// TypeBegin, TypeMove, TypeEnd
Type Type
}
touch.Event
Slide URL: https://goo.gl/cIvTb5
Touch Types and Sequence
Go for Mobile Game / Touch Types and Sequence 52
TypeBegin TypeMove
Same Sequence
TypeEnd
Sequence:1
Multi Touch
Sequence:2
Slide URL: https://goo.gl/cIvTb5
Debug on PC
● Go Mobile’s packages also works fine on PC
(Mac, Windows, Linux).
Go for Mobile Game / Debug on PC 53
$ go build mainpkg
$ ./mainpkg
assets directry should be
placed at working directory
Running on Mac
Slide URL: https://goo.gl/cIvTb5
Restrictions for Native Apps (Android)
● Cannot set own App’s icon
● Only use a debug keystore
● Cannot distribute on Google Play
○ Need to set own App’s icon
○ Need a release keystore
● Cannot use Platform API
○ Cannot use In-app Billing API
○ Cannot use third party API
Go for Mobile Game / Debug on PC 54
Slide URL: https://goo.gl/cIvTb5
Advanced Topics
55
● Distribute apps on Google Play
● Use Platform APIs from Go
Slide URL: https://goo.gl/cIvTb5
Contents of APK
56Advanced Topics / Contents of APK
$ gomobile build golang.org/x/mobile/example/flappy
$ unzip -Z1 flappy.apk
AndroidManifest.xml
classes.dex
lib/armeabi-v7a/libflappy.so
lib/arm64-v8a/libflappy.so
lib/x86/libflappy.so
lib/x86_64/libflappy.so
assets/README
assets/sprite.png
META-INF/MANIFEST.MF
META-INF/CERT.SF
META-INF/CERT.RSA
res directory is not
included into APK
Signature Related Files
Slide URL: https://goo.gl/cIvTb5
Modify APK for Release
57Advanced Topics / Modify APK for Release
gomobile build● Create an APK file for debug
● Expand the APK file by apktool
● Modify the AndroidManifest
○ Add icon setting and Disable debuggable setting
● Add app’s icons and res directory
● Rearchive an APK file by apktool
● Signature with release keystore
● ZIP Align
Slide URL: https://goo.gl/cIvTb5
Expand an APK File
Advanced Topics / Expand an APK File 58
# if you have not installed
$ brew install apktool
$ apktool d flappy.apk # expand
● Use apktool to expand and archive an APK
file
Slide URL: https://goo.gl/cIvTb5
Add App’s Icons
Advanced Topics / Add App’s Icons 59
$ tree flappy/res
flappy/res
├── drawable-hdpi
│ └── ic_launcher.png
...
└── drawable-xxxhdpi
└── ic_launcher.png
● Make a res direcotry and add app’s icons
○ under the expanded APK directory
App’s Icons
Slide URL: https://goo.gl/cIvTb5
Add icon setting
● Add an icon setting to AndroidManifest
● android:icon sepecify icon file name
Advanced Topics / Add icon setting 60
<?xml version="1.0" encoding="utf-8"?>
...
<application android:label="Flappy"
android:icon="@drawable/ic_launcher"
...
Slide URL: https://goo.gl/cIvTb5
Disable debuggable setting
● To upload apk on Google Play, apk should be
built without debuggable="true"
○ We can also use own AndroidManifest.xml by
putting top level directory before building.
Advanced Topics / Disable debuggable setting 61
<?xml version="1.0" encoding="utf-8"?>
...
<application android:label="Flappy" ...
android:debuggable="true"
...
Slide URL: https://goo.gl/cIvTb5
Signiture with Release Keystore
62Advanced Topics / Signiture with Release Keystore
● Re-archive the APK file
● Re-signiture the APK file
$ apktool b flappy
$ cd flappy/dist
$ jarsigner ... -keystore release.keystore 
flappy.apk flappy
$ zipalign -f -v 4 flappy{,_aligned}.apk
$ ls
flappy.pak flappy_aligned.apk
Slide URL: https://goo.gl/cIvTb5
Distribute on Google Play
63Advanced Topics / Distribute on Google Play
Slide URL: https://goo.gl/cIvTb5
Restrictions for Native App (Android)
● Cannot set own App’s icon
● Only use a debug keystore
● Cannot distribute on Google Play
○ Need to set own App’s icon
○ Need a release keystore
● Cannot use Platform API
○ Cannot use In-app Billing API
○ Cannot use third party API
Advanced Topics / Debug on PC 64
OK!
OK!
OK!
Slide URL: https://goo.gl/cIvTb5
Requirement Mobile Games for Business
● In-app Billing
○ Purchase a items in the game
● SNS connection
○ Facebook, Twitter, ...
● Advertisements
● Analytics
○ Google Analytics, Firebase, Facebook Analytics,...
Advanced Topics / Requirement of Mobile Games for Business 65
These APIs are provided
as Java SDK for Android
Slide URL: https://goo.gl/cIvTb5
How to call Android API from Go
Advanced Topics / How to call Android API from 66
● Call Android API through cgo by JNI
○ We should get JavaVM* object in own cgo code
● JavaVM* object is defined in Go Mobile inner
package as current_vm variable
○ x/mobile/internal/mobileinit/ctx_android.go
● We also use current_vm in own cgo code
Slide URL: https://goo.gl/cIvTb5
Call android.util.Log.d
Advanced Topics / Call android.util.Log.d 67
RunOnJVM(func(vm, jniEnv, ctx uintptr) error {
env := (*C.JNIEnv)(unsafe.Pointer(jniEnv))
C.logd(env)
return nil
})
void logd(JNIEnv* env) {
jclass log = (*env)->FindClass(env, "android/util/Log");
jmethodID methodD = (*env)->GetStaticMethodID(
env, log, "d", "(Ljava/lang/String;Ljava/lang/String;)I");
jstring tag = (*env)->NewStringUTF(env, "log");
jstring message = (*env)->NewStringUTF(env, "hi! JVM");
(*env)->CallStaticIntMethod(env, log, methodD, tag, message);
}
Go
C
All Source Code
RunOnJVM is copied from
ctx_android.go
Slide URL: https://goo.gl/cIvTb5
Call own Java Codes from Go codes
Advanced Topics / Call own Java Codes from Go codes 68
● Create a new Android project
● Copy GoNativeActivity and AndroidManifest
from GoMobile repositry to own project
● Write own Java codes
● Write application code in Go
○ Call own Java codes with RunOnJVM
● Build Go code to a shared library
● Copy shared library to own Android project
● Build the Android project Do all processes by hand!
Slide URL: https://goo.gl/cIvTb5
Toast on Go Mobile
Advanced Topics / Toast on Go Mobile 69
Slide URL: https://goo.gl/cIvTb5
Plugin System for Game Engine
Advanced Topics / Plugin System for Game Engine 70
● Most Game Engine has a plugin system
○ Unity, Cocos2d-x, ...
○ Facebook Plugin, In-app Billing Plugin, ...
● Go Mobile needs a plugin system
Application Code
(Go)
Own Plugin
Java/Obj-C code
C code
Go/cgo
Go Mobile
Register
Use
Slide URL: https://goo.gl/cIvTb5
Summaries
● The Basics of Go Mobile
○ Cross-compile and Android device
○ SDK App and Native App
● Go for Mobile Game
○ Event handling
○ 2D scene graph
● Advanced Topics
○ Distribute apps on Google Play
○ How to use Android API from Go
71
Slide URL: https://goo.gl/cIvTb5
Go for Unity Native Plugin
● Unity Native Plugin can be written in Go/cgo
Advanced Topics / Go for Unity Native Plugin 72
Unity
Native Plugin
.so for Android
.a for iOS
Written in GoGo has good packages
to create a communication module!
Slide URL: https://goo.gl/cIvTb5
Go for Unity Native Plugin
Advanced Topics / Go for Unity Native Plugin 73
package main
import "C"
//export Hoge
func Hoge() int {return 100}
func main() {}
#if UNITY_IPHONE
[DllImport("__Internal")]
#else
[DllImport("hoge")]
#endif
private static extern int Hoge();
void Start() {Debug.LogFormat("{0}", Hoge());}
Go
Unity (C#)
Slide URL: https://goo.gl/cIvTb5
Build a Native Plugin for Android
Advanced Topics / Build a Native Plugin for Android 74
$ CGO_ENABLED=1 
CC=arm-linux-androideabi-gcc 
GOOS=android 
GOARCH=arm 
GOARM=7 
go build -buildmode=c-shared  -pkgdir=
$GOPATH/pkg/gomobile/pkg_android_arm 
-o libhoge.so hoge.go
Slide URL: https://goo.gl/cIvTb5
Build a Native Plugin for iOS
Advanced Topics / Build a Native Plugin for iOS 75
GOOS=darwin 
GOARCH=arm 
GOARM=7 
CC=`xcrun --sdk iphoneos -f clang` 
CXX=`xcrun --sdk iphoneos -f clang` 
CGO_CFLAGS="-isysroot `xcrun --sdk iphoneos --show-sdk-
path` -arch armv7 -miphoneos-version-min=6.1" 
CGO_LDFLAGS="-isysroot `xcrun --sdk iphoneos --show-sdk-
path` -arch armv7 -miphoneos-version-min=6.1" 
CGO_ENABLED=1 
go build -pkgdir=$GOPATH/pkg/gomobile/pkg_darwin_arm 
-buildmode=c-archive -tags=ios -o hoge.a hoge.go
Takuya Ueda
@tenntenn
KLab Inc.
76
Takuya Ueda
@tenntenn
KLab Inc.
77
Takuya Ueda
@tenntenn
KLab Inc.
78
Slide URL: https://goo.gl/cIvTb5
Run on Android Devices
79
● Go can build for Android Devices
Android DevicePC
Cross-compile Run on adb shellpush binary
to Android Deivce
$ adb push cmd /sdcard
The Basics of Go Mobile / Run on Androind Devices
Slide URL: https://goo.gl/cIvTb5
Run on Android Devices
Watch at Youtube Source Code
Android
Shell on Mac
adb shell
The Basics of Go Mobile / Run on Androind Devices 80
Slide URL: https://goo.gl/cIvTb5
Handle Lifecycle Event
Go for Mobile Game / Handle Lifecycle Event 81
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
glctx, _ = e.DrawContext.(gl.Context)
onStart(glctx)
a.Send(paint.Event{})
case lifecycle.CrossOff:
onStop()
glctx = nil
}
StageDead
StageAlive
StageVisible
StageFocused

More Related Content

Viewers also liked

Mobile game UI trends 2016
Mobile game UI trends 2016Mobile game UI trends 2016
Mobile game UI trends 2016Bilyana Vacheva
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldJignesh Shah
 
Marketing Mobile Games and Apps in India
Marketing Mobile Games and Apps in IndiaMarketing Mobile Games and Apps in India
Marketing Mobile Games and Apps in IndiaBenjamin Cheeks
 
[English] Create Mobile LBS Application Using Maps API
[English] Create Mobile LBS Application Using Maps API[English] Create Mobile LBS Application Using Maps API
[English] Create Mobile LBS Application Using Maps APIGoogle Cloud Platform - Japan
 
Goでwebアプリを開発してみよう
Goでwebアプリを開発してみようGoでwebアプリを開発してみよう
Goでwebアプリを開発してみようTakuya Ueda
 
Journey to Containerized Application / Google Container Engine
Journey to Containerized Application / Google Container EngineJourney to Containerized Application / Google Container Engine
Journey to Containerized Application / Google Container EngineGoogle Cloud Platform - Japan
 
GAE/GoでWebアプリ開発入門
GAE/GoでWebアプリ開発入門GAE/GoでWebアプリ開発入門
GAE/GoでWebアプリ開発入門Takuya Ueda
 
Digital Advertising and the way forward
Digital Advertising and the way forwardDigital Advertising and the way forward
Digital Advertising and the way forwardGreedyGame
 
Googleにおける機械学習の活用とクラウドサービス
Googleにおける機械学習の活用とクラウドサービスGoogleにおける機械学習の活用とクラウドサービス
Googleにおける機械学習の活用とクラウドサービスGoogle Cloud Platform - Japan
 
Strategy for Successful Mobile Game development
Strategy for Successful Mobile Game developmentStrategy for Successful Mobile Game development
Strategy for Successful Mobile Game developmentGreedyGame
 
go.mobile で Android 開発
go.mobile で Android 開発go.mobile で Android 開発
go.mobile で Android 開発Hiroshi Kurokawa
 
Go mobileでモバイルアプリを作ろう
Go mobileでモバイルアプリを作ろうGo mobileでモバイルアプリを作ろう
Go mobileでモバイルアプリを作ろうTakuya Ueda
 
Goだけでモバイルアプリを作ろう
Goだけでモバイルアプリを作ろうGoだけでモバイルアプリを作ろう
Goだけでモバイルアプリを作ろうTakuya Ueda
 
エディタの壁を越えるGoの開発ツールの文化と作成法
エディタの壁を越えるGoの開発ツールの文化と作成法エディタの壁を越えるGoの開発ツールの文化と作成法
エディタの壁を越えるGoの開発ツールの文化と作成法Takuya Ueda
 
Google Cloud のネットワークとロードバランサ
Google Cloud のネットワークとロードバランサGoogle Cloud のネットワークとロードバランサ
Google Cloud のネットワークとロードバランサGoogle Cloud Platform - Japan
 
GAE/GoでLINE Messaging API を使う
GAE/GoでLINE Messaging API を使うGAE/GoでLINE Messaging API を使う
GAE/GoでLINE Messaging API を使うTakuya Ueda
 

Viewers also liked (20)

Mobile game UI trends 2016
Mobile game UI trends 2016Mobile game UI trends 2016
Mobile game UI trends 2016
 
PostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized WorldPostgreSQL High Availability in a Containerized World
PostgreSQL High Availability in a Containerized World
 
Marketing Mobile Games and Apps in India
Marketing Mobile Games and Apps in IndiaMarketing Mobile Games and Apps in India
Marketing Mobile Games and Apps in India
 
[English] Create Mobile LBS Application Using Maps API
[English] Create Mobile LBS Application Using Maps API[English] Create Mobile LBS Application Using Maps API
[English] Create Mobile LBS Application Using Maps API
 
Goでwebアプリを開発してみよう
Goでwebアプリを開発してみようGoでwebアプリを開発してみよう
Goでwebアプリを開発してみよう
 
No-Ops で大量データ処理基盤
No-Ops で大量データ処理基盤No-Ops で大量データ処理基盤
No-Ops で大量データ処理基盤
 
Mobile Game Market In India
Mobile Game Market In IndiaMobile Game Market In India
Mobile Game Market In India
 
Journey to Containerized Application / Google Container Engine
Journey to Containerized Application / Google Container EngineJourney to Containerized Application / Google Container Engine
Journey to Containerized Application / Google Container Engine
 
GAE/GoでWebアプリ開発入門
GAE/GoでWebアプリ開発入門GAE/GoでWebアプリ開発入門
GAE/GoでWebアプリ開発入門
 
Digital Advertising and the way forward
Digital Advertising and the way forwardDigital Advertising and the way forward
Digital Advertising and the way forward
 
Googleにおける機械学習の活用とクラウドサービス
Googleにおける機械学習の活用とクラウドサービスGoogleにおける機械学習の活用とクラウドサービス
Googleにおける機械学習の活用とクラウドサービス
 
Strategy for Successful Mobile Game development
Strategy for Successful Mobile Game developmentStrategy for Successful Mobile Game development
Strategy for Successful Mobile Game development
 
go.mobile で Android 開発
go.mobile で Android 開発go.mobile で Android 開発
go.mobile で Android 開発
 
Go mobileでモバイルアプリを作ろう
Go mobileでモバイルアプリを作ろうGo mobileでモバイルアプリを作ろう
Go mobileでモバイルアプリを作ろう
 
Goだけでモバイルアプリを作ろう
Goだけでモバイルアプリを作ろうGoだけでモバイルアプリを作ろう
Goだけでモバイルアプリを作ろう
 
Pokémon GOとGCP
Pokémon GOとGCPPokémon GOとGCP
Pokémon GOとGCP
 
エディタの壁を越えるGoの開発ツールの文化と作成法
エディタの壁を越えるGoの開発ツールの文化と作成法エディタの壁を越えるGoの開発ツールの文化と作成法
エディタの壁を越えるGoの開発ツールの文化と作成法
 
Google Cloud のネットワークとロードバランサ
Google Cloud のネットワークとロードバランサGoogle Cloud のネットワークとロードバランサ
Google Cloud のネットワークとロードバランサ
 
GAE/GoでLINE Messaging API を使う
GAE/GoでLINE Messaging API を使うGAE/GoでLINE Messaging API を使う
GAE/GoでLINE Messaging API を使う
 
Go入門
Go入門Go入門
Go入門
 

Similar to Go for Mobile Games

Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingTakuya Ueda
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using GolangSeongJae Park
 
Develop Android/iOS app using golang
Develop Android/iOS app using golangDevelop Android/iOS app using golang
Develop Android/iOS app using golangSeongJae Park
 
(Live) build and run golang web server on android.avi
(Live) build and run golang web server on android.avi(Live) build and run golang web server on android.avi
(Live) build and run golang web server on android.aviSeongJae Park
 
Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and GolangAlmog Baku
 
Android is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog BakuAndroid is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog BakuDroidConTLV
 
Golang skills pre-session
Golang skills pre-sessionGolang skills pre-session
Golang skills pre-sessionsofianinho
 
Ionic - Revolutionizing Hybrid Mobile Application Development
Ionic - Revolutionizing Hybrid Mobile Application DevelopmentIonic - Revolutionizing Hybrid Mobile Application Development
Ionic - Revolutionizing Hybrid Mobile Application DevelopmentJustin James
 
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)Evan Lin
 
Introduction to Cloud Computing with Google Cloud
Introduction to Cloud Computing with Google CloudIntroduction to Cloud Computing with Google Cloud
Introduction to Cloud Computing with Google Cloudwesley chun
 
DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.JooinK
 
DIY- computer vision with GWT
DIY- computer vision with GWTDIY- computer vision with GWT
DIY- computer vision with GWTFrancesca Tosi
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to GoSimon Hewitt
 
Embedded Android Workshop with Nougat
Embedded Android Workshop with NougatEmbedded Android Workshop with Nougat
Embedded Android Workshop with NougatOpersys inc.
 
GTG30: Introduction vgo
GTG30: Introduction vgoGTG30: Introduction vgo
GTG30: Introduction vgoEvan Lin
 
Gomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidGomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidJovica Popovic
 
Scaling applications with go
Scaling applications with goScaling applications with go
Scaling applications with goVimlesh Sharma
 

Similar to Go for Mobile Games (20)

Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse Binding
 
Develop Android app using Golang
Develop Android app using GolangDevelop Android app using Golang
Develop Android app using Golang
 
Develop Android/iOS app using golang
Develop Android/iOS app using golangDevelop Android/iOS app using golang
Develop Android/iOS app using golang
 
Comparing C and Go
Comparing C and GoComparing C and Go
Comparing C and Go
 
(Live) build and run golang web server on android.avi
(Live) build and run golang web server on android.avi(Live) build and run golang web server on android.avi
(Live) build and run golang web server on android.avi
 
Android is going to Go! Android and Golang
Android is going to Go! Android and GolangAndroid is going to Go! Android and Golang
Android is going to Go! Android and Golang
 
Android is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog BakuAndroid is going to Go! - Android and goland - Almog Baku
Android is going to Go! - Android and goland - Almog Baku
 
Golang skills pre-session
Golang skills pre-sessionGolang skills pre-session
Golang skills pre-session
 
Ionic - Revolutionizing Hybrid Mobile Application Development
Ionic - Revolutionizing Hybrid Mobile Application DevelopmentIonic - Revolutionizing Hybrid Mobile Application Development
Ionic - Revolutionizing Hybrid Mobile Application Development
 
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)iTHome Gopher Day 2017: What can Golang do?  (Using project 52 as examples)
iTHome Gopher Day 2017: What can Golang do? (Using project 52 as examples)
 
Introduction to Cloud Computing with Google Cloud
Introduction to Cloud Computing with Google CloudIntroduction to Cloud Computing with Google Cloud
Introduction to Cloud Computing with Google Cloud
 
DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.DIY: Computer Vision with GWT.
DIY: Computer Vision with GWT.
 
DIY- computer vision with GWT
DIY- computer vision with GWTDIY- computer vision with GWT
DIY- computer vision with GWT
 
Drone sdk showdown
Drone sdk showdownDrone sdk showdown
Drone sdk showdown
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
Embedded Android Workshop with Nougat
Embedded Android Workshop with NougatEmbedded Android Workshop with Nougat
Embedded Android Workshop with Nougat
 
GTG30: Introduction vgo
GTG30: Introduction vgoGTG30: Introduction vgo
GTG30: Introduction vgo
 
Gomobile: gophers in the land of Android
Gomobile: gophers in the land of AndroidGomobile: gophers in the land of Android
Gomobile: gophers in the land of Android
 
What is PhoneGap?
What is PhoneGap?What is PhoneGap?
What is PhoneGap?
 
Scaling applications with go
Scaling applications with goScaling applications with go
Scaling applications with go
 

More from Takuya Ueda

Goにおけるバージョン管理の必要性 − vgoについて −
Goにおけるバージョン管理の必要性 − vgoについて −Goにおけるバージョン管理の必要性 − vgoについて −
Goにおけるバージョン管理の必要性 − vgoについて −Takuya Ueda
 
WebAssembly with Go
WebAssembly with GoWebAssembly with Go
WebAssembly with GoTakuya Ueda
 
GAE/Goとsyncパッケージ
GAE/GoとsyncパッケージGAE/Goとsyncパッケージ
GAE/GoとsyncパッケージTakuya Ueda
 
静的解析を使った開発ツールの開発
静的解析を使った開発ツールの開発静的解析を使った開発ツールの開発
静的解析を使った開発ツールの開発Takuya Ueda
 
そうだ、Goを始めよう
そうだ、Goを始めようそうだ、Goを始めよう
そうだ、Goを始めようTakuya Ueda
 
マスター・オブ・goパッケージ
マスター・オブ・goパッケージマスター・オブ・goパッケージ
マスター・オブ・goパッケージTakuya Ueda
 
メルカリ カウルのマスタデータの更新
メルカリ カウルのマスタデータの更新メルカリ カウルのマスタデータの更新
メルカリ カウルのマスタデータの更新Takuya Ueda
 
Go1.8 for Google App Engine
Go1.8 for Google App EngineGo1.8 for Google App Engine
Go1.8 for Google App EngineTakuya Ueda
 
Go Friday 傑作選
Go Friday 傑作選Go Friday 傑作選
Go Friday 傑作選Takuya Ueda
 
GoによるiOSアプリの開発
GoによるiOSアプリの開発GoによるiOSアプリの開発
GoによるiOSアプリの開発Takuya Ueda
 
Static Analysis in Go
Static Analysis in GoStatic Analysis in Go
Static Analysis in GoTakuya Ueda
 
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話Takuya Ueda
 
メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?Takuya Ueda
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGoTakuya Ueda
 
Go静的解析ハンズオン
Go静的解析ハンズオンGo静的解析ハンズオン
Go静的解析ハンズオンTakuya Ueda
 
Goにおける静的解析と製品開発への応用
Goにおける静的解析と製品開発への応用Goにおける静的解析と製品開発への応用
Goにおける静的解析と製品開発への応用Takuya Ueda
 
オススメの標準・準標準パッケージ20選
オススメの標準・準標準パッケージ20選オススメの標準・準標準パッケージ20選
オススメの標準・準標準パッケージ20選Takuya Ueda
 
Gopher Fest 2017参加レポート
Gopher Fest 2017参加レポートGopher Fest 2017参加レポート
Gopher Fest 2017参加レポートTakuya Ueda
 
Google Assistant関係のセッションまとめ
Google Assistant関係のセッションまとめGoogle Assistant関係のセッションまとめ
Google Assistant関係のセッションまとめTakuya Ueda
 
Cloud functionsの紹介
Cloud functionsの紹介Cloud functionsの紹介
Cloud functionsの紹介Takuya Ueda
 

More from Takuya Ueda (20)

Goにおけるバージョン管理の必要性 − vgoについて −
Goにおけるバージョン管理の必要性 − vgoについて −Goにおけるバージョン管理の必要性 − vgoについて −
Goにおけるバージョン管理の必要性 − vgoについて −
 
WebAssembly with Go
WebAssembly with GoWebAssembly with Go
WebAssembly with Go
 
GAE/Goとsyncパッケージ
GAE/GoとsyncパッケージGAE/Goとsyncパッケージ
GAE/Goとsyncパッケージ
 
静的解析を使った開発ツールの開発
静的解析を使った開発ツールの開発静的解析を使った開発ツールの開発
静的解析を使った開発ツールの開発
 
そうだ、Goを始めよう
そうだ、Goを始めようそうだ、Goを始めよう
そうだ、Goを始めよう
 
マスター・オブ・goパッケージ
マスター・オブ・goパッケージマスター・オブ・goパッケージ
マスター・オブ・goパッケージ
 
メルカリ カウルのマスタデータの更新
メルカリ カウルのマスタデータの更新メルカリ カウルのマスタデータの更新
メルカリ カウルのマスタデータの更新
 
Go1.8 for Google App Engine
Go1.8 for Google App EngineGo1.8 for Google App Engine
Go1.8 for Google App Engine
 
Go Friday 傑作選
Go Friday 傑作選Go Friday 傑作選
Go Friday 傑作選
 
GoによるiOSアプリの開発
GoによるiOSアプリの開発GoによるiOSアプリの開発
GoによるiOSアプリの開発
 
Static Analysis in Go
Static Analysis in GoStatic Analysis in Go
Static Analysis in Go
 
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話
静的解析とUIの自動生成を駆使してモバイルアプリの運用コストを大幅に下げた話
 
メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?メルカリ・ソウゾウでは どうGoを活用しているのか?
メルカリ・ソウゾウでは どうGoを活用しているのか?
 
エキスパートGo
エキスパートGoエキスパートGo
エキスパートGo
 
Go静的解析ハンズオン
Go静的解析ハンズオンGo静的解析ハンズオン
Go静的解析ハンズオン
 
Goにおける静的解析と製品開発への応用
Goにおける静的解析と製品開発への応用Goにおける静的解析と製品開発への応用
Goにおける静的解析と製品開発への応用
 
オススメの標準・準標準パッケージ20選
オススメの標準・準標準パッケージ20選オススメの標準・準標準パッケージ20選
オススメの標準・準標準パッケージ20選
 
Gopher Fest 2017参加レポート
Gopher Fest 2017参加レポートGopher Fest 2017参加レポート
Gopher Fest 2017参加レポート
 
Google Assistant関係のセッションまとめ
Google Assistant関係のセッションまとめGoogle Assistant関係のセッションまとめ
Google Assistant関係のセッションまとめ
 
Cloud functionsの紹介
Cloud functionsの紹介Cloud functionsの紹介
Cloud functionsの紹介
 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Go for Mobile Games

  • 1. The Go gopher was designed by Renée French. The gopher stickers was made by Takuya Ueda. Licensed under the Creative Commons 3.0 Attributions license. Go for Mobile Games GopherCon 2016, Denver 11th July 2016 Takuya Ueda @tenntenn KLab Inc. Slide URL: https://goo.gl/cIvTb5
  • 2. Slide URL: https://goo.gl/cIvTb5 What is this talk about? ● The Basics of Go Mobile ○ Cross-compile and Android device ○ SDK Apps and Native Apps ● Go for Mobile Game ○ Event handling ○ 2D scene graph ● Advanced Topics ○ Distribute apps on Google Play ○ How to use Android API from Go 2
  • 3. Slide URL: https://goo.gl/cIvTb5 The Basics of Go Mobile 3 ● Run on Android Devices ● Cross-compile and cgo ● SDK Apps and Native Apps
  • 4. Slide URL: https://goo.gl/cIvTb5 Cross-compile ● GOOS and GOARCH ○ Go can cross-compile ○ GOOS indicates target OS ○ GOARCH indicates target architecture 4 # Build for 32bit Windows $ GOOS=windows GOARCH=386 go build # Build for arm Linux $ GOOS=linux GOARCH=arm go build A linux/arm binary also works on android devices. The Basics of Go Mobile / Cross-compile and cgo
  • 5. Slide URL: https://goo.gl/cIvTb5 Webserver on Android Devices Watch at Youtube Source Code Android Shell on Mac adb shell The Basics of Go Mobile / Webserver on Androind Devices 5
  • 6. Slide URL: https://goo.gl/cIvTb5 cgo ● C codes into Go codes import "unsafe" /* #include <stdio.h> #include <stdlib.h> void hello(char *s) { printf("Hello, %sn", s); } */ import "C" func main() { str := C.CString("GopherCon") C.hello(str) C.free(unsafe.Pointer(str)) } Comments before import "C" would be built as C codes Call C’s function from Go code The Basics of Go Mobile / Cross Compile and cgo 6
  • 7. Slide URL: https://goo.gl/cIvTb5 cgo for Android ● cgo codes also can be cross-compiled 7 $ CGO_ENABLED=1 CC=arm-linux-androideabi-gcc GOOS=android GOARCH=arm GOARM=7 go build -buildmode=pie hellocgo.go $ adb push hellocgo /data/local/tmp $ chmod 755 /data/local/tmp/hellocgo $ /data/local/tmp/hellocgo Hello, GopherCon GOOS should be android when CGO_ENABLED is 1. Enable cgo at cross-compiling adb shell PC The Basics of Go Mobile / Cross Compile and cgo
  • 8. Slide URL: https://goo.gl/cIvTb5 buildmode ● Change output formats ○ archive, c-archive ■ build to C archive (.a file) ○ shared, c-shared ■ build to shared library (.so file) ○ exe ■ build to executable file ○ pie ■ build to PIE style executable file archive and shared ignore main package Go can build to .so files for Android 8The Basics of Go Mobile / Cross Compile and cgo
  • 9. Slide URL: https://goo.gl/cIvTb5 Go Mobile ● What is Go Mobile? ○ Go Mobile is a toolkit for Mobile Platform (Android and iOS) with Go. ● How Go Mobile works? ○ Go Mobile provides bindings of Android and iOS through cgo. 9 Go C Java Obj-C JNIcgo Android iOS The Basics of Go Mobile / Go Mobile
  • 10. Slide URL: https://goo.gl/cIvTb5 Go Mobile The Basics of Go Mobile / Go Mobile 10 https://github.com/golang/mobile
  • 11. Slide URL: https://goo.gl/cIvTb5 Installation ● Install gomobile comand ● Initialize the build tool chain ○ gomobile init initializes the build tool chain for mobile apps. Android NDK is also installed. 11 $ gomobile init -v $ ls $GOPATH/pkg/gomobile android-ndk-r12 pkg_android_386 pkg_android_arm pkg_darwin_amd64 pkg_darwin_arm64 dl pkg_android_amd64 pkg_android_arm64 pkg_darwin_arm version $ go get golang.org/x/mobile/cmd/gomobile The Basics of Go Mobile / Installation
  • 12. Slide URL: https://goo.gl/cIvTb5 gomobile command gomobile command provides sub-commands. ● Sub-commands 12 bind build a library for Android and iOS build compile Android APK and iOS app clean remove object files and cached gomobile files init install android compiler toolchain install compile android APK and install on device version print version The Basics of Go Mobile / gomobile command
  • 13. Slide URL: https://goo.gl/cIvTb5 SDK Apps and Native Apps Go Mobile provides two ways to develop mobile apps. ■ SDK Apps ● Write common funcations in Go as a library ● Write UI and platform dependent functions in Java for Android and Objective-C/Swift for iOS ■ Native Apps ● Write UI and all codes in Go 13The Basics of Go Mobile / SDK Apps and Native Apps
  • 14. Slide URL: https://goo.gl/cIvTb5 Go aar file SDK Apps and Native Apps Binding Classes (Java) Shared library (.so) Java ● SDK Apps for Android ● Native Apps for Android apk file Go GoNativeActivity Shared library (.so) UI, IAB, ... As a library UI, audio, ... gomobile bind gomobile build The Basics of Go Mobile / SDK Apps and Native Apps 14
  • 15. Slide URL: https://goo.gl/cIvTb5 Go aar file SDK Apps and Native Apps Binding Classes (Java) Shared library (.so) Java ● SDK Apps for Android ● Native Apps for Android apk file Go GoNativeActivity Shared library (.so) UI, IAB, ... As a library UI, audio, ... gomobile bind gomobile build The Basics of Go Mobile / SDK Apps and Native Apps 15
  • 16. Slide URL: https://goo.gl/cIvTb5 SDK App example: Ivy ● Ivy big number calculator (source code) ○ Interpriter for APL-like language ○ Android App and iOS App use a same engine ○ The engine is written in Go by Rob Pike 16 Google Play App Store The Basics of Go Mobile / SDK App example: Ivy
  • 17. Slide URL: https://goo.gl/cIvTb5 gomobile bind ● Generate an Android Archive (.aar) ○ Including a shared library (.so) written in Go ○ Including a JAR file which is bult Java bindings ● Develop with Android Studio Plugin ○ Runs gomobile bind ○ Links to a generated .aar file $ gomobile bind [-target ios|android] mypkg 17The Basics of Go Mobile / gomobile bind
  • 18. Slide URL: https://goo.gl/cIvTb5 Contents of AAR 18The Basics of Go Mobile / Contents of AAR $ gomobile bind sample $ unzip -Z1 sample.aar AndroidManifest.xml proguard.txt classes.jar jni/armeabi-v7a/libgojni.so jni/arm64-v8a/libgojni.so jni/x86/libgojni.so jni/x86_64/libgojni.so R.txt res/ Compiled Java code Compiled Go/C code
  • 19. Slide URL: https://goo.gl/cIvTb5 Binding Use SDK from Application 19The Basics of Go Mobile / Use SDK from Application Java code Application Code (Java) C code Go/cgo JNI Generated by gomobile bind SDK Code (Go) cgo
  • 20. Slide URL: https://goo.gl/cIvTb5 Binding Go and Java 20The Basics of Go Mobile / Binding Go and Java Package Abstrct Class Struct Inner Class Struct Field Getter/Setter (Native) Method Method (Native) Pacakge Function Static Method Go Java
  • 21. Slide URL: https://goo.gl/cIvTb5 Binding Go and Java 21The Basics of Go Mobile / Binding Go and Java package sample func Hello() string { return "Hello" } type MyStruct struct { Str string } func (s MyStruct) MyMethod() string { return s.Str } public abstract class Sample { // ... private Sample() {} // uninstantiable public static final class MyStruct extends Seq.Proxy { public final native String getStr(); public final native void setStr(String v); public native String MyMethod(); // ... } public static native String Hello(); } Java Go Struct Field Method Package Function
  • 22. Slide URL: https://goo.gl/cIvTb5 Type restrictions The Basics of Go Mobile / 22 ● Signed integer and floating point type ● String and boolean type ● Byte slice type ● Any functions ○ parameter and result types must be supported types ○ results are 0, 1 or 2 (2nd result must be an error type) ● Any struct type ○ all fields and methods must be supported types ● Any interface ○ all methods must be supported types
  • 23. Slide URL: https://goo.gl/cIvTb5 Go aar file SDK Apps and Native Apps Binding Classes (Java) Shared library (.so) Java ● SDK Apps for Android ● Native Apps for Android apk file Go GoNativeActivity Shared library (.so) UI, IAB, ... As a library UI, audio, ... gomobile bind gomobile build The Basics of Go Mobile / SDK Apps and Native Apps 23
  • 24. Slide URL: https://goo.gl/cIvTb5 gomobile build and gomobile install ● Generate an .apk file ○ Including a shared library (.so) written in Go ○ Including a dex file which is bult GoNativeActivity ● Build and Install ○ Run gomobile build and adb install ○ Android Only $ gomobile build [-target ios|android] mainpkg 24The Basics of Go Mobile / gomobile build and gomobile install $ gomobile install [-target ios|android] mainpkg
  • 25. Slide URL: https://goo.gl/cIvTb5 Contents of APK 25The Basics of Go Mobile / Contents of APK $ gomobile build golang.org/x/mobile/example/flappy $ unzip -Z1 flappy.apk AndroidManifest.xml classes.dex lib/armeabi-v7a/libflappy.so lib/arm64-v8a/libflappy.so lib/x86/libflappy.so lib/x86_64/libflappy.so assets/README assets/sprite.png META-INF/MANIFEST.MF META-INF/CERT.SF META-INF/CERT.RSA Compiled GoNativeActivity.java Compiled Go/C code
  • 26. Slide URL: https://goo.gl/cIvTb5 x/mobile/app How Native App works? 26The Basics of Go Mobile / How Native App works? GoNativeActivity C code Go/cgo JNI Application Code (Go) cgo exntends NativeActivity
  • 27. Slide URL: https://goo.gl/cIvTb5 Go for Mobile Game 27 ● Basic event loop and paint events ● Size Event and Lifecycle Event ● 2D Scene Graph ● Touch Event
  • 28. Slide URL: https://goo.gl/cIvTb5 Go for Mobile Game Go for Mobile Game / Go for Mobile Game 28 ● Flappy Gopher ○ by Andrew Gerrand ○ for Go Conference 2015 Winter ○ Source Code ● How it works? ○ gomobile build ○ render images and animate ○ handle touch events $ go get golang.org/x/mobile/cmd/gomobile && gomobile init $ gomobile install golang.org/x/mobile/example/flappy
  • 29. Slide URL: https://goo.gl/cIvTb5 Packages ● Rendering ○ OpenGL ES2 : gl, exp/gl/glutil ○ 2D Scene Graph : exp/sprite ● Event ○ Touch Event : event/touch ○ Lifecycle Event : event/lifecycle ● Sensors : exp/sensor ○ Accelerometer, Gyroscope, Magnetometer ● Audio : exp/audio Go for Mobile Game / Packages 29 Package Name
  • 30. Slide URL: https://goo.gl/cIvTb5 app.Main ● app.Main receives an entry point function Go for Mobile Game / app.Main 30 func main() { app.Main(func(a app.App) { // Event Loop }) }
  • 31. Slide URL: https://goo.gl/cIvTb5 Event Loop ● Receive events through a channel Go for Mobile Game / Event Loop 31 Event Loop Paint Event Touch Event Life Cycle Event Switch by Event Types CASE CASE CASE
  • 32. Slide URL: https://goo.gl/cIvTb5 Event Channel ● Receive events from App.Events() channel Go for Mobile Game / Event Channel 32 // Events() <-chan interface{} for e := range a.Events() { // a is app.App switch e := a.Filter(e).(type) { case paint.Event: case touch.Event: case lifecycle.Event: } }
  • 33. Slide URL: https://goo.gl/cIvTb5 Event Types Go for Mobile Game / Event Types 33 paint.Event Rendering event touch.Event Screen touch event lifecycle.Event App’s lifecycle event Such as OnStart and OnStop on Android size.Event dimension, physical resolution and orientation changed event mouse.Event Mouse event key.Event Only hardware keyboard event
  • 34. Slide URL: https://goo.gl/cIvTb5 How to render images Go for Mobile Game / How to render images 34 ● Construct a scene graph ○ exp/sprite package provides 2D scene graph ● Load a texture ○ asset package loads a image as a texture ● Set a sub-texture to a node ○ A node of scene graph can be set a sub-texture (part of a texture) ● Render a scene graph ○ sprite.Engine type has Render method
  • 35. Slide URL: https://goo.gl/cIvTb5 2D scene graph Go for Mobile Game / 2D scene graph 35 scene gopher Rendering Engine ground1 Node TextureSub-texture Game SceneScene Graph Render Set Load
  • 36. Slide URL: https://goo.gl/cIvTb5 Construct a scene graph ● Create a rendering engine ● Create and register a node ● Append a child node Go for Mobile Game / Construct a scene graph 36 images = glutil.NewImages(glctx) eng = glsprite.Engine(images) node := &sprite.Node{} eng.Register(node) parentNode.AppendChild(childNode) glctx is a OpenGL context images maintains shared state used by texutres
  • 37. Slide URL: https://goo.gl/cIvTb5 Load a texture ● Open an asset ● Decode an image ● Load a texture to rendering engine Go for Mobile Game / Load a texture 37 a, err := asset.Open("gopher.png") img, err := image.Decode(a) tex, err := eng.LoadTexture(img) asset files are put into assets directory use image package from standard packages
  • 38. Slide URL: https://goo.gl/cIvTb5 Set a sub-texture ● Create a sub-texture ● Set a sub-texture to a node Go for Mobile Game / Set a sub-texture 38 subtex := sprite.Subtex { T:tex, R:iamge.Rect(128, 0, 128, 128) } eng.SetSubTex(node, subtex) Bounds on a source texture
  • 39. Slide URL: https://goo.gl/cIvTb5 Render a scene graph ● Render receives a root node of a scene graph Go for Mobile Game / Render a scene graph 39 // compute current frame in 60FPS since := time.Since(startTime) now := clock.Time(since * 60 / time.Second) // scene *sprite.Node // now clock.Time // sz event.Size eng.Render(scene, now, sz) Root Node Screen Size and Orientation
  • 40. Slide URL: https://goo.gl/cIvTb5 Handling Events Go for Mobile Game / Handling Events 40 Handle Size Event Handle Lifecycle Event Handle Paint Event Get Screen Size and Orientation Get OpenGL Context and Construct a Scene Graph Render a Scene Graph
  • 41. Slide URL: https://goo.gl/cIvTb5 Handle Size Event Go for Mobile Game / Handle Size Event 41 app.Main(func(a app.App) { var glctx gl.Context var sz size.Event for e := range a.Events() { switch e := a.Filter(e).(type) { case size.Event: sz = e // ... } } }) type Event struct { WidthPx, HeightPx int WidthPt, HeightPt geom.Pt PixelsPerPt float32 Orientation Orientation }
  • 42. Slide URL: https://goo.gl/cIvTb5 Handle Lifecycle Event Go for Mobile Game / Handle Lifecycle Event 42 case lifecycle.Event: switch e.Crosses(lifecycle.StageVisible) { case lifecycle.CrossOn: glctx, _ = e.DrawContext.(gl.Context) onStart(glctx) a.Send(paint.Event{}) case lifecycle.CrossOff: onStop() glctx = nil } Get a OpenGL Context StageDead StageAlive StageVisible StageFocused
  • 43. Slide URL: https://goo.gl/cIvTb5 Handle Lifecycle Event Go for Mobile Game / Handle Lifecycle Event 43 StageDead StageAlive StageVisible StageFocused From To type Event struct { From, To Stage DrawContext interface{} } lifecycle.Event e.Crosses(StageVisible) == CrossOn
  • 44. Slide URL: https://goo.gl/cIvTb5 Handle Lifecycle Event Go for Mobile Game / Handle Lifecycle Event 44 StageDead StageAlive StageVisible StageFocused To From type Event struct { From, To Stage DrawContext interface{} } lifecycle.Event e.Crosses(StageAlive) == CrossOff
  • 45. Slide URL: https://goo.gl/cIvTb5 Handle Paint Event Go for Mobile Game / Handle Paint Event 45 Arrange Nodes Set Sub-texture Render Scene Graph Set an Affine Transformation Matrix Relative to Parent Node Change images for animations
  • 46. Slide URL: https://goo.gl/cIvTb5 Arrange a Scene Graph Node Go for Mobile Game / Arrange a Scene Graph Node 46 type Arranger interface{ Arrange(e Engine, n *Node, t clock.Time) } // For convinience, arrangeFunc implements Arrange interface type arrangeFunc func(e Engine, n *Node, t clock.Time) func (f arrangeFunc) Arrange(e Engine, n *Node, t clock.Time) { f(e, n, t) } ● sprite.Arrranger has Arrange method which is called each frame by rendering engine
  • 47. Slide URL: https://goo.gl/cIvTb5 Set Arranger to a Scene Graph Node Go for Mobile Game / Set Arranger to a Scene Graph Node 47 // Called each frame func arrange(e sprite.Engine, n *sprite.Node, t clock.Time) { // Node manupulation } // Set a Arranger interface to a node node.Arranger = arrangerFunc(arrange)
  • 48. Slide URL: https://goo.gl/cIvTb5 Affine Transformation Matrix Go for Mobile Game / Affine Transformation Matrix 48 // Scale(2,2) and Translate(5,5) eng.SetTransform(node, f32.Affine{ {2, 0, 5}, {0, 2, 5}, }) ● A scene graph node can set a affine transform matrix to compute position, scale and rotation angle
  • 49. Slide URL: https://goo.gl/cIvTb5 Affine Transform Go for Mobile Game / Affine Transform 49 ● Affine transform from the root node to the child node root n Translate(5,5) Scale(2,2) Translate(10,10) Scale(100,100) pos: (5,5) size: 2pt x 2pt pos: (25,25) size: 200pt x 200pt 1pt = 1/72 inch Base size is 1pt x 1pt Base position is (0,0) Base rotation angle is 0
  • 50. Slide URL: https://goo.gl/cIvTb5 Affine Transform Go for Mobile Game / Affine Transform 50 root n pos: (5,5) size: 2pt x 2pt pos: (25,25) size: 200pt x 200pt eng.SetTransform(root, f32.Affine{ {2, 0, 5}, {0, 2, 5}, }) eng.SetTransform(n, f32.Affine{ {100, 0, 10}, {0, 100, 10}, }) pos: (0,0) size: 1pt x 1pt
  • 51. Slide URL: https://goo.gl/cIvTb5 Handle Touch Event Go for Mobile Game / Handle Touch Event 51 type Event struct { // Touch location in pixels. X, Y float32 // Sequence number for each touch. Sequence Sequence // Type is the touch type. // TypeBegin, TypeMove, TypeEnd Type Type } touch.Event
  • 52. Slide URL: https://goo.gl/cIvTb5 Touch Types and Sequence Go for Mobile Game / Touch Types and Sequence 52 TypeBegin TypeMove Same Sequence TypeEnd Sequence:1 Multi Touch Sequence:2
  • 53. Slide URL: https://goo.gl/cIvTb5 Debug on PC ● Go Mobile’s packages also works fine on PC (Mac, Windows, Linux). Go for Mobile Game / Debug on PC 53 $ go build mainpkg $ ./mainpkg assets directry should be placed at working directory Running on Mac
  • 54. Slide URL: https://goo.gl/cIvTb5 Restrictions for Native Apps (Android) ● Cannot set own App’s icon ● Only use a debug keystore ● Cannot distribute on Google Play ○ Need to set own App’s icon ○ Need a release keystore ● Cannot use Platform API ○ Cannot use In-app Billing API ○ Cannot use third party API Go for Mobile Game / Debug on PC 54
  • 55. Slide URL: https://goo.gl/cIvTb5 Advanced Topics 55 ● Distribute apps on Google Play ● Use Platform APIs from Go
  • 56. Slide URL: https://goo.gl/cIvTb5 Contents of APK 56Advanced Topics / Contents of APK $ gomobile build golang.org/x/mobile/example/flappy $ unzip -Z1 flappy.apk AndroidManifest.xml classes.dex lib/armeabi-v7a/libflappy.so lib/arm64-v8a/libflappy.so lib/x86/libflappy.so lib/x86_64/libflappy.so assets/README assets/sprite.png META-INF/MANIFEST.MF META-INF/CERT.SF META-INF/CERT.RSA res directory is not included into APK Signature Related Files
  • 57. Slide URL: https://goo.gl/cIvTb5 Modify APK for Release 57Advanced Topics / Modify APK for Release gomobile build● Create an APK file for debug ● Expand the APK file by apktool ● Modify the AndroidManifest ○ Add icon setting and Disable debuggable setting ● Add app’s icons and res directory ● Rearchive an APK file by apktool ● Signature with release keystore ● ZIP Align
  • 58. Slide URL: https://goo.gl/cIvTb5 Expand an APK File Advanced Topics / Expand an APK File 58 # if you have not installed $ brew install apktool $ apktool d flappy.apk # expand ● Use apktool to expand and archive an APK file
  • 59. Slide URL: https://goo.gl/cIvTb5 Add App’s Icons Advanced Topics / Add App’s Icons 59 $ tree flappy/res flappy/res ├── drawable-hdpi │ └── ic_launcher.png ... └── drawable-xxxhdpi └── ic_launcher.png ● Make a res direcotry and add app’s icons ○ under the expanded APK directory App’s Icons
  • 60. Slide URL: https://goo.gl/cIvTb5 Add icon setting ● Add an icon setting to AndroidManifest ● android:icon sepecify icon file name Advanced Topics / Add icon setting 60 <?xml version="1.0" encoding="utf-8"?> ... <application android:label="Flappy" android:icon="@drawable/ic_launcher" ...
  • 61. Slide URL: https://goo.gl/cIvTb5 Disable debuggable setting ● To upload apk on Google Play, apk should be built without debuggable="true" ○ We can also use own AndroidManifest.xml by putting top level directory before building. Advanced Topics / Disable debuggable setting 61 <?xml version="1.0" encoding="utf-8"?> ... <application android:label="Flappy" ... android:debuggable="true" ...
  • 62. Slide URL: https://goo.gl/cIvTb5 Signiture with Release Keystore 62Advanced Topics / Signiture with Release Keystore ● Re-archive the APK file ● Re-signiture the APK file $ apktool b flappy $ cd flappy/dist $ jarsigner ... -keystore release.keystore flappy.apk flappy $ zipalign -f -v 4 flappy{,_aligned}.apk $ ls flappy.pak flappy_aligned.apk
  • 63. Slide URL: https://goo.gl/cIvTb5 Distribute on Google Play 63Advanced Topics / Distribute on Google Play
  • 64. Slide URL: https://goo.gl/cIvTb5 Restrictions for Native App (Android) ● Cannot set own App’s icon ● Only use a debug keystore ● Cannot distribute on Google Play ○ Need to set own App’s icon ○ Need a release keystore ● Cannot use Platform API ○ Cannot use In-app Billing API ○ Cannot use third party API Advanced Topics / Debug on PC 64 OK! OK! OK!
  • 65. Slide URL: https://goo.gl/cIvTb5 Requirement Mobile Games for Business ● In-app Billing ○ Purchase a items in the game ● SNS connection ○ Facebook, Twitter, ... ● Advertisements ● Analytics ○ Google Analytics, Firebase, Facebook Analytics,... Advanced Topics / Requirement of Mobile Games for Business 65 These APIs are provided as Java SDK for Android
  • 66. Slide URL: https://goo.gl/cIvTb5 How to call Android API from Go Advanced Topics / How to call Android API from 66 ● Call Android API through cgo by JNI ○ We should get JavaVM* object in own cgo code ● JavaVM* object is defined in Go Mobile inner package as current_vm variable ○ x/mobile/internal/mobileinit/ctx_android.go ● We also use current_vm in own cgo code
  • 67. Slide URL: https://goo.gl/cIvTb5 Call android.util.Log.d Advanced Topics / Call android.util.Log.d 67 RunOnJVM(func(vm, jniEnv, ctx uintptr) error { env := (*C.JNIEnv)(unsafe.Pointer(jniEnv)) C.logd(env) return nil }) void logd(JNIEnv* env) { jclass log = (*env)->FindClass(env, "android/util/Log"); jmethodID methodD = (*env)->GetStaticMethodID( env, log, "d", "(Ljava/lang/String;Ljava/lang/String;)I"); jstring tag = (*env)->NewStringUTF(env, "log"); jstring message = (*env)->NewStringUTF(env, "hi! JVM"); (*env)->CallStaticIntMethod(env, log, methodD, tag, message); } Go C All Source Code RunOnJVM is copied from ctx_android.go
  • 68. Slide URL: https://goo.gl/cIvTb5 Call own Java Codes from Go codes Advanced Topics / Call own Java Codes from Go codes 68 ● Create a new Android project ● Copy GoNativeActivity and AndroidManifest from GoMobile repositry to own project ● Write own Java codes ● Write application code in Go ○ Call own Java codes with RunOnJVM ● Build Go code to a shared library ● Copy shared library to own Android project ● Build the Android project Do all processes by hand!
  • 69. Slide URL: https://goo.gl/cIvTb5 Toast on Go Mobile Advanced Topics / Toast on Go Mobile 69
  • 70. Slide URL: https://goo.gl/cIvTb5 Plugin System for Game Engine Advanced Topics / Plugin System for Game Engine 70 ● Most Game Engine has a plugin system ○ Unity, Cocos2d-x, ... ○ Facebook Plugin, In-app Billing Plugin, ... ● Go Mobile needs a plugin system Application Code (Go) Own Plugin Java/Obj-C code C code Go/cgo Go Mobile Register Use
  • 71. Slide URL: https://goo.gl/cIvTb5 Summaries ● The Basics of Go Mobile ○ Cross-compile and Android device ○ SDK App and Native App ● Go for Mobile Game ○ Event handling ○ 2D scene graph ● Advanced Topics ○ Distribute apps on Google Play ○ How to use Android API from Go 71
  • 72. Slide URL: https://goo.gl/cIvTb5 Go for Unity Native Plugin ● Unity Native Plugin can be written in Go/cgo Advanced Topics / Go for Unity Native Plugin 72 Unity Native Plugin .so for Android .a for iOS Written in GoGo has good packages to create a communication module!
  • 73. Slide URL: https://goo.gl/cIvTb5 Go for Unity Native Plugin Advanced Topics / Go for Unity Native Plugin 73 package main import "C" //export Hoge func Hoge() int {return 100} func main() {} #if UNITY_IPHONE [DllImport("__Internal")] #else [DllImport("hoge")] #endif private static extern int Hoge(); void Start() {Debug.LogFormat("{0}", Hoge());} Go Unity (C#)
  • 74. Slide URL: https://goo.gl/cIvTb5 Build a Native Plugin for Android Advanced Topics / Build a Native Plugin for Android 74 $ CGO_ENABLED=1 CC=arm-linux-androideabi-gcc GOOS=android GOARCH=arm GOARM=7 go build -buildmode=c-shared -pkgdir= $GOPATH/pkg/gomobile/pkg_android_arm -o libhoge.so hoge.go
  • 75. Slide URL: https://goo.gl/cIvTb5 Build a Native Plugin for iOS Advanced Topics / Build a Native Plugin for iOS 75 GOOS=darwin GOARCH=arm GOARM=7 CC=`xcrun --sdk iphoneos -f clang` CXX=`xcrun --sdk iphoneos -f clang` CGO_CFLAGS="-isysroot `xcrun --sdk iphoneos --show-sdk- path` -arch armv7 -miphoneos-version-min=6.1" CGO_LDFLAGS="-isysroot `xcrun --sdk iphoneos --show-sdk- path` -arch armv7 -miphoneos-version-min=6.1" CGO_ENABLED=1 go build -pkgdir=$GOPATH/pkg/gomobile/pkg_darwin_arm -buildmode=c-archive -tags=ios -o hoge.a hoge.go
  • 79. Slide URL: https://goo.gl/cIvTb5 Run on Android Devices 79 ● Go can build for Android Devices Android DevicePC Cross-compile Run on adb shellpush binary to Android Deivce $ adb push cmd /sdcard The Basics of Go Mobile / Run on Androind Devices
  • 80. Slide URL: https://goo.gl/cIvTb5 Run on Android Devices Watch at Youtube Source Code Android Shell on Mac adb shell The Basics of Go Mobile / Run on Androind Devices 80
  • 81. Slide URL: https://goo.gl/cIvTb5 Handle Lifecycle Event Go for Mobile Game / Handle Lifecycle Event 81 case lifecycle.Event: switch e.Crosses(lifecycle.StageVisible) { case lifecycle.CrossOn: glctx, _ = e.DrawContext.(gl.Context) onStart(glctx) a.Send(paint.Event{}) case lifecycle.CrossOff: onStop() glctx = nil } StageDead StageAlive StageVisible StageFocused