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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# 🤖 SevenX Engine - Guia Completo Android


## 📱 Visão Geral


A SevenX Engine oferece suporte completo para Android com recursos nativos:

- **Touch Multi-touch** - Suporte completo para múltiplos toques
-**Gestos Avançados** - Tap, Double Tap, Long Press, Swipe, Pinch, Rotate
-**Sensores** - Acelerômetro e Giroscópio
-**Vibração** - Feedback háptico com intensidade variável
-**Joystick Virtual** - Controles touch customizáveis
-**Bateria** - Monitoramento e otimização automática
-**Orientação** - Suporte para Portrait e Landscape
-**Notificações** - Sistema de notificações locais
-**Conectividade** - Detecção de WiFi/Mobile
-**Armazenamento** - Persistência de dados
-**Permissões** - Gerenciamento de permissões Android
-**Teclado Virtual** - Controle do teclado on-screen

## 🚀 Quick Start


### 1. Configuração do Ambiente


```powershell
# Execute o script de configuração

.\build-android-complete.ps1
```

O script irá:
- Instalar `cargo-apk` se necessário
- Adicionar targets Android (ARM64 e ARMv7)
- Verificar configuração do NDK
- Buildar seus exemplos

### 2. Primeiro Exemplo Android


```rust
use sevenx_engine::{Engine, EngineConfig, GameState};

#[cfg(target_os = "android")]

use sevenx_engine::android::AdvancedAndroidManager;

struct MyAndroidGame {
    #[cfg(target_os = "android")]
    android: AdvancedAndroidManager,
}

impl GameState for MyAndroidGame {
    fn new() -> Self {
        #[cfg(target_os = "android")]
        {
            let mut android = AdvancedAndroidManager::new();
            
            // Cria joystick virtual
            android.input.create_virtual_joystick(100.0, 450.0, 50.0);
            
            Self { android }
        }
        
        #[cfg(not(target_os = "android"))]
        {
            Self {}
        }
    }

    fn update(&mut self, dt: f32, _input: &InputHandler, _world: &mut World) {
        #[cfg(target_os = "android")]
        {
            self.android.update();
            
            // Processa toques
            let touches = self.android.input.get_touches();
            for touch in touches {
                println!("Touch: {}, {} (pressure: {})", 
                    touch.x, touch.y, touch.pressure);
            }
        }
    }

    fn draw(&mut self, _world: &World, pixels: &mut [u8]) {
        // Seu código de renderização
    }
}

fn main() {
    let config = EngineConfig::new()
        .with_title("My Android Game")
        .with_size(800, 600);
    
    Engine::with_config(config).run::<MyAndroidGame>();
}
```

### 3. Build e Instalação


```powershell
# Build para ARM64 (recomendado)

cargo apk build --example my_game --target aarch64-linux-android --release

# Instalar no dispositivo

adb install target\aarch64-linux-android\release\examples\my_game.apk

# Ou build + run direto

cargo apk run --example my_game --target aarch64-linux-android
```

## 📚 Recursos Detalhados


### Touch e Multi-touch


```rust
// Obter todos os toques ativos
let touches = android.input.get_touches();

// Verificar toque em área específica
if android.input.is_touch_in_area(100.0, 100.0, 200.0, 50.0) {
    println!("Botão tocado!");
}

// Número de toques
let count = android.input.touch_count();
```

### Gestos Avançados


```rust
// Atualizar reconhecedor de gestos
android.gestures.update(&touches);

// Processar gestos detectados
for gesture in android.gestures.get_gestures() {
    match gesture.gesture_type {
        GestureType::Tap => {
            println!("Tap em: {}, {}", gesture.position.0, gesture.position.1);
        }
        GestureType::DoubleTap => {
            println!("Double tap!");
        }
        GestureType::LongPress => {
            println!("Long press!");
        }
        GestureType::Swipe(direction) => {
            match direction {
                SwipeDirection::Up => println!("Swipe para cima"),
                SwipeDirection::Down => println!("Swipe para baixo"),
                SwipeDirection::Left => println!("Swipe para esquerda"),
                SwipeDirection::Right => println!("Swipe para direita"),
            }
        }
        GestureType::Pinch(pinch_type) => {
            println!("Pinch: {:?}, scale: {}", pinch_type, gesture.scale);
        }
        GestureType::Rotate => {
            println!("Rotação: {} radianos", gesture.angle);
        }
    }
}

// Verificar gesto específico
if android.gestures.has_gesture(GestureType::Tap) {
    println!("Tap detectado!");
}
```

