### Install gomobile and gobind Source: https://github.com/golang/mobile/blob/master/example/ivy/android/README.md Install the gomobile and gobind tools. Ensure they are in your system's PATH. ```sh go install golang.org/x/mobile/cmd/gomobile@latest go install golang.org/x/mobile/cmd/gobind@latest ``` -------------------------------- ### Go Documentation for Bindings Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Example of Go documentation comments used with gobind to generate documentation for bindings. ```go // Counter counts up from zero. type Counter struct { // Value is the current count. Value int } // Inc increments the counter. func (c *Counter) Inc() { c.Value++ } ``` -------------------------------- ### Go Mobile Setup Command Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Initializes the Go Mobile environment. Ensure ANDROID_HOME is set correctly for Android development. ```bash gomobile init export ANDROID_HOME=$HOME/Android/Sdk ``` -------------------------------- ### Shader Compilation Example Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md An example demonstrating the common usage pattern for compiling and linking GLSL shaders and creating a program. ```APIDOC ## Shader Compilation Example ### Description An example demonstrating the common usage pattern for compiling and linking GLSL shaders and creating a program. ### Usage Pattern ```go // Create and compile vertex shader vshader := glctx.CreateShader(gl.VERTEX_SHADER) glctx.ShaderSource(vshader, `#version 100 attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); } `) glctx.CompileShader(vshader) // Check compilation if glctx.GetShaderiv(vshader, gl.COMPILE_STATUS) == 0 { log.Fatalf("Vertex shader compile error: %s", glctx.GetShaderInfoLog(vshader)) } // Similar for fragment shader fshader := glctx.CreateShader(gl.FRAGMENT_SHADER) glctx.ShaderSource(fshader, `#version 100 precision mediump float; void main() { gl_FragColor = vec4(1, 0, 0, 1); } `) glctx.CompileShader(fshader) // Link program program := glctx.CreateProgram() glctx.AttachShader(program, vshader) glctx.AttachShader(program, fshader) glctx.LinkProgram(program) if glctx.GetProgramiv(program, gl.LINK_STATUS) == 0 { log.Fatalf("Program link error: %s", glctx.GetProgramInfoLog(program)) } glctx.UseProgram(program) ``` ``` -------------------------------- ### OpenGL Rendering Setup and Drawing Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Demonstrates creating, compiling, and linking OpenGL shaders and programs, then performing a basic draw call. Requires an initialized OpenGL context. ```go import "golang.org/x/mobile/gl" // Create shader shader := glctx.CreateShader(gl.VERTEX_SHADER) glctx.ShaderSource(shader, shaderCode) glctx.CompileShader(shader) // Create program program := glctx.CreateProgram() glctx.AttachShader(program, shader) glctx.LinkProgram(program) glctx.UseProgram(program) // Draw glctx.Clear(gl.COLOR_BUFFER_BIT) glctx.DrawArrays(gl.TRIANGLES, 0, 3) glctx.Flush() ``` -------------------------------- ### Install App on Android Device Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Compile and install a Go mobile application on an attached Android device using gomobile install. ```bash gomobile install golang.org/myapp ``` -------------------------------- ### Event Processing Example Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md A comprehensive example demonstrating how to handle various event types including lifecycle, paint, size, touch, mouse, and key events. ```APIDOC ## Event Processing Example Comprehensive example handling all event types: ```go package main import ( "golang.org/x/mobile/app" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/mouse" "golang.org/x/mobile/event/paint" "golang.org/x/mobile/event/size" "golang.org/x/mobile/event/touch" ) func main() { app.Main(func(a app.App) { var windowWidth, windowHeight int var glctx interface{} for e := range a.Events() { e = a.Filter(e) if e == nil { continue } switch e := e.(type) { case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { glctx = e.DrawContext } case paint.Event: drawFrame(glctx, windowWidth, windowHeight) a.Publish() case size.Event: windowWidth = e.WidthPx windowHeight = e.HeightPx case touch.Event: handleTouch(e.X, e.Y, e.Type, e.Sequence) case mouse.Event: if e.Direction == mouse.DirPress { handleMousePress(e.X, e.Y, e.Button) } case key.Event: if e.Direction == key.DirPress { handleKeyPress(e.Code, e.Rune, e.Modifiers) } } } }) } ``` ``` -------------------------------- ### Go Library Initialization Pattern Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md A common pattern for initializing a Go library with a one-time setup function. This ensures that resources are prepared before API calls are made. ```go package mylib var initialized bool func Init() error { // One-time setup initialized = true return nil } type API struct{} func (a *API) DoWork(input string) (string, error) { if !initialized { return "", fmt.Errorf("not initialized") } // Do work return "result", nil } ``` -------------------------------- ### Shader Compilation and Linking Example Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Demonstrates the process of creating, compiling, and linking vertex and fragment shaders into a program. Includes error checking for compilation and linking steps. Use this pattern when setting up shaders for rendering. ```go // Create and compile vertex shader vshader := glctx.CreateShader(gl.VERTEX_SHADER) glctx.ShaderSource(vshader, `#version 100 attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); } `) glctx.CompileShader(vshader) // Check compilation if glctx.GetShaderiv(vshader, gl.COMPILE_STATUS) == 0 { log.Fatalf("Vertex shader compile error: %s", glctx.GetShaderInfoLog(vshader)) } // Similar for fragment shader fshader := glctx.CreateShader(gl.FRAGMENT_SHADER) glctx.ShaderSource(fshader, `#version 100 precision mediump float; void main() { gl_FragColor = vec4(1, 0, 0, 1); } `) glctx.CompileShader(fshader) // Link program program := glctx.CreateProgram() glctx.AttachShader(program, vshader) glctx.AttachShader(program, fshader) glctx.LinkProgram(program) if glctx.GetProgramiv(program, gl.LINK_STATUS) == 0 { log.Fatalf("Program link error: %s", glctx.GetProgramInfoLog(program)) } glctx.UseProgram(program) ``` -------------------------------- ### Initialize Gomobile Environment Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Initializes the mobile development environment. Run this once per development setup. It can optionally build OpenAL for Android. ```bash gomobile init # Initialize with custom OpenAL gomobile init -openal ~/openal-soft ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md This command installs the necessary Xcode command line tools to resolve 'Xcode Not Found' errors on macOS. Verify the installation by checking the Xcode path. ```bash # Install Xcode from App Store or: xcode-select --install # Verify installation xcode-select -p # Should show Xcode path ``` -------------------------------- ### Example Debug Log Output Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Shows a sample of the log output generated when the `gldebug` build tag is enabled, detailing GL function calls and their parameters. ```text I/GoLog (27668): gl.GenBuffers(1) [Buffer(70001)] I/GoLog (27668): gl.BindBuffer(ARRAY_BUFFER, Buffer(70001)) I/GoLog (27668): gl.BufferData(ARRAY_BUFFER, 36, 36, STATIC_DRAW) I/GoLog (27668): gl.VertexAttribPointer(Attrib(0), 2, FLOAT, false, 8, 0) ``` -------------------------------- ### Coordinate Conversion Example Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Convert between pixel and point coordinate systems using geom.Pt. Ensure correct scaling with pixelsPerPt. ```go // Pixel to point touchPoint := geom.Point{ X: geom.Pt(touchEvent.X / pixelsPerPt), Y: geom.Pt(touchEvent.Y / pixelsPerPt), } // Point to pixel pixelX := int(touchPoint.X.Px(pixelsPerPt)) pixelY := int(touchPoint.Y.Px(pixelsPerPt)) ``` -------------------------------- ### Handle Lifecycle Event Transitions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Example of handling lifecycle events to manage rendering based on app focus. Requires type assertion for the DrawContext. ```go case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { glctx := e.DrawContext.(gl.Context) // Start rendering } if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOff { // Stop rendering } ``` -------------------------------- ### Build for Specific iOS Architectures Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Specify precise architectures for iOS devices and simulators. For example, arm64 for devices and x86_64 for simulators. ```bash gomobile build -target ios/arm64,iossimulator/x86_64 golang.org/myapp ``` -------------------------------- ### Accessing Bundled Assets in Go Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Example of how to open an asset file from the /assets directory within Go code. Assets are automatically bundled into AARs for Android and resource bundles for iOS. ```go data, err := asset.Open("config.json") ``` -------------------------------- ### Custom AndroidManifest.xml Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Example of a custom AndroidManifest.xml file for Android APK builds, specifying application details and permissions. ```xml ``` -------------------------------- ### Handle Paint Event for Rendering Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Example of handling paint events to render a frame and publish it. Ignores external paint events if actively drawing via vsync to avoid backlog. Must be followed by App.Publish(). ```go case paint.Event: // Render frame drawScene(glctx) // Swap buffers result := a.Publish() if !result.BackBufferPreserved { // Screen cleared, must redraw next frame } ``` -------------------------------- ### Set ANDROID_HOME Environment Variable Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Configure the ANDROID_HOME environment variable to point to the Android SDK installation directory, required for Android builds. ```bash export ANDROID_HOME=$HOME/Android/Sdk ``` -------------------------------- ### Get and Use Screen Dimensions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/geom.md Retrieve screen dimensions in points from a size.Event and use them to calculate center coordinates for rendering objects. ```go var screenW, screenH geom.Pt case size.Event: sscreenW = e.WidthPt screenH = e.HeightPt // Center an object centerX := screenW / 2 centerY := screenH / 2 // Render at center case paint.Event: centerXPx := int(centerX.Px(pixelsPerPt)) centerYPx := int(centerY.Px(pixelsPerPt)) drawObject(centerXPx, centerYPx) ``` -------------------------------- ### Run Go Mobile Application Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/app.md Starts the mobile application by invoking a provided function with the App interface on a separate goroutine. The Main function blocks until the app lifecycle ends. ```go package main import ( "golang.org/x/mobile/app" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" ) func main() { app.Main(func(a app.App) { for e := range a.Events() { switch e := a.Filter(e).(type) { case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { // App gained focus } case paint.Event: // Render frame here a.Publish() } } }) } ``` -------------------------------- ### Build for Android with Specific API Level Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md This command addresses the 'SDK Not Found' error by building for Android with a specified API level. Ensure the required Android SDK platform is installed or adjust the -androidapi version accordingly. ```bash # Install API level via Android SDK Manager # or use appropriate -androidapi version gomobile build -target android -androidapi 21 golang.org/myapp ``` -------------------------------- ### Basic Application Lifecycle and Event Handling Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Sets up the main application loop, handling lifecycle events and paint events for rendering. This is the entry point for most golang/mobile applications. ```go package main import ( "golang.org/x/mobile/app" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" ) func main() { app.Main(func(a app.App) { for e := range a.Events() { e = a.Filter(e) if e == nil { continue } switch e := e.(type) { case lifecycle.Event: handleLifecycle(e) case paint.Event: renderFrame() a.Publish() } } }) } ``` -------------------------------- ### size.Event Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Represents window dimensions and screen resolution information. It provides methods to get the window size and bounds. ```APIDOC ## Event Type: size.Event ### Description Provides window dimensions and screen resolution information. ### Fields - **WidthPx** (int) - Window width in pixels - **HeightPx** (int) - Window height in pixels - **WidthPt** (geom.Pt) - Window width in typographic points (1/72 inch) - **HeightPt** (geom.Pt) - Window height in typographic points - **PixelsPerPt** (float32) - Pixels per typographic point; varies by device density - **Orientation** (Orientation) - Screen orientation (portrait/landscape) ### Methods #### Event.Size() image.Point Returns window dimensions as an `image.Point`. #### Event.Bounds() image.Rectangle Returns window bounds as an `image.Rectangle` with top-left at (0,0). ### Example ```go case size.Event: width := e.WidthPx height := e.HeightPx dpi := e.PixelsPerPt * 72 // Convert to pixels per inch // Set OpenGL viewport glctx.Viewport(0, 0, width, height) // Adjust projection matrix setupProjection(float32(width), float32(height)) // Check orientation sswitch e.Orientation { case size.OrientationPortrait: // Handle portrait case size.OrientationLandscape: // Handle landscape } ``` ``` -------------------------------- ### Build iOS Framework Source: https://github.com/golang/mobile/blob/master/_autodocs/README.md Command to build an iOS framework from Go code. ```bash gomobile bind -target ios -prefix GoMylib golang.org/mylib ``` -------------------------------- ### Production Build for Size Optimization Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Create a production-ready binary by stripping symbols and debug information and setting the release tag. This results in a smaller binary size and reduced debug information. ```bash gomobile build \ -ldflags="-s -w" \ -tags release \ golang.org/myapp ``` -------------------------------- ### Event Type Assertion Example Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Handle different event types received on the app.Events() channel using a type switch. ```go e := <-app.Events() switch e := e.(type) { case lifecycle.Event: // Handle lifecycle case touch.Event: // Handle touch case paint.Event: // Handle paint } ``` -------------------------------- ### Create Framebuffer with Texture Attachment Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Shows how to create a framebuffer, bind it, create a texture attachment, and configure it for rendering. It includes a check for framebuffer completeness. ```go fb := glctx.CreateFramebuffer() glctx.BindFramebuffer(gl.FRAMEBUFFER, fb) tex := glctx.CreateTexture() glctx.BindTexture(gl.TEXTURE_2D, tex) glctx.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, nil) glctx.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0) status := glctx.CheckFramebufferStatus(gl.FRAMEBUFFER) if status != gl.FRAMEBUFFER_COMPLETE { log.Fatalf("Framebuffer incomplete: 0x%x", status) } ``` -------------------------------- ### Default iOS Build (Device and Simulator) Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Create an XCFramework that includes slices for both iOS devices and simulators by default. ```bash gomobile build -target ios,iossimulator golang.org/myapp ``` -------------------------------- ### Get Window Dimensions using Event.Size() Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Retrieves the window dimensions as an image.Point. Useful for immediate display of pixel dimensions. ```go case size.Event: bounds := e.Size() fmt.Printf("Window: %dx%d pixels\n", bounds.X, bounds.Y) ``` -------------------------------- ### Safe Asset Loading with Error Handling Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md Illustrates the correct way to open and read assets, including essential error checking at each step. This pattern prevents runtime errors caused by missing assets or read failures. ```Go // INCORRECT: Ignores error, panics on use f, _ := asset.Open("data.json") data := io.ReadAll(f) // CORRECT: Check and handle error f, err := asset.Open("data.json") if err != nil { log.Printf("Failed to open asset: %v", err) return err } deferr f.Close() data, err := io.ReadAll(f) if err != nil { return err } ``` -------------------------------- ### Main Application Entry Point Source: https://github.com/golang/mobile/blob/master/_autodocs/README.md This is the main entry point for a golang/mobile application. It sets up the application lifecycle and event handling, including drawing context for OpenGL. ```go package main import ( "golang.org/x/mobile/app" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" "golang.org/x/mobile/gl" ) func main() { app.Main(func(a app.App) { for e := range a.Events() { switch e := a.Filter(e).(type) { case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { glctx := e.DrawContext.(gl.Context) // GL context available } case paint.Event: // Render frame a.Publish() } } }) } ``` -------------------------------- ### Go to Objective-C Naming Conventions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Shows how Go package and function names are converted to Objective-C. Package functions are prefixed with 'Go' and the package name. ```go package mypkg func NewCounter() *Counter func (c *Counter) Inc() func GetName(c *Counter) string ``` -------------------------------- ### Accessing Assets in Go Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Demonstrates how to open and read asset files from the 'assets/' directory using the 'golang.org/x/mobile/asset' package. ```go import "golang.org/x/mobile/asset" data, err := asset.Open("images/logo.png") ``` -------------------------------- ### Get Window Bounds using Event.Bounds() Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Retrieves the window bounds as an image.Rectangle, with the top-left corner at (0,0). Used for setting the OpenGL viewport. ```go case size.Event: rect := e.Bounds() glctx.Viewport(0, 0, rect.Max.X, rect.Max.Y) ``` -------------------------------- ### Build Pipeline for Cross-Language Bindings Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Details the steps for generating language bindings and native libraries from Go source code. ```text Go source → gobind → Java stubs + ObjC headers ↓ Binding code generation ↓ Native library compilation ↓ AAR (Android) or Framework (iOS) ``` -------------------------------- ### File Interface Methods Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Demonstrates using the File interface, which embeds io.ReadSeeker and io.Closer. It shows how to read a portion of an asset, determine its size by seeking to the end, and reset the position. ```go f, _ := asset.Open("image.png") deffer f.Close() // Read first 100 bytes buf := make([]byte, 100) n, _ := f.Read(buf) // Seek to end to get size size, _ := f.Seek(0, io.SeekEnd) // Seek back to start f.Seek(0, io.SeekStart) ``` -------------------------------- ### Define Touch Type Constants Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Defines constants for touch event types: TypeBegin, TypeMove, and TypeEnd, indicating the start, progression, or conclusion of a touch interaction. ```go type Type byte const ( TypeBegin Type = iota // Touch began TypeMove // Touch moved TypeEnd // Touch ended ) ``` -------------------------------- ### Generate Mobile.xcframework for iOS Source: https://github.com/golang/mobile/blob/master/example/ivy/ios/README.md Sets up a working directory, initializes a Go module, fetches dependencies, and binds Go packages for iOS development, creating a Mobile.xcframework. ```bash mkdir work; cd work go mod init work go get -d golang.org/x/mobile/bind@latest go get -d robpike.io/ivy/mobile gomobile bind -target=ios,iossimulator,maccatalyst,macos robpike.io/ivy/mobile robpike.io/ivy/demo ``` -------------------------------- ### Build Pipeline for All-Go Apps Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Shows the process of building an all-Go application into an executable format for Android or iOS. ```text Go source → gomobile build → APK (Android) or IPA (iOS) ``` -------------------------------- ### Initialize Gomobile with NDK Path Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Set the ANDROID_NDK_HOME environment variable to the path of your Android NDK and run 'gomobile init' to resolve NDK not found errors. ```bash export ANDROID_NDK_HOME=/path/to/ndk gomobile init ``` -------------------------------- ### Set ANDROID_NDK_HOME and Initialize Go Mobile Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md This command sequence is used to resolve the 'NDK Not Found' build error. It sets the ANDROID_NDK_HOME environment variable to the NDK's location and then initializes Go Mobile. ```bash export ANDROID_NDK_HOME=/path/to/android-ndk gomobile init ``` -------------------------------- ### Define Keyboard Code Type Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Defines the type for keyboard key codes, which identify physical keys using standard USB HID codes. Non-standard keys are assigned codes starting from 0x10000. ```go type Code uint32 ``` -------------------------------- ### Resource Management with Close Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Demonstrates a resource struct with a handle, a constructor, a method to use the resource, and a Close method for releasing the underlying handle. ```go type Resource struct { // unexported implementation handle uintptr } func NewResource() *Resource { return &Resource{handle: createHandle()} } func (r *Resource) Use() { // Use resource } func (r *Resource) Close() error { return releaseHandle(r.handle) } ``` -------------------------------- ### Build iOS App Source: https://github.com/golang/mobile/blob/master/_autodocs/README.md Command to build an iOS application using Go. ```bash gomobile build -target ios -bundleid com.example.app golang.org/myapp ``` -------------------------------- ### Asset Directory Structure Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Illustrates the recommended directory structure for placing asset files within a Go mobile project. ```text myapp/ main.go assets/ images/ logo.png shaders/ vertex.glsl data/ config.json ``` -------------------------------- ### Go Constructor Shorthand to Java Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Shows how Go functions matching `NewT(...) *T` pattern become Java constructors. Both direct constructor calls and factory methods are available. ```go func NewCounter() *Counter // Java: new Counter() func NewServer(port int) *Server // In Java Counter c = new Counter(); Server s = new Server(8080); // Also available as factory methods Counter c = Mypkg.newCounter(); Server s = Mypkg.newServer(8080); ``` -------------------------------- ### Generate iOS Framework Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Use gomobile bind to create an iOS framework for a Go package. ```bash gomobile bind -target ios -prefix GoMylib -o GoMylib.xcframework golang.org/mylib ``` -------------------------------- ### Enable Debug Logging with Build Tag Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Explains how to compile the Go project with the `gldebug` build tag to enable tracing of all OpenGL calls. This is useful for debugging but has high performance overhead. ```bash go build -tags gldebug ``` -------------------------------- ### Create and Upload Buffer Data Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Demonstrates creating a buffer, binding it, uploading vertex data, and linking it to a vertex attribute. Ensure `unsafeFloatsToBytes` is defined elsewhere. ```go buf := glctx.CreateBuffer() glctx.BindBuffer(gl.ARRAY_BUFFER, buf) vertices := []float32{ -0.5, -0.5, 0.5, -0.5, 0, 0.5, } glctx.BufferData(gl.ARRAY_BUFFER, unsafeFloatsToBytes(vertices), gl.STATIC_DRAW) posAttr := glctx.GetAttribLocation(program, "position") glctx.EnableVertexAttribArray(posAttr) glctx.VertexAttribPointer(posAttr, 2, gl.FLOAT, false, 8, 0) ``` -------------------------------- ### Verbose Build Output in Golang Mobile Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md Provides detailed build steps, including packages being built and commands executed. Use the -v flag for comprehensive build information. ```bash gomobile build -v -target android golang.org/myapp ``` -------------------------------- ### Asset Loading from Bundled Resources Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Opens and reads data from a bundled asset file. Ensure the asset path is correct and the file exists in the asset directory. ```go import ( "golang.org/x/mobile/asset" "io" ) data, err := asset.Open("shaders/vertex.glsl") if err != nil { log.Fatal(err) } def data.Close() source, _ := io.ReadAll(data) ``` -------------------------------- ### Build All-Go Android App Source: https://github.com/golang/mobile/blob/master/_autodocs/README.md Command to build a standalone Android application entirely in Go. ```bash gomobile build -target android -o app.apk golang.org/myapp ``` -------------------------------- ### Set Android SDK and NDK Paths Source: https://github.com/golang/mobile/blob/master/example/ivy/android/README.md Set ANDROID_HOME and ANDROID_NDK_HOME environment variables if gomobile cannot locate your SDK and NDK. ```sh export ANDROID_HOME=/path/to/sdk-directory export ANDROID_NDK_HOME=/path/to/ndk-directory ``` -------------------------------- ### GL Resource Creation and Usage Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Demonstrates the lifecycle of a GL texture resource: creation, binding, data upload, and deletion. Use glctx and gl package functions. ```go // Create resource texture := glctx.CreateTexture() // Bind for use glctx.BindTexture(gl.TEXTURE_2D, texture) // Use in operations glctx.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, data) // Delete when done glctx.DeleteTexture(texture) ``` -------------------------------- ### Production Build for Android Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Create a production-ready build for Android. This build is smaller, has stripped symbols and debug info, and no file paths in the binary. ```bash gomobile build \ -target android \ -ldflags="-s -w" \ -trimpath \ golang.org/myapp ``` -------------------------------- ### Reinstall App with Rebuild Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Force a rebuild and reinstallation of a Go mobile application on an Android device. ```bash gomobile install -a golang.org/myapp ``` -------------------------------- ### Go to Java Naming Conventions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Illustrates how Go function and method names are converted to Java camelCase. Note the handling of slices. ```go func NewCounter() *Counter // Java: newCounter() func (c *Counter) Inc() // Java: c.inc() func ProcessData(b []byte) // Java: processData(byte[] b) ``` -------------------------------- ### Build All-Go App for Android Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Compiles a Go application into an Android APK. Specify the target platform and output file. ```bash gomobile build -target android -o app.apk ./cmd/myapp ``` -------------------------------- ### Reverse Binding: Calling Java API from Go Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Demonstrates how Go code can import and call Java APIs. Ensure the Java class and method exist and are accessible. ```go import "Java/java/lang/System" t := System.CurrentTimeMillis() ``` -------------------------------- ### Error Handling for Asset Opening Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Shows how to handle errors when opening an asset file, specifically checking for `*os.PathError` to extract operation and path details. ```go f, err := asset.Open("nonexistent.txt") if err != nil { pathErr := err.(*os.PathError) fmt.Printf("Operation: %s, Path: %s\n", pathErr.Op, pathErr.Path) } ``` -------------------------------- ### Device Scaling Conversion Pattern Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/geom.md Illustrates the standard pattern for handling device-independent positioning: store in points, convert to pixels for rendering, and convert input events from pixels to points. ```go // Application stores dimensions in points type GameState struct { playerX, playerY geom.Pt playerWidth, playerHeight geom.Pt } // In size.Event handler case size.Event: state.pixelsPerPt = e.PixelsPerPt // Store screen bounds in points state.screenWidthPt = e.WidthPt state.screenHeightPt = e.HeightPt // In touch.Event handler case touch.Event: // Convert pixel coordinates to points touchX := geom.Pt(e.X / e.PixelsPerPt) touchY := geom.Pt(e.Y / e.PixelsPerPt) state.handleTouchAt(touchX, touchY) // In paint.Event handler case paint.Event: // Convert points back to pixels for rendering playerXPx := int(state.playerX.Px(state.pixelsPerPt)) playerYPx := int(state.playerY.Px(state.pixelsPerPt)) glctx.Viewport(playerXPx, playerYPx, ...) ``` -------------------------------- ### Event Flow Architecture Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Illustrates the sequence of events from OS to application handler and screen update. ```text OS Events ↓ App.Events() channel ↓ App.Filter() ← Filters can consume/modify events ↓ Type assertion (e.g., touch.Event) ↓ Application event handler ↓ GL drawing commands (if paint event) ↓ App.Publish() → Screen update ``` -------------------------------- ### Loading Configuration Files Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md A function to load and parse JSON configuration files from assets. It opens the asset, decodes the JSON content into a map, and returns the configuration. ```go func loadConfig(name string) (map[string]interface{}, error) { f, err := asset.Open("config/" + name) if err != nil { return nil, err } defer f.Close() var cfg map[string]interface{} json.NewDecoder(f).Decode(&cfg) return cfg, nil } ``` -------------------------------- ### Build with Android Tag Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Compile a Go package with the 'android' build tag enabled. ```bash gomobile build -tags android golang.org/myapp ``` -------------------------------- ### app.Main Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/app.md Initializes and runs the mobile application by invoking a provided function with an App interface. It manages the app lifecycle and event handling on a separate goroutine. ```APIDOC ## func Main(f func(App)) ### Description Main is called by the main.main function to run the mobile application. It invokes the provided function `f` with an `App` interface on a separate goroutine, as OS-specific libraries often require execution on the main thread. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **f** (func(App)) - Required - Function to execute with the App interface. ### Returns None ### Behavior The main function blocks until the app lifecycle ends. On Android, this corresponds to the app being destroyed. On iOS, this occurs when the app is terminated. ### Request Example ```go package main import ( "golang.org/x/mobile/app" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/paint" ) func main() { app.Main(func(a app.App) { for e := range a.Events() { switch e := a.Filter(e).(type) { case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { // App gained focus } case paint.Event: // Render frame here a.Publish() } } }) } ``` ``` -------------------------------- ### Open(name string) (File, error) Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Opens a named asset by relative path and returns a file-like interface for reading and seeking. Platform-specific asset lookup is handled automatically. ```APIDOC ## Open(name string) (File, error) ### Description Opens a named asset by relative path and returns a file-like interface for reading and seeking. ### Method Open ### Parameters #### Path Parameters - **name** (string) - Required - Relative path to the asset file ### Returns - **file** (File) - File-like interface for reading the asset content - **error** (error) - Error of type *os.PathError if the asset cannot be found or opened ### Example ```go // Load a shader file shaderFile, err := asset.Open("shaders/vertex.glsl") if err != nil { log.Fatal(err) } defer shaderFile.Close() // Read shader content data, err := io.ReadAll(shaderFile) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Go Code Demonstrating Safe Callback Usage Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Illustrates a 'good' pattern in Go for using callbacks without storing references to foreign objects, thus avoiding reference cycles. ```go // GOOD: Use callback without storing reference type MyProcessor struct { // No reference to foreign objects } func (p *MyProcessor) Process(callback Callback) { // Use callback locally, don't store callback.OnResult(42) } ``` -------------------------------- ### Generate iOS Framework with Specific Architectures Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Specify target architectures for generating an iOS framework using gomobile bind. ```bash gomobile bind -target ios/arm64,iossimulator/arm64 golang.org/mylib ``` -------------------------------- ### Open and Read Asset File Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Opens a named asset file and reads its entire content. Ensure to close the file after use. This is useful for loading shader files or other raw asset data. ```go // Load a shader file shaderFile, err := asset.Open("shaders/vertex.glsl") if err != nil { log.Fatal(err) } deffer shaderFile.Close() // Read shader content data, err := io.ReadAll(shaderFile) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Shader and Program Management Functions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Provides functions for creating, compiling, linking, and managing OpenGL shaders and programs. ```go CreateShader(ty Enum) Shader ShaderSource(s Shader, source string) CompileShader(s Shader) GetShaderiv(s Shader, pname Enum) int32 GetShaderInfoLog(s Shader) string DeleteShader(v Shader) CreateProgram() Program AttachShader(p Program, s Shader) LinkProgram(p Program) UseProgram(p Program) GetProgramiv(p Program, pname Enum) int32 GetProgramInfoLog(p Program) string DeleteProgram(v Program) ``` -------------------------------- ### gobind.md - Language Binding Generation Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Documentation for language binding generation, enabling Go code to be called from Java/Objective-C and vice versa. Covers forward and reverse bindings, type support, and framework generation. ```APIDOC ## gobind.md - Language Binding Generation ### Description Language binding generation for calling Go from Java/Objective-C and vice versa. This package facilitates cross-language communication and native library creation. ### Key Concepts - Forward bindings: Go → Java/Objective-C - Reverse bindings: Java/Objective-C → Go - Type restrictions and supported types - Memory management and reference cycles - Android AAR and iOS framework generation ### Scope Creating cross-language APIs and native libraries. ### Use when Building Android libraries (AAR) or iOS frameworks, or calling native APIs from Go. ``` -------------------------------- ### Perform Drawing Operations Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Illustrates common drawing operations including clearing the screen, setting up blending and viewport, and issuing a draw call. Ensure `width` and `height` are defined. ```go glctx.ClearColor(0.2, 0.3, 0.3, 1.0) glctx.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) glctx.Enable(gl.BLEND) glctx.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) glctx.Viewport(0, 0, width, height) glctx.DrawArrays(gl.TRIANGLES, 0, 3) glctx.Flush() ``` -------------------------------- ### Enable Platform-Specific Code with Build Tags Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Use Go build tags to enable platform-specific code, such as Android-specific logging. ```go //go:build android package myapp import "android/log" func LogMessage(msg string) { log.Printf("MyApp", msg) } ``` -------------------------------- ### app.md - Core Application Lifecycle Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Documentation for the core application lifecycle and event management interface. This includes the entry point for Go mobile apps and the main app interface for event handling. ```APIDOC ## app.md - Core Application Lifecycle ### Description Core application lifecycle and event management interface. This package provides the entry point for all-Go mobile applications and the main interface for managing app events. ### Key Types - `app.Main(func(App))` — Entry point for all-Go mobile apps - `app.App` interface — Main app interface with event channel, publishing, filtering - `app.PublishResult` — Drawing buffer state information ### Scope Event processing loop setup, app lifecycle management, screen publishing. ### Use when Building all-Go mobile applications for iOS and Android. ``` -------------------------------- ### Enable Verbose Output for Gobind Build Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Command to enable verbose output during the gomobile bind process, useful for inspecting generated code and build steps. ```bash gomobile bind -v -target android golang.org/mylib ``` -------------------------------- ### asset.md - Access to Bundled Application Resources Source: https://github.com/golang/mobile/blob/master/_autodocs/INDEX.md Documentation for accessing bundled application resources and assets. This includes functions for opening asset files and the interface for file-like access. ```APIDOC ## asset.md - Access to Bundled Application Resources ### Description Access to bundled application resources and assets. This package allows you to load files that are bundled with your application. ### Key Functions - `asset.Open(name string) (File, error)` — Load bundled asset files - `asset.File` interface — File-like access to assets (Read, Seek, Close) ### Scope Loading images, shaders, configuration files, and other bundled data. ### Use when Loading resources bundled with your application. ``` -------------------------------- ### Rendering Functions Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Provides core functions for clearing buffers, drawing primitives, and setting the viewport. ```go Clear(mask Enum) ClearColor(red, green, blue, alpha float32) ClearDepthf(d float32) ClearStencil(s int) DrawArrays(mode Enum, first, count int) DrawElements(mode Enum, count int, ty Enum, offset int) Viewport(x, y, width, height int) Flush() ``` -------------------------------- ### Shader and Program Management Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Methods for creating, compiling, linking, and managing OpenGL shaders and programs, including error log retrieval. ```APIDOC ## Shader and Program Management ### Description Methods for creating, compiling, linking, and managing OpenGL shaders and programs, including error log retrieval. ### Methods - **CreateShader(ty Enum) Shader** - **ShaderSource(s Shader, source string)** - **CompileShader(s Shader)** - **GetShaderiv(s Shader, pname Enum) int32** - **GetShaderInfoLog(s Shader) string** - **DeleteShader(v Shader)** - **CreateProgram() Program** - **AttachShader(p Program, s Shader)** - **LinkProgram(p Program)** - **UseProgram(p Program)** - **GetProgramiv(p Program, pname Enum) int32** - **GetProgramInfoLog(p Program) string** - **DeleteProgram(v Program)** ``` -------------------------------- ### Set ANDROID_NDK_HOME Environment Variable Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Optionally set the ANDROID_NDK_HOME environment variable to specify the path to the Android NDK. ```bash export ANDROID_NDK_HOME=$HOME/android-ndk-r21 ``` -------------------------------- ### Accessing Android Assets Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Illustrates how to open an asset file located within the `assets/` directory on Android. The path provided to `asset.Open` is relative to this directory. ```go // Access src/main/assets/images/logo.png img, _ := asset.Open("images/logo.png") ``` -------------------------------- ### OpenGL Program Structure Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Identifies a compiled shader program. The 'Init' field indicates if the program has been successfully initialized. ```go type Program struct { Init bool Value uint32 } ``` -------------------------------- ### Build iOS XCFramework Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Command to build a Go package into an iOS XCFramework using gomobile bind. This creates a universal framework for multiple architectures and OS versions. ```bash gomobile bind -target ios -bundleid com.example.mylib \ -o GoMylib.xcframework golang.org/mylib ``` -------------------------------- ### Build Android Library (AAR) Source: https://github.com/golang/mobile/blob/master/_autodocs/README.md Command to build an Android Archive (AAR) library from Go code. ```bash gomobile bind -target android -o mylib.aar golang.org/mylib ``` -------------------------------- ### Build for Specific Android Architectures Source: https://github.com/golang/mobile/blob/master/_autodocs/configuration.md Specify a subset of Android architectures for the build. Supported architectures include arm, arm64, 386, and amd64. ```bash gomobile build -target android/arm,android/arm64 golang.org/myapp ``` -------------------------------- ### Lifecycle Stage Constants Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Represents app lifecycle states in order of increasing activity. Applications transition through these stages in response to OS lifecycle events. ```go type Stage uint32 const ( StageDead Stage = iota StageAlive StageVisible StageFocused ) ``` -------------------------------- ### Update Go Dependencies Source: https://github.com/golang/mobile/blob/master/example/ivy/android/README.md Fetch the latest versions of Go dependencies and tidy the module. ```sh go get -d golang.org/x/mobile@latest go get -d robpike.io/ivy/mobile go mod tidy ``` -------------------------------- ### gl.Program Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md Identifies a compiled shader program in OpenGL. The 'Init' field indicates if it has been successfully initialized. ```APIDOC ## gl.Program ### Description Identifies a compiled shader program. ### Fields - **Init bool**: True if the program has been initialized. - **Value uint32**: The OpenGL program handle. ``` -------------------------------- ### Project File Structure Source: https://github.com/golang/mobile/blob/master/_autodocs/COMPLETION_REPORT.md This tree outlines the generated markdown files and their respective sizes and purposes within the output directory. ```tree output/ ├── README.md # Overview and getting started (9.9 KB) ├── INDEX.md # Master index with quick reference (14 KB) ├── types.md # Type reference documentation (12 KB) ├── configuration.md # Build configuration and options (13 KB) ├── errors.md # Error handling and troubleshooting (11 KB) └── api-reference/ # Detailed API documentation (6 files) ├── app.md # App lifecycle and event management (7.6 KB) ├── asset.md # Asset access API (4.9 KB) ├── events.md # Complete event system (14 KB) ├── gl.md # OpenGL ES bindings (12 KB) ├── geom.md # Geometry types (8.3 KB) └── gobind.md # Language binding generation (12 KB) ``` -------------------------------- ### lifecycle.Event Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/events.md Represents a transition between app lifecycle stages. It includes fields for the transition's origin and destination stages, and an optional GL context for drawing. ```APIDOC ## Event Type ```go type Event struct { From, To Stage DrawContext interface{} } ``` Represents a transition between app lifecycle stages. **Fields:** | Field | Type | Description | |-------|------|-------------| | From | Stage | The stage the app is transitioning from | | To | Stage | The stage the app is transitioning to | | DrawContext | interface{} | GL context if drawing is valid (normally a gl.Context). Non-nil when transitioning to a visible stage. | **Example:** ```go case lifecycle.Event: if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOn { glctx := e.DrawContext.(gl.Context) // Start rendering } if e.Crosses(lifecycle.StageFocused) == lifecycle.CrossOff { // Stop rendering } ``` ``` -------------------------------- ### Partial Asset Reading with Seek Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/asset.md Demonstrates reading only a specific portion of an asset file. It uses `Seek` to skip initial bytes and then `Read` to retrieve a subsequent block of data. ```go f, _ := asset.Open("data.bin") deffer f.Close() // Skip first 512 bytes f.Seek(512, io.SeekStart) // Read next 256 bytes buf := make([]byte, 256) f.Read(buf) ``` -------------------------------- ### Go Interface Implementation in Java Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gobind.md Explains how Go interfaces are implemented in Java. The Java implementation can then be passed to Go code. ```go // Go interface interface Reader { Read(b []byte) (int, error) } // Java interface public interface Reader { long read(byte[] b) throws Exception; } // Implement in Java class MyReader implements Reader { public long read(byte[] b) { // Implementation return b.length; } } // Pass to Go MyReader r = new MyReader(); mypkg.Process(r); // Go receives Reader implementation ``` -------------------------------- ### Safe GL Context Usage Source: https://github.com/golang/mobile/blob/master/_autodocs/errors.md Demonstrates how to safely use the GL context by checking if it is non-nil before performing GL operations. This prevents errors when GL calls are made before the StageFocused event or if the context has been destroyed. ```Go if e.DrawContext != nil { glctx := e.DrawContext.(gl.Context) // Safe to use GL } ``` -------------------------------- ### Asset File Interface Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md A file-like interface for reading assets, supporting Read, Seek, and Close operations. It embeds io.ReadSeeker and io.Closer. ```go type File interface { io.ReadSeeker io.Closer } ``` -------------------------------- ### size.Event Struct Source: https://github.com/golang/mobile/blob/master/_autodocs/types.md The size.Event provides window dimensions and screen resolution information, including pixel and point dimensions, and pixel density. ```APIDOC ## size.Event Struct ### Description Provides window dimensions and screen resolution information. WidthPt and HeightPt are in typographic points for device independence. ### Fields - `WidthPx, HeightPx int`: Window dimensions in pixels. - `WidthPt, HeightPt geom.Pt`: Window dimensions in points (1/72 inch). - `PixelsPerPt float32`: Pixel density for coordinate conversion. - `Orientation Orientation`: Screen orientation state. ### Location `golang.org/x/mobile/event/size` ``` -------------------------------- ### Check for OpenGL ES 3.0 Context Source: https://github.com/golang/mobile/blob/master/_autodocs/api-reference/gl.md Demonstrates how to check if the current OpenGL context supports ES 3.0 features and access its specific methods. This is useful for conditionally using advanced functionality. ```go if ctx3, ok := glctx.(gl.Context3); ok { // ES 3.0 specific calls ctx3.BlitFramebuffer(...) ctx3.GetStringi(...) // ... additional ES 3.0 methods } ```