# 📖 API Reference v0.2.9 - SevenX Engine
## 🆕 Novidades v0.2.9 - Suporte Android Completo!
### 📱 AndroidManager - Gerenciador Android
```rust
use sevenx_engine::AndroidManager;
// Criar gerenciador
let mut android = AndroidManager::new();
// Habilitar features
android.enable_touch();
android.enable_virtual_joystick(100.0, 500.0, 80.0);
android.enable_sensors();
android.enable_vibration();
// Atualizar (chamar todo frame)
android.update();
```
### 👆 Touch Input Multi-Touch
```rust
// Obter todos os toques
let touches = android.get_touches();
for touch in touches {
println!("ID: {}, Pos: ({}, {})", touch.id, touch.x, touch.y);
println!("Pressure: {}", touch.pressure);
}
// Toque primário (primeiro toque)
if let Some(touch) = android.get_primary_touch() {
player_x = touch.x;
player_y = touch.y;
}
// Contar toques ativos
let count = android.get_touch_count();
```
### 🕹️ Joystick Virtual
```rust
// Configurar joystick
android.enable_virtual_joystick(
100.0, // X (posição na tela)
500.0, // Y (posição na tela)
80.0 // Raio
);
// Configurar zona morta
android.set_joystick_deadzone(0.1);
// Obter eixos (-1.0 a 1.0)
let (jx, jy) = android.get_joystick_axis();
player_x += jx * speed * dt;
player_y += jy * speed * dt;
// Verificar se está ativo
if android.is_joystick_active() {
// Joystick sendo usado
}
// Desenhar joystick
android.draw_virtual_joystick(pixels, screen_width);
```
### 📡 Sensores (Acelerômetro/Giroscópio)
```rust
// Habilitar sensores
android.enable_sensors();
// Acelerômetro (inclinação do dispositivo)
let (ax, ay, az) = android.get_accelerometer();
// ax, ay, az: -10.0 a 10.0 (m/s²)
// Giroscópio (rotação)
let (gx, gy, gz) = android.get_gyroscope();
// gx, gy, gz: radianos por segundo
// Exemplo: Controle por inclinação
player_x += ax * sensitivity * dt;
player_y += ay * sensitivity * dt;
```
### 📳 Vibração
```rust
// Vibração simples (duração em ms)
android.vibrate(100);
// Intensidades pré-definidas
android.vibrate_light(); // Leve (~50ms)
android.vibrate_medium(); // Média (~100ms)
android.vibrate_strong(); // Forte (~200ms)
// Padrão customizado
use sevenx_engine::VibrationPattern;
let pattern = VibrationPattern::new()
.vibrate(100) // Vibra 100ms
.pause(50) // Pausa 50ms
.vibrate(200) // Vibra 200ms
.repeat(2); // Repete 2 vezes
android.vibrate_pattern(pattern);
// Cancelar vibração
android.cancel_vibration();
```
### 🎯 Sistema de Gestos
```rust
use sevenx_engine::GestureType;
// Obter último gesto detectado
if let Some(gesture) = android.get_last_gesture() {
match gesture {
GestureType::Tap(x, y) => {
println!("Tap em ({}, {})", x, y);
}
GestureType::DoubleTap(x, y) => {
println!("Double tap em ({}, {})", x, y);
}
GestureType::LongPress(x, y) => {
println!("Long press em ({}, {})", x, y);
}
GestureType::Swipe(direction) => {
// direction: SwipeDirection::Up/Down/Left/Right
println!("Swipe: {:?}", direction);
}
GestureType::Pinch(scale) => {
// scale: fator de zoom (< 1.0 = zoom out, > 1.0 = zoom in)
camera_zoom *= scale;
}
GestureType::Rotate(angle) => {
// angle: rotação em radianos
object_rotation += angle;
}
}
}
```
### 🔋 Gerenciamento de Bateria
```rust
// Nível de bateria (0-100)
let level = android.get_battery_level();
println!("Bateria: {}%", level);
// Status de carregamento
if android.is_charging() {
println!("Dispositivo carregando");
}
// Temperatura (°C)
let temp = android.get_battery_temperature();
if temp > 40.0 {
println!("Dispositivo quente!");
}
// Otimizar baseado na bateria
if level < 20 {
// Reduzir qualidade gráfica
android.set_target_fps(30);
}
```
### ⚡ Performance Adaptativa
```rust
// Configurar FPS alvo
android.set_target_fps(60); // 30, 60, 120
// Habilitar thermal throttling
android.enable_thermal_management();
// Verificar superaquecimento
if android.is_overheating() {
// Reduzir qualidade
android.set_target_fps(30);
}
// Estatísticas de performance
let stats = android.get_performance_stats();
println!("FPS atual: {:.1}", stats.current_fps);
println!("Frame time: {:.2}ms", stats.frame_time_ms);
println!("Estável: {}", stats.is_stable);
```
### 📐 Orientação de Tela
```rust
use sevenx_engine::ScreenOrientation;
// Obter orientação atual
match android.get_orientation() {
ScreenOrientation::Portrait => println!("Retrato"),
ScreenOrientation::Landscape => println!("Paisagem"),
ScreenOrientation::PortraitReverse => println!("Retrato invertido"),
ScreenOrientation::LandscapeReverse => println!("Paisagem invertida"),
}
// Bloquear orientação
android.lock_orientation(ScreenOrientation::Landscape);
// Desbloquear
android.unlock_orientation();
```
### 🔔 Notificações Locais
```rust
// Notificação simples
let id = android.show_notification(
"Título",
"Mensagem da notificação",
"icon_name"
);
// Notificação agendada (delay em segundos)
let id = android.schedule_notification(
"Lembrete",
"Volte a jogar!",
"icon",
3600 // 1 hora
);
// Cancelar notificação específica
android.cancel_notification(id);
// Cancelar todas
android.cancel_all_notifications();
```
### 🌐 Conectividade
```rust
use sevenx_engine::ConnectionType;
// Tipo de conexão
match android.get_connection_type() {
ConnectionType::WiFi => println!("WiFi"),
ConnectionType::Mobile => println!("Dados móveis"),
ConnectionType::Ethernet => println!("Ethernet"),
ConnectionType::None => println!("Sem conexão"),
}
// Verificar se está online
if android.is_online() {
// Fazer operações de rede
}
// Velocidade da conexão (estimada)
let speed = android.get_connection_speed(); // Mbps
```
### 💾 Armazenamento Persistente
```rust
// Salvar dados
let data = serde_json::to_string(&game_state)?;
android.save_data("save.json", &data)?;
// Carregar dados
if let Ok(data) = android.load_data("save.json") {
let game_state: GameState = serde_json::from_str(&data)?;
}
// Verificar se arquivo existe
if android.file_exists("save.json") {
println!("Save encontrado!");
}
// Deletar arquivo
android.delete_file("save.json")?;
// Listar arquivos
let files = android.list_files()?;
for file in files {
println!("Arquivo: {}", file);
}
// Obter tamanho do arquivo
let size = android.get_file_size("save.json")?;
println!("Tamanho: {} bytes", size);
```
### 🔐 Permissões Android
```rust
use sevenx_engine::AndroidPermission;
// Verificar permissão
if android.has_permission(AndroidPermission::Camera) {
// Usar câmera
}
// Solicitar permissão
android.request_permission(
AndroidPermission::WriteExternalStorage,
|granted| {
if granted {
println!("Permissão concedida!");
}
}
);
// Permissões disponíveis:
// - Camera
// - Microphone
// - Location
// - WriteExternalStorage
// - ReadExternalStorage
// - Internet
// - Vibrate
```
### ⌨️ Teclado Virtual
```rust
// Mostrar teclado
android.show_keyboard();
// Ocultar teclado
android.hide_keyboard();
// Verificar se está visível
if android.is_keyboard_visible() {
// Ajustar UI
}
```
### 📤 Sistema de Compartilhamento
```rust
// Compartilhar texto
android.share_text("Confira meu score: 1000!");
// Compartilhar imagem
android.share_image("screenshot.png");
// Compartilhar arquivo
android.share_file("replay.dat", "application/octet-stream");
```
### 📊 Exemplo Completo Android
```rust
use sevenx_engine::*;
struct MeuJogoMobile {
android: AndroidManager,
player_x: f32,
player_y: f32,
score: u32,
}
impl GameState for MeuJogoMobile {
fn new() -> Self {
let mut android = AndroidManager::new();
// Configurar features
android.enable_touch();
android.enable_virtual_joystick(100.0, 500.0, 80.0);
android.enable_sensors();
android.enable_vibration();
android.enable_thermal_management();
android.set_target_fps(60);
Self {
android,
player_x: 400.0,
player_y: 300.0,
score: 0,
}
}
fn update(&mut self, dt: f32, _input: &InputHandler, _world: &mut World) {
// Atualizar Android Manager
self.android.update();
// Joystick virtual
let (jx, jy) = self.android.get_joystick_axis();
self.player_x += jx * 200.0 * dt;
self.player_y += jy * 200.0 * dt;
// Ou acelerômetro
let (ax, ay, _) = self.android.get_accelerometer();
self.player_x += ax * 50.0 * dt;
self.player_y += ay * 50.0 * dt;
// Gestos
if let Some(gesture) = self.android.get_last_gesture() {
match gesture {
GestureType::Tap(x, y) => {
self.score += 10;
self.android.vibrate_light();
}
GestureType::Swipe(dir) => {
println!("Swipe: {:?}", dir);
self.android.vibrate_medium();
}
_ => {}
}
}
// Gerenciamento de bateria
if self.android.get_battery_level() < 20 {
self.android.set_target_fps(30);
}
// Thermal throttling
if self.android.is_overheating() {
self.android.set_target_fps(30);
}
}
fn draw(&mut self, _world: &World, pixels: &mut [u8]) {
// Limpar tela
for pixel in pixels.chunks_exact_mut(4) {
pixel.copy_from_slice(&[20, 20, 30, 255]);
}
// Desenhar jogador
ui::render_rect(
self.player_x as i32,
self.player_y as i32,
32, 32,
[0, 255, 0, 255],
pixels,
800
);
// Desenhar joystick
self.android.draw_virtual_joystick(pixels, 800);
// HUD
let score_text = format!("SCORE: {}", self.score);
ui::render_text(&score_text, 10, 10, [255, 255, 255, 255], pixels, 800);
// Bateria
let battery = self.android.get_battery_level();
let battery_text = format!("BAT: {}%", battery);
ui::render_text(&battery_text, 10, 30, [255, 255, 0, 255], pixels, 800);
// FPS
let stats = self.android.get_performance_stats();
let fps_text = format!("FPS: {:.0}", stats.current_fps);
ui::render_text(&fps_text, 10, 50, [0, 255, 255, 255], pixels, 800);
}
}
fn main() {
let config = EngineConfig::new()
.with_title("Meu Jogo Mobile")
.with_size(800, 600);
Engine::with_config(config).run::<MeuJogoMobile>();
}
```
---
## 🔧 Compilação Android
### Setup Inicial
```bash
# Instalar cargo-ndk
cargo install cargo-ndk
# Adicionar targets
rustup target add aarch64-linux-android
rustup target add armv7-linux-androideabi
rustup target add x86_64-linux-android
# Instalar Android NDK (via Android Studio ou sdkmanager)
```
### Compilar para Android
```bash
# ARM64 (recomendado - dispositivos modernos)
cargo ndk -t arm64-v8a build --release --example android_complete
# ARMv7 (dispositivos antigos)
cargo ndk -t armeabi-v7a build --release --example android_complete
# x86_64 (emulador)
cargo ndk -t x86_64 build --release --example android_complete
# Todos os targets
cargo ndk -t arm64-v8a -t armeabi-v7a build --release --example android_complete
```
### Instalar no Dispositivo
```bash
# Habilitar USB Debugging no dispositivo
# Conectar via USB
# Instalar APK
adb install target/aarch64-linux-android/release/examples/android_complete.apk
# Ver logs
### Configuração Cargo.toml
```toml
[package.metadata.android]
package = "com.sevenx.meujogo"
build_targets = ["aarch64-linux-android", "armv7-linux-androideabi"]
assets = "assets"
[package.metadata.android.sdk]
min_sdk_version = 24
target_sdk_version = 33
compile_sdk_version = 33
[[package.metadata.android.uses_permission]]
name = "android.permission.INTERNET"
[[package.metadata.android.uses_permission]]
name = "android.permission.VIBRATE"
[[package.metadata.android.uses_permission]]
name = "android.permission.WAKE_LOCK"
[[package.metadata.android.uses_feature]]
name = "android.hardware.touchscreen"
required = true
[[package.metadata.android.uses_feature]]
name = "android.hardware.sensor.accelerometer"
required = false
[[package.metadata.android.uses_feature]]
name = "android.hardware.sensor.gyroscope"
required = false
```
---
## 📚 Documentação Adicional
- **ANDROID_FEATURES_0.2.9.md** - Guia completo de features Android
- **PLATFORM_SUPPORT.md** - Suporte multiplataforma
- **RELEASE_NOTES_0.2.9.md** - Notas de lançamento
- **FAQ.md** - Perguntas frequentes
---
**SevenX Engine v0.2.9 - Agora com suporte Android completo! 🤖📱**