# Exporting Games with AeThex

This guide covers exporting your AeThex game to all supported platforms: Windows, Linux, macOS, Web (HTML5), and Android.

> [!TIP]
> Start with web exports for quick testing and distribution. Windows and Linux exports are easiest for desktop games.

---

## Overview

AeThex supports exporting to:
- **Desktop:** Windows, Linux, macOS
- **Web:** HTML5 (WebAssembly + WebGL)
- **Mobile:** Android (iOS planned)

Each platform has specific requirements and optimization considerations.

```mermaid
graph TD
    Game[🎮 Your Game] --> Export{Export Target}
    
    Export -->|Desktop| Windows[🖥️ Windows]
    Export -->|Desktop| Linux[🐧 Linux]
    Export -->|Desktop| Mac[🍎 macOS]
    Export -->|Web| HTML5[🌐 HTML5]
    Export -->|Mobile| Android[📱 Android]
    
    Windows --> Steam[Steam]
    Windows --> Itch[itch.io]
    Linux --> Steam
    Linux --> Itch
    Mac --> AppStore[App Store]
    HTML5 --> Web[Web Hosting]
    Android --> PlayStore[Google Play]
    
    style Game fill:#00ffff22,stroke:#00ffff
    style Windows fill:#ff00ff22,stroke:#ff00ff
    style Linux fill:#00ffff22,stroke:#00ffff
    style Mac fill:#ff00ff22,stroke:#ff00ff
    style HTML5 fill:#00ffff22,stroke:#00ffff
    style Android fill:#ff00ff22,stroke:#ff00ff
```

> [!NOTE]
> Each platform requires specific export templates. Download them from the editor or the AeThex website.

---

## Before Exporting

> [!WARNING]
> Always test your game in release mode before exporting. Some bugs only appear in release builds due to optimizations and different code paths.

### 1. Test Your Game

Always test thoroughly before exporting:
```bash
# Run in editor
aethex --editor --path ./my-project

# Test in release mode
aethex --path ./my-project
```

### 2. Configure Project Settings

**Project → Project Settings → Application:**
```
Name: Your Game Name
Description: Game description
Icon: res://icon.png
Version: 1.0.0
```

**Display Settings:**
```
Window Width: 1920
Window Height: 1080
Fullscreen: false
Resizable: true
```

### 3. Export Templates

Download export templates for your target platform:
```bash
# Via Studio IDE: Editor → Export Templates → Download

# Or manually:
wget https://aethex.io/downloads/export-templates-[version].zip
unzip export-templates-[version].zip -d ~/.local/share/aethex/templates/
```

---

## Windows Export

### Requirements

- **Build Machine:** Windows, Linux, or macOS
- **Target:** Windows 7+ (64-bit)
- **Export Template:** Windows Desktop template

### Export Steps

**1. Add Export Preset:**
```
Project → Export
Click "Add..." → Windows Desktop
```

**2. Configure Options:**
```
Export Path: builds/windows/YourGame.exe
Architecture: x86_64
Runnable: ✓ (for executable)
Embed PCK: ✓ (single file)

Code Signing:
- Identity: (optional) Your signing certificate
- Password: Your certificate password
```

**3. Export:**
```
Click "Export PCK/ZIP" for package only
Click "Export Project" for executable
```

### Windows-Specific Options

**Application:**
```
Company Name: Your Company
Product Name: Your Game
File Version: 1.0.0.0
Product Version: 1.0.0.0
File Description: Your game description
Copyright: © 2024 Your Company
Trademarks: Your trademarks
```

**Executable:**
```
Console Wrapper: ✗ (disable for release)
Icon: res://icon.ico (Windows icon format)
```

**Code Signing:**
```gdscript
# Sign your executable (optional but recommended)
signtool sign /f certificate.pfx /p password YourGame.exe
```

### Windows Distribution

**Standalone:**
- Single `.exe` file
- Portable, no installation required
- Share via download link or USB

