sevenx_engine 0.2.11

Engine de jogos 2D/3D completa com suporte Android, física, áudio, partículas, tilemap, UI, eventos e sistema 3D avançado com PBR.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# 📖 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

adb logcat | grep RustStdoutStderr
```

### 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! 🤖📱**