### Joystick Virtual


```rust
// Criar joystick
android.input.create_virtual_joystick(100.0, 450.0, 50.0);

// Obter eixos (-1.0 a 1.0)
let (axis_x, axis_y) = android.input.get_virtual_joystick_axis();

// Mover personagem
player.x += axis_x * speed * dt;
player.y += axis_y * speed * dt;
```

### Sensores


```rust
// Acelerômetro (m/s²)
let accel = android.input.get_accelerometer();
println!("Aceleração: {}, {}, {}", accel.x, accel.y, accel.z);

// Detectar sacudida
if accel.x.abs() > 15.0 || accel.y.abs() > 15.0 {
    println!("Dispositivo sacudido!");
}

// Giroscópio (rad/s)
let gyro = android.input.get_gyroscope();
println!("Rotação: {}, {}, {}", gyro.x, gyro.y, gyro.z);

// Controle por inclinação
player.x += accel.x * sensitivity * dt;
```

### Vibração


```rust
// Vibração simples (milissegundos)
android.vibration.vibrate(100);

// Vibração com intensidade
use sevenx_engine::android::VibrationIntensity;

android.vibration.vibrate_with_intensity(50, VibrationIntensity::Light);
android.vibration.vibrate_with_intensity(100, VibrationIntensity::Medium);
android.vibration.vibrate_with_intensity(200, VibrationIntensity::Heavy);

// Padrão customizado
use sevenx_engine::android::VibrationPattern;

let pattern = VibrationPattern {
    durations: vec![0, 100, 50, 100], // espera, vibra, espera, vibra
    repeat: false,
};
android.vibration.vibrate_pattern(pattern);

// Cancelar vibração
android.vibration.cancel();

// Habilitar/desabilitar
android.vibration.set_enabled(false);
```

### Bateria e Performance


```rust
// Informações da bateria
if let Some(battery) = android.input.get_battery() {
    println!("Nível: {:.0}%", battery.level * 100.0);
    println!("Carregando: {}", battery.is_charging);
    println!("Temperatura: {:.1}°C", battery.temperature);
}

// Performance automática
android.performance.set_target_fps(60);

// Modo economia de bateria
if battery.level < 0.2 {
    android.performance.enable_power_save(); // FPS -> 30
}

// Thermal throttling automático
// Se temperatura > 45°C, reduz FPS automaticamente
```

### Orientação


```rust
use sevenx_engine::android::ScreenOrientation;

// Obter orientação atual
let orientation = android.orientation.get_orientation();

// Verificar tipo
if android.orientation.is_landscape() {
    println!("Modo paisagem");
}

if android.orientation.is_portrait() {
    println!("Modo retrato");
}

// Travar orientação
android.orientation.lock(ScreenOrientation::Landscape);

// Destravar
android.orientation.unlock();
```

### Notificações


```rust
// Notificação simples
let id = android.notifications.show("Título", "Mensagem");

// Notificação agendada
use std::time::Duration;

android.notifications.show_delayed(
    "Lembrete",
    "Volte ao jogo!",
    Duration::from_secs(3600) // 1 hora
);

// Cancelar notificação
android.notifications.cancel(id);

// Cancelar todas
android.notifications.cancel_all();
```

### Conectividade


```rust
// Verificar conexão
if android.connectivity.is_connected() {
    println!("Conectado!");
}

// Tipo de rede
if android.connectivity.is_wifi() {
    println!("WiFi - pode baixar assets grandes");
} else if android.connectivity.is_mobile() {
    println!("Dados móveis - economizar banda");
}

// Rede medida (dados móveis limitados)
if android.connectivity.is_metered() {
    println!("Conexão medida - evitar downloads grandes");
}
```

### Armazenamento