**Installer (Optional):**
```bash
# Use NSIS, Inno Setup, or WiX
# Example with NSIS:
makensis installer.nsi
```

**Steam:**
```bash
# Use Steamworks SDK
# Follow Steam's integration guide
# Configure depot builds
```

---

## Linux Export

### Requirements

- **Target:** Ubuntu 20.04+, most modern distros
- **Architecture:** x86_64, ARM64
- **Export Template:** Linux/X11 template

### Export Steps

**1. Add Export Preset:**
```
Project → Export
Click "Add..." → Linux/X11
```

**2. Configure Options:**
```
Export Path: builds/linux/YourGame.x86_64
Architecture: x86_64 (or arm64)
Runnable: ✓
Embed PCK: ✓
```

**3. Export:**
```
Click "Export Project"
```

### Linux-Specific Options

**Binary:**
```
Strip Debug Symbols: ✓ (reduces size)
Make Executable: ✓
```

**Dependencies:**
```bash
# Your game requires these libraries on user's system:
# - libGL.so.1
# - libX11.so.6
# - libXcursor.so.1
# - libXrandr.so.2
# - libXi.so.6

# Most modern distros include these
```

### Linux Distribution

**AppImage (Recommended):**
```bash
# Create portable AppImage
wget https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage
chmod +x appimagetool-x86_64.AppImage

# Structure:
# YourGame.AppDir/
#   ├── AppRun (symlink to your binary)
#   ├── YourGame.x86_64
#   ├── YourGame.desktop
#   └── icon.png

./appimagetool-x86_64.AppImage YourGame.AppDir
```

**Flatpak:**
```bash
# Create Flatpak manifest
# Follow Flathub guidelines
flatpak-builder build-dir com.yourcompany.yourgame.yml
```

**Snap:**
```bash
# Create snapcraft.yaml
snapcraft
```

**.tar.gz Archive:**
```bash
# Simple distribution
tar -czf YourGame-linux.tar.gz YourGame.x86_64
```

---

## macOS Export

### Requirements

- **Build Machine:** macOS (for signing/notarization)
- **Target:** macOS 10.13+
- **Export Template:** macOS template
- **Apple Developer Account:** For signing (required for distribution)

### Export Steps

**1. Add Export Preset:**
```
Project → Export
Click "Add..." → macOS
```

**2. Configure Options:**
```
Export Path: builds/macos/YourGame.zip
Architecture: universal (Intel + Apple Silicon)
or separate: x86_64, arm64
```

**3. Code Signing:**
```
Codesign:
  Identity: "Developer ID Application: Your Name (TEAM_ID)"
  Certificate Path: /path/to/certificate.p12
  Certificate Password: your_password
  
Entitlements: res://entitlements.plist (optional)
```

**4. Export:**
```
Click "Export Project"
```

### macOS-Specific Options

**Application Bundle:**
```
Bundle ID: com.yourcompany.yourgame
Display Name: Your Game
Version: 1.0.0
Copyright: © 2024 Your Company
Icon: res://icon.icns (macOS icon format)
```

**Hardened Runtime:**
```
Enable Hardened Runtime: ✓
Disable Library Validation: ✗
Allow JIT Code: ✗ (unless needed)
Allow Unsigned Executable Memory: ✗
Allow DYLD Environment Variables: ✗
Disable Executable Memory Protection: ✗
```

### Notarization (Required for macOS 10.15+)

```bash
# Sign the app
codesign --deep --force --verify --verbose \
  --sign "Developer ID Application: Your Name (TEAM_ID)" \
  --options runtime \
  YourGame.app

# Create ZIP for notarization
ditto -c -k --keepParent YourGame.app YourGame.zip

# Submit for notarization
xcrun notarytool submit YourGame.zip \
  --apple-id your@email.com \
  --team-id TEAM_ID \
  --password app-specific-password \
  --wait

# Staple notarization ticket
xcrun stapler staple YourGame.app

# Verify
spctl -a -vv YourGame.app
```