```rust
// Salvar dados
android.storage.save("player_name", "João");
android.storage.save("high_score", "1000");

// Carregar dados
if let Some(name) = android.storage.load("player_name") {
    println!("Bem-vindo, {}!", name);
}

// Verificar existência
if android.storage.has("high_score") {
    println!("Save encontrado!");
}

// Remover
android.storage.remove("temp_data");

// Limpar tudo
android.storage.clear();
```

### Permissões


```rust
use sevenx_engine::android::Permission;

// Solicitar permissão
if android.permissions.request(Permission::Camera) {
    println!("Permissão de câmera concedida!");
}

// Verificar permissão
if android.permissions.is_granted(Permission::Storage) {
    // Pode acessar armazenamento
}

// Revogar (para testes)
android.permissions.revoke(Permission::Microphone);

// Permissões disponíveis:
// - Permission::Camera
// - Permission::Microphone
// - Permission::Location
// - Permission::Storage
// - Permission::Contacts
// - Permission::Calendar
```

### Teclado Virtual


```rust
// Mostrar teclado
android.keyboard.show();

// Esconder teclado
android.keyboard.hide();

// Verificar visibilidade
if android.keyboard.is_visible() {
    println!("Teclado aberto");
}

// Obter texto
let text = android.keyboard.get_text();

// Definir texto
android.keyboard.set_text("Novo texto".to_string());

// Limpar
android.keyboard.clear();
```

### Compartilhamento


```rust
use sevenx_engine::android::ShareManager;

// Compartilhar texto
ShareManager::share_text("Meu high score: 1000!");

// Compartilhar imagem
ShareManager::share_image("/sdcard/screenshot.png");

// Compartilhar arquivo
ShareManager::share_file("/sdcard/save.dat", "application/octet-stream");
```

## 🎮 Exemplo Completo: Jogo Mobile


```rust
use sevenx_engine::{
    Engine, EngineConfig, GameState,
    input::InputHandler,
    world::World,
    ui::render_text,
};

#[cfg(target_os = "android")]

use sevenx_engine::android::{
    AdvancedAndroidManager, GestureType, VibrationIntensity,
};

struct MobileGame {
    #[cfg(target_os = "android")]
    android: AdvancedAndroidManager,
    
    player_x: f32,
    player_y: f32,
    score: u32,
}

impl GameState for MobileGame {
    fn new() -> Self {
        #[cfg(target_os = "android")]
        {
            let mut android = AdvancedAndroidManager::new();
            
            // Setup inicial
            android.input.create_virtual_joystick(100.0, 450.0, 50.0);
            android.permissions.request(sevenx_engine::android::Permission::Storage);
            
            // Carregar high score
            let score = if let Some(saved) = android.storage.load("high_score") {
                saved.parse().unwrap_or(0)
            } else {
                0
            };
            
            Self {
                android,
                player_x: 400.0,
                player_y: 300.0,
                score,
            }
        }
        
        #[cfg(not(target_os = "android"))]
        {
            Self {
                player_x: 400.0,
                player_y: 300.0,
                score: 0,
            }
        }
    }

    fn update(&mut self, dt: f32, _input: &InputHandler, _world: &mut World) {
        #[cfg(target_os = "android")]
        {
            self.android.update();
            
            // Controle por joystick
            let (axis_x, axis_y) = self.android.input.get_virtual_joystick_axis();
            self.player_x += axis_x * 200.0 * dt;
            self.player_y += axis_y * 200.0 * dt;
            
            // Controle por acelerômetro
            let accel = self.android.input.get_accelerometer();
            self.player_x += accel.x * 10.0 * dt;
            
            // Gestos
            for gesture in self.android.gestures.get_gestures() {
                match gesture.gesture_type {
                    GestureType::Tap => {
                        self.score += 10;
                        self.android.vibration.vibrate_with_intensity(
                            30,
                            VibrationIntensity::Light
                        );
                    }
                    GestureType::DoubleTap => {
                        self.score += 50;
                        self.android.vibration.vibrate_with_intensity(
                            50,
                            VibrationIntensity::Heavy
                        );
                    }
                    _ => {}
                }
            }
            
            // Salvar high score
            self.android.storage.save("high_score", &self.score.to_string());
        }
    }

    fn draw(&mut self, _world: &World, pixels: &mut [u8]) {
        let score_text = format!("Score: {}", self.score);
        render_text(&score_text, 20, 20, [255, 255, 255, 255], pixels, 800);
        
        // Desenhar player (círculo simples)
        let px = self.player_x as i32;
        let py = self.player_y as i32;
        let radius = 20;
        
        for y in (py - radius).max(0)..(py + radius).min(600) {
            for x in (px - radius).max(0)..(px + radius).min(800) {
                let dx = x - px;
                let dy = y - py;
                if dx * dx + dy * dy <= radius * radius {
                    let idx = ((y * 800 + x) * 4) as usize;
                    if idx + 3 < pixels.len() {
                        pixels[idx] = 255;     // R
                        pixels[idx + 1] = 100; // G
                        pixels[idx + 2] = 100; // B
                        pixels[idx + 3] = 255; // A
                    }
                }
            }
        }
    }
}

fn main() {
    let config = EngineConfig::new()
        .with_title("Mobile Game")
        .with_size(800, 600);
    
    Engine::with_config(config).run::<MobileGame>();
}
```