### macOS Distribution

**Direct Download:**
- Distribute `.dmg` or `.zip`
- Users drag to Applications folder

**Mac App Store:**
- Use App Store Connect
- Follow Apple's submission guidelines
- Use "Mac App Store" export preset

**Create DMG:**
```bash
# Create disk image
hdiutil create -volname "Your Game" -srcfolder YourGame.app -ov -format UDZO YourGame.dmg
```

---

## Web (HTML5) Export

### Requirements

- **Target:** Modern browsers (Chrome, Firefox, Safari, Edge)
- **Export Template:** Web template
- **Web Server:** For hosting

### Export Steps

**1. Add Export Preset:**
```
Project → Export
Click "Add..." → Web (HTML5)
```

**2. Configure Options:**
```
Export Path: builds/web/index.html
Head Include: res://web/head.html (custom HTML)
```

**3. Export:**
```
Click "Export Project"
```

### Web-Specific Options

**Performance:**
```
WebGL Version: 2.0 (WebGL 2)
Enable Run: ✓ (for testing)
Full Window Size: ✓

Memory Settings:
  Initial Memory: 33554432 (32MB)
  Max Memory: 2147483648 (2GB)
  Stack Size: 5242880 (5MB)
```

**Progressive Web App:**
```
PWA: ✓
Icon 144x144: res://icons/icon-144.png
Icon 180x180: res://icons/icon-180.png
Icon 512x512: res://icons/icon-512.png
Background Color: #000000
Orientation: landscape
```

**Compression:**
```
Export Type: Regular
Gzip Compression: ✓
```

### Testing Locally

```bash
# Serve with Python
cd builds/web
python3 -m http.server 8000

# Or with Node
npx http-server builds/web -p 8000
```

Open `http://localhost:8000`

### Web Deployment

**Static Hosting (Recommended):**
```bash
# Netlify
netlify deploy --dir=builds/web --prod

# Vercel
vercel --prod builds/web

# GitHub Pages
git subtree push --prefix builds/web origin gh-pages

# Firebase Hosting
firebase deploy --only hosting
```

**itch.io:**
```
1. Zip the web folder
2. Upload to itch.io
3. Set "This file will be played in the browser"
```

**Your Own Server:**
```nginx
# Nginx configuration
server {
    listen 80;
    server_name yourgame.com;
    root /var/www/yourgame;
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # Enable CORS if needed
    location ~* \.(wasm|pck)$ {
        add_header Access-Control-Allow-Origin *;
    }
    
    # Gzip compression
    gzip on;
    gzip_types application/wasm application/octet-stream;
}
```

### Web Best Practices

**Loading Screen:**
```html
<!-- builds/web/index.html -->
<style>
.loading {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-family: sans-serif;
}
</style>
<div class="loading">Loading Your Game...</div>
```

**Optimize Size:**
```gdscript
# Disable unused features in export preset
# Compress textures
# Use streaming for audio
# Lazy load assets
```

---

## Android Export

### Requirements

- **Android SDK:** Android 6.0+ (API 23+)
- **Android NDK:** r23b+
- **JDK:** OpenJDK 11+
- **Export Template:** Android template
- **Keystore:** For signing (release builds)

### Setup Android Development

**1. Install Android SDK:**
```bash
# Download Android Studio or command-line tools
# Set ANDROID_HOME environment variable
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
```

**2. Install Required Components:**
```bash
sdkmanager "platform-tools" "platforms;android-33" "build-tools;33.0.0" "ndk;23.2.8568313"
```

**3. Configure AeThex:**
```
Editor → Editor Settings → Export → Android:
  Android SDK Path: /path/to/Android/Sdk
  Debug Keystore: ~/.android/debug.keystore
```

### Export Steps

**1. Add Export Preset:**
```
Project → Export
Click "Add..." → Android
```