## 📦 Configuração do Cargo.toml


```toml
[package.metadata.android]
package = "com.sevenx.mygame"
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

[lib]
crate-type = ["cdylib", "rlib"]

[[example]]
name = "my_game"
crate-type = ["cdylib"]

[target.'cfg(target_os = "android")'.dependencies]
android-activity = { version = "0.6", features = ["native-activity"] }
```

## 🔧 Troubleshooting


### Erro: NDK não encontrado


```powershell
# Instale o NDK via Android Studio ou:

# 1. Baixe de https://developer.android.com/ndk/downloads

# 2. Configure a variável:

$env:ANDROID_NDK_ROOT = "C:\Android\sdk\ndk\25.2.9519653"
```

### Erro: cargo-apk não encontrado


```powershell
cargo install cargo-apk
```

### Erro: Target não instalado


```powershell
rustup target add aarch64-linux-android
rustup target add armv7-linux-androideabi
```

### APK não instala no dispositivo


```powershell
# Verifique se o dispositivo está conectado

adb devices

# Desinstale versão antiga

adb uninstall com.sevenx.mygame

# Instale novamente

adb install -r target\aarch64-linux-android\release\examples\my_game.apk
```

### Performance ruim


```rust
// Ative modo economia
android.performance.enable_power_save();

// Reduza qualidade gráfica
android.performance.set_target_fps(30);
```

## 📱 Otimizações para Mobile


### 1. Bateria


```rust
// Ajuste automático baseado na bateria
if let Some(battery) = android.input.get_battery() {
    if battery.level < 0.2 && !battery.is_charging {
        android.performance.enable_power_save();
    }
}
```

### 2. Thermal Throttling


```rust
// Reduz FPS automaticamente se esquentar
android.performance.check_thermal_throttling(battery.temperature);
```

### 3. Conectividade


```rust
// Evite downloads grandes em dados móveis
if android.connectivity.is_mobile() && android.connectivity.is_metered() {
    println!("Adiando download de assets");
}
```

### 4. Resolução Adaptativa


```rust
let config = if android.performance.is_power_save_mode() {
    EngineConfig::new().with_size(640, 480) // Menor resolução
} else {
    EngineConfig::new().with_size(1280, 720) // Resolução normal
};
```

## 🎯 Próximos Passos


1. **Teste no dispositivo real** - Emuladores não suportam todos os sensores
2. **Otimize assets** - Use texturas comprimidas para mobile
3. **Implemente salvamento** - Use o StorageManager para persistência
4. **Adicione analytics** - Monitore performance em dispositivos reais
5. **Teste em múltiplos dispositivos** - Diferentes resoluções e capacidades

## 📚 Recursos Adicionais


- [Android NDK Guide]https://developer.android.com/ndk/guides
- [cargo-apk Documentation]https://github.com/rust-mobile/cargo-apk
- [SevenX Examples]./examples/
- [API Reference]./API_REFERENCE.md

## 🆘 Suporte


Problemas? Abra uma issue no GitHub:
https://github.com/sevenx777-dev/SevenX-Engine/issues

---

**SevenX Engine** - Build amazing mobile games with Rust! 🚀