**2. Configure Options:**
```
Export Path: builds/android/YourGame.apk (or .aab)

Package:
  Unique Name: com.yourcompany.yourgame
  Name: Your Game
  Signed: ✓ (for release)
  
Version:
  Code: 1 (increment for each release)
  Name: 1.0.0
```

**3. Code Signing:**
```
Keystore:
  Debug: ~/.android/debug.keystore
  Release: /path/to/release.keystore
  User: your_key_alias
  Password: your_keystore_password
```

**4. Export:**
```
Click "Export Project"
```

### Android-Specific Options

**Graphics:**
```
OpenGL ES: 3.0
ASTC Compression: ✓ (for textures)
```

**Permissions:**
```
Internet: ✓ (for cloud features)
Access Network State: ✓
Access WiFi State: ✓
Vibrate: ✓ (optional)
```

**Screen:**
```
Orientation: landscape (or portrait)
Support Small Screen: ✗
Support Normal Screen: ✓
Support Large Screen: ✓
Support XLarge Screen: ✓
```

**Architecture:**
```
Export ABIs:
  ✓ armeabi-v7a (32-bit ARM)
  ✓ arm64-v8a (64-bit ARM) - Required by Play Store
  ✗ x86 (optional for emulators)
  ✗ x86_64 (optional for emulators)
```

### Creating Debug Build

```bash
# Export unsigned debug APK
# Install via ADB
adb install builds/android/YourGame-debug.apk

# Run and view logs
adb logcat | grep YourGame
```

### Creating Release Build

**1. Create Release Keystore:**
```bash
keytool -genkey -v -keystore release.keystore -alias my_game_key \
  -keyalg RSA -keysize 2048 -validity 10000

# Keep this keystore safe! You need it for all future updates
```

**2. Export Release Build:**
```
Select "Android" preset
Enable "Signed"
Provide keystore details
Click "Export Project"
```

**3. Generate AAB (for Play Store):**
```
Export Path: builds/android/YourGame.aab
Export Type: AAB (Android App Bundle)
```

### Testing on Device

```bash
# Enable USB debugging on Android device
# Connect via USB

# List devices
adb devices

# Install
adb install YourGame.apk

# Uninstall
adb uninstall com.yourcompany.yourgame

# View logs
adb logcat -c  # Clear logs
adb logcat | grep YourGame
```

### Android Distribution

**Google Play Store:**
```
1. Create Play Console account
2. Create app listing
3. Upload AAB (not APK)
4. Configure store presence
5. Set pricing
6. Submit for review
```

**Other Stores:**
- Amazon Appstore (APK)
- Samsung Galaxy Store (APK)
- itch.io (APK)
- Direct download (APK)

### Android Optimization

**Reduce APK Size:**
```
# In export preset:
- Enable compression
- Disable unused ABIs
- Compress textures (ASTC)
- Remove unused resources
- Use ProGuard/R8
```

**Performance:**
```gdscript
# Target 60 FPS on mid-range devices
# Test on:
# - Low-end device (2GB RAM)
# - Mid-range device (4GB RAM)
# - High-end device (8GB+ RAM)

# Android-specific optimizations:
func _ready():
    if OS.get_name() == "Android":
        # Reduce particle count
        # Lower shadow quality
        # Disable post-processing effects
        pass
```

---

## Multi-Platform Tips

### Asset Optimization

**Textures:**
```
Desktop: PNG, JPEG, or uncompressed
Web: Compress, reduce resolution
Mobile: ASTC compression, aggressive optimization
```

**Audio:**
```
Music: OGG Vorbis, 128kbps
SFX: OGG Vorbis, 64kbps
Mobile: Lower bitrates
```

**3D Models:**
```
Desktop: Full detail
Web: Reduce poly count 30%
Mobile: Reduce poly count 50%
```

### Platform Detection

```gdscript
extends Node

func _ready():
    match OS.get_name():
        "Windows":
            setup_windows()
        "Linux", "FreeBSD", "NetBSD", "OpenBSD", "BSD":
            setup_linux()
        "macOS":
            setup_macos()
        "Web":
            setup_web()
        "Android":
            setup_android()
        "iOS":
            setup_ios()

func setup_windows():
    # Windows-specific setup
    DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_ENABLED)

func setup_mobile():
    # Touch controls, battery optimization
    if OS.get_name() in ["Android", "iOS"]:
        # Mobile optimizations
        pass
```

### Feature Flags

```gdscript
const FEATURES = {
    "cloud_saves": true,
    "multiplayer": true,
    "analytics": true,
    "haptics": OS.get_name() in ["Android", "iOS"],
    "keyboard": OS.get_name() not in ["Android", "iOS", "Web"],
}

func _ready():
    if FEATURES.cloud_saves:
        await AeThexCloud.connect_to_cloud()
```

---

## Troubleshooting

### Common Issues

**Export template missing:**
```
Solution: Download export templates from
Editor → Export Templates → Download
```

**Code signing failed (macOS):**
```bash
# Verify certificate
security find-identity -v -p codesigning

# Check entitlements
codesign -d --entitlements :- YourGame.app
```

**Web build doesn't load:**
```
Check console for errors
Must be served from HTTP server (not file://)
Check SharedArrayBuffer requirements
Enable CORS headers if needed
```

**Android build fails:**
```bash
# Check SDK paths
echo $ANDROID_HOME

# Update build tools
sdkmanager --update

# Clean build
./gradlew clean
```

### Performance Testing

```gdscript
# Add FPS counter
func _process(delta):
    if OS.is_debug_build():
        $FPSLabel.text = "FPS: " + str(Engine.get_frames_per_second())
```

### Build Size Optimization

```
1. Disable unused modules in export preset
2. Compress textures appropriately
3. Use streaming for large assets
4. Remove debug symbols (release mode)
5. Use platform-specific compression
```

---

## Best Practices

### Before Every Release

✓ Test on all target platforms  
✓ Profile performance  
✓ Check memory usage  
✓ Test on low-end hardware  
✓ Verify all assets load correctly  
✓ Test input methods (keyboard, gamepad, touch)  
✓ Check for crash logs  

### Versioning

```
Use semantic versioning: MAJOR.MINOR.PATCH
Example: 1.2.3

MAJOR: Breaking changes
MINOR: New features (backward compatible)
PATCH: Bug fixes

Android version code: Increment for each release
```

### Continuous Integration

```yaml
# GitHub Actions example
name: Export Game
on: [push]

jobs:
  export:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Export for Windows
        run: |
          # Export commands here
      - name: Upload artifacts
        uses: actions/upload-artifact@v2
        with:
          name: game-builds
          path: builds/
```

---

## Platform Comparison

| Feature | Windows | Linux | macOS | Web | Android |
|---------|---------|-------|-------|-----|---------|
| **Ease of Export** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| **Distribution** | Easy | Easy | Medium | Easiest | Medium |
| **Performance** | Excellent | Excellent | Excellent | Good | Good |
| **File Size** | Medium | Medium | Large | Large | Medium |
| **Monetization** | Direct | Direct | App Store | Ads/IAP | Play Store |
| **Updates** | Manual | Manual | Manual | Instant | Store |

---

## Next Steps

- **Test Your Exports:** Always test on real hardware
- **Get Feedback:** Share with beta testers
- **Optimize:** Profile and improve performance
- **Distribute:** Choose your distribution method
- **Monitor:** Use AeThexAnalytics to track usage

For platform-specific questions, see:
- [API Reference](API_REFERENCE.md) - Cloud features
- [GAME_DEVELOPMENT.md](GAME_DEVELOPMENT.md) - Core engine features
- [ARCHITECTURE_OVERVIEW.md](ARCHITECTURE_OVERVIEW.md) - Technical details

Happy shipping! 🚀
