# Getting started

One avatar in a window of your own: a context, an avatar, a renderer on your device, and two calls a frame. Every
step is shown in C, C++, C#, Rust, Python, JavaScript, Unity, Godot and Unreal: pick yours in the step's tabs. In an
engine the plugin makes the renderer and draws each frame, so its tabs say what is left to you. You need a download
([installing](install.md)) and a manifest: the avatar as base64, from 360sona.com's share box or
`GET /sona/v1/avatar/random`.

## 1. Open a context

The context holds the licence, where avatar files come from, and every avatar. A game has one.

### C

```c
sona_config cfg;
sona_ctx *ctx = NULL;
sona_config_defaults(&cfg);
cfg.licence = licence;                       /* the bytes of sona-licence.json */
cfg.licence_len = licence_len;
cfg.sources[0].kind = SONA_SOURCE_GATE;      /* stream item files from 360sona */
cfg.source_count = 1;
if (sona_open(&cfg, &ctx) != SONA_OK) {
  sona_error_info e = sona_last_error(NULL);
  fprintf(stderr, "%s\n%s\n", e.message, e.fix);
}
```

`SONA_SOURCE_DIR` with `location` set reads a folder you own in place of the gate. Every call returns a
`sona_result`; `sona_last_error` gives the message and a fix.

### C++

```cpp
sona::Config cfg;
if (!cfg.licence_file(argv[1])) { std::fprintf(stderr, "cannot read %s\n", argv[1]); return 1; }
if (const char *app = std::getenv("SONA_APP_ID")) cfg.app_id(app);   // unset: the app id your download is made for
if (dir) cfg.dir(dir); else cfg.gate();   // the gate: item files from 360sona
sona::Context ctx(cfg);
```

### C#

```csharp
var options = new SonaOptions
{
    Licence = File.ReadAllBytes(args[0]),
    AppId = Environment.GetEnvironmentVariable("SONA_APP_ID"),
};
options.Sources.Add(dir != null ? SonaSourceSpec.Dir(dir) : SonaSourceSpec.Gate());   // the gate: item files from 360sona
using var ctx = new SonaContext(options);
```

### Rust

```rust
let licence = std::fs::read(&args[0])
    .map_err(|e| format!("cannot read {}: {}", args[0], e))?;
let mut cfg = sona::Config::new().licence(licence);
if let Ok(app) = std::env::var("SONA_APP_ID") {
    cfg = cfg.app_id(&app); // unset: the app id your download is made for
}
cfg = match &dir {
    Some(d) => cfg.dir(d),
    None => cfg.gate(None),
};
let ctx = sona::Context::open(cfg).map_err(|e| e.to_string())?;
```

### Python

```python
with sona.Context(app_id=os.environ.get("SONA_APP_ID"), licence=licence,
                  sources=[source]) as ctx:
    avatar = ctx.add_base64(manifest)
```

### JavaScript

The Renderer SDK opens the context and the renderer together, on your canvas:

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
```

`create()` rejects with a `SonaError` whose `code` says what and `fix` what to do.

### Unity

Put a `SonaContext` component on one GameObject of the scene and set its `licence` to your `sona-licence.json`. It
opens the context when the scene starts; leave `useGate` on to stream avatar files from 360sona.

### Godot

Copy `addons/sona` into the project and put `sona-licence.json` at `res://sona-licence.json`. `SonaServer` opens the
context when the first avatar enters the tree.

### Unreal

Copy the `Sona360` plugin into the project's `Plugins` folder and put `sona-licence.json` at
`Content/Sona360/sona-licence.json`. The plugin's subsystem opens the context when the game starts.

## 2. Add an avatar

The avatar loads on worker threads over the next updates and is drawn once it is ready.

### C

```c
sona_avatar *avatar = NULL;
sona_avatar_add_base64(ctx, b64, NULL, &avatar);   /* b64: the manifest; returns at once */
sona_avatar_play(avatar, "GenericWave", NULL);     /* remembered until it is ready */
```

Its state is `SONA_AVATAR_READY` when it can be drawn; `sona_poll_event` tells you when (`SONA_EVENT_READY`), or turn
on [placeholders](guides/placeholder.md) to show a neutral figure meanwhile.

### C++

```cpp
sona::Avatar avatar = ctx.add_base64(argv[2]);
```

### C#

```csharp
var avatar = ctx.AddBase64(args[1]);
while (avatar.State != SonaAvatarState.Ready && avatar.State != SonaAvatarState.Failed) ctx.Update(1.0 / 60);
if (avatar.State != SonaAvatarState.Ready) { Console.Error.WriteLine("the avatar did not load"); return 1; }

avatar.Play("GenericWave");
for (var i = 0; i < 60; i++) ctx.Update(1.0 / 60);
```

### Rust

```rust
let avatar = ctx.add_base64(&args[1], &sona::AddOptions::default()).map_err(|e| e.to_string())?;
```

### Python

```python
avatar = ctx.add_base64(manifest)
while not avatar.settled:
    ctx.update(1 / 60)
if not avatar.ready:
    sys.exit("the avatar did not load")

avatar.play("GenericWave")
```

### JavaScript

`add()` returns at once; `ready` resolves when the avatar is drawn:

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericWave' });
await avatar.ready;
```
### Unity

A `SonaAvatar` component holds the manifest. This script, on any GameObject, adds one waving; `manifest` is a text
asset holding the avatar as base64 (the package's Components sample):

```csharp
void Start()
{
    var avatar = new GameObject("Avatar").AddComponent<SonaAvatar>();
    avatar.manifestAsset = manifest;
    avatar.clip = "GenericWave";
}
```

### Godot

A `SonaAvatar3D` node holds the manifest. The root script of the demo's hello scene:

```gdscript
func _ready() -> void:
	var avatar = ClassDB.instantiate("SonaAvatar3D")
	var text = FileAccess.get_file_as_string("res://hello/manifest.txt")
	avatar.manifest = text.strip_edges()
	avatar.clip = "GenericWave"
	add_child(avatar)
	avatar.avatar_ready.connect(func(): avatar.frame_camera($Camera3D))
```

### Unreal

A `USonaAvatarComponent` holds the manifest. This actor of the SonaStarter project reads it from
`Content/manifest.txt`:

```cpp
AHelloAvatar::AHelloAvatar()
{
	Avatar = CreateDefaultSubobject<USonaAvatarComponent>(TEXT("Avatar"));
	RootComponent = Avatar;
	Avatar->Clip = TEXT("GenericWave");
}

void AHelloAvatar::BeginPlay()
{
	Super::BeginPlay();
	FString Manifest;
	if (FFileHelper::LoadFileToString(Manifest, *FPaths::Combine(FPaths::ProjectContentDir(), TEXT("manifest.txt"))))
		Avatar->SetManifest(Manifest.TrimStartAndEnd());
}
```

## 3. Make a renderer on your device

The device stays yours. Hand it over in a `sona_device_desc`; the union member is per backend.

| Backend | `backend` | Fill |
|---|---|---|
| OpenGL 3.3, OpenGL ES 3.0 | `SONA_BACKEND_GL`, `SONA_BACKEND_GLES` | `u.gl.get_proc`, with the context current |
| Vulkan 1.1 | `SONA_BACKEND_VULKAN` | `u.vk`: instance, physical device, device, queue, queue family |
| Direct3D 11 | `SONA_BACKEND_D3D11` | `u.d3d11`: the device and its context |
| Direct3D 12 | `SONA_BACKEND_D3D12` | `u.d3d12`: the device and a command queue |
| Metal | `SONA_BACKEND_METAL` | `u.metal`: the `MTLDevice` |

No window at all? `sona_headless_open` makes a device of the library's own: [headless rendering](guides/headless.md).

### C

```c
sona_device_desc dev;
sona_renderer *renderer = NULL;
memset(&dev, 0, sizeof dev);
dev.backend = SONA_BACKEND_GL;
dev.u.gl.get_proc = my_gl_get_proc;          /* SDL_GL_GetProcAddress, glfwGetProcAddress, ... */
while (sona_renderer_create(ctx, &dev, &renderer) == SONA_PENDING)
  sona_update(ctx, 0, NULL, NULL);           /* the shading data is still arriving */
```

### C++

```cpp
sona_device_desc dev;
std::memset(&dev, 0, sizeof dev);
dev.backend = SONA_BACKEND_GL;
dev.u.gl.get_proc = my_gl_get_proc;
sona::Renderer renderer;
while (sona::Renderer::create(ctx, dev, renderer) == SONA_PENDING)
  ctx.update(0);                               // the shading data is still arriving
```

### C#

```csharp
var dev = new Native.sona_device_desc { backend = SonaBackend.GL };
dev.u.gl.get_proc = getProc;                 // SDL_GL_GetProcAddress, glfwGetProcAddress, ...
SonaRenderer renderer;
while ((renderer = ctx.CreateRenderer(dev)) == null)
    ctx.Update(0);                           // the shading data is still arriving
```

### Rust

```rust
let mut dev: sys::sona_device_desc = unsafe { std::mem::zeroed() };
dev.backend = sys::SONA_BACKEND_GL;
dev.u.gl.get_proc = Some(get_proc); // SDL_GL_GetProcAddress, glfwGetProcAddress, ...
let mut frame = ctx.frame()?;
let mut renderer = loop {
    if let Some(r) = unsafe { sona::Renderer::new(ctx, &dev)? } {
        break r;
    }
    frame.update(0.0, None)?; // the shading data is still arriving
};
```

### Python

The Python binding draws on no device of yours. It reads the posed avatar each frame for your own pass (step 4), or
draws with a device of the library's own:

```python
with sona.Headless(ctx) as h:
    rgba = h.render(avatar, width=1280, height=720, clip="GenericWave")
```

### JavaScript

The canvas given to `create()` is the device: the SDK draws with WebGPU where the browser has it and WebGL2 where it
does not ([WebGPU and WebGL2](guides/web-webgpu.md)). There is nothing more to make.

### Unity

Unity draws the avatars with its own renderer, as it draws any mesh. There is no renderer to make.

### Godot

Godot draws `SonaAvatar3D` nodes with its own renderer, as it draws any mesh. There is no renderer to make.

### Unreal

Unreal draws `USonaAvatarComponent`s with its own renderer, as it draws any mesh. There is no renderer to make.

## 4. The frame

Each frame, update the context (it moves every avatar on) and draw. `view` is your camera: set `eye`, `target` and
`fov_deg` yourself, or let the library frame the avatar with `sona_camera_preset`. `target` names where the draw lands:
a GL framebuffer, a Vulkan image and command buffer, a D3D render target. The avatars are drawn over a clear of your
choice; to lay them over your own scene, draw into a texture and composite it, or read posed meshes with the
data API and draw them in your own pass ([your own renderer](guides/own-renderer.md)).

### C

```c
sona_view view;
sona_target target;
sona_view_defaults(&view);                     /* a full-body framing of an avatar at the origin */
view.width = 1280;
view.height = 720;
memset(&target, 0, sizeof target);
target.width = 1280;
target.height = 720;
target.u.gl.framebuffer = 0;                   /* the window; per backend, as the device */

while (game_running()) {
  sona_frame_stats stats;
  sona_update(ctx, dt, &view, &stats);         /* dt: seconds since the last frame */
  sona_draw(renderer, &view, &target, NULL);   /* into your target, the badge in a corner */
  present_frame();
}
```

### C++

```cpp
sona_view view;
sona_view_defaults(&view);
view.width = 1280;
view.height = 720;
sona_target target;
std::memset(&target, 0, sizeof target);
target.width = 1280;
target.height = 720;
target.u.gl.framebuffer = 0;                   // the window
while (game_running()) {
  ctx.update(dt, &view);
  renderer.draw(view, target);
  present_frame();
}
```

### C#

```csharp
var view = SonaView.Defaults();
view.Width = 1280;
view.Height = 720;
var target = new Native.sona_target { width = 1280, height = 720 };
target.u.gl.framebuffer = 0;                 // the window
while (gameRunning())
{
    ctx.Update(dt, view);
    renderer.Draw(view, target);
    presentFrame();
}
```

### Rust

```rust
let mut view = sona::view_defaults();
view.width = 1280;
view.height = 720;
let mut target: sys::sona_target = unsafe { std::mem::zeroed() };
target.width = 1280;
target.height = 720;
target.u.gl.framebuffer = 0; // the window
while game_running() {
    frame.update(dt, Some(&view))?;
    unsafe { renderer.draw(&view, &target, None)? };
    present_frame();
}
```

### Python

```python
view = sona.view_defaults()
while game_running():
    ctx.update(dt, view)
    pose = avatar.pose()   # this frame's posed meshes, for your own pass
    draw_meshes(pose.meshes)
```

### JavaScript

The SDK draws every frame on its own. To draw from your own loop, create it with `loop: 'manual'` and call `frame()`:

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas, loop: 'manual' });
sona.add(manifestBase64, { clip: 'GenericWave' });
function tick(t) {
  sona.frame(t).then(() => requestAnimationFrame(tick));
}
requestAnimationFrame(tick);
```

### Unity

Unity's frame updates the context and draws the avatars. Move the camera as you would for any scene.

### Godot

Godot's frame updates the context and draws the avatars; `frame_camera` frames one in a `Camera3D`.

### Unreal

Unreal's frame updates the context and draws the avatars. Move the camera as you would for any level.

## 5. Move it, dress it, change it

Place the avatar and change what it plays; the rest of what an avatar does, with its C calls:

| To | Call |
|---|---|
| Place the avatar | `sona_avatar_move(avatar, &placement, 0)` |
| Play, blend, queue clips | `sona_avatar_play`, `sona_avatar_crossfade`, `sona_avatar_queue` ([clips](guides/clips.md)) |
| Change the face | `sona_avatar_expression`; from audio, [lip sync](guides/lipsync.md) |
| Look at something, plant the feet | [IK](guides/ik.md) |
| Change what it wears | Edit the manifest with `sona_manifest_wear`, add it as a new avatar, and remove the old one when the new one is READY ([how](concepts/manifests.md#changing-one)) |
| Let the player do all of it | [The player editor](guides/editor.md) |

Each binding's name for each call is in the [bindings reference](reference/bindings.md).

### C

```c
sona_placement to = { { 1.0f, 0.0f, -2.0f }, 90.0f, 1.0f };
sona_avatar_move(avatar, &to, 0.5f);                  /* over half a second */
sona_avatar_crossfade(avatar, "GenericWave", NULL, 0.2f);
```

### C++

```cpp
sona_placement to = {{1.0f, 0.0f, -2.0f}, 90.0f, 1.0f};
sona_avatar_move(avatar.raw(), &to, 0.5f);     // over half a second; sona.hpp hands over the raw handle
avatar.crossfade("GenericWave", 0.2f);
```

### C#

```csharp
avatar.Move(new SonaPlacement(1, 0, -2, 90), 0.5f);   // over half a second
avatar.Crossfade("GenericWave", 0.2f);
```

### Rust

```rust
let to = sona::Placement { position: [1.0, 0.0, -2.0], turn_deg: 90.0, scale: 1.0 };
avatar.move_to(&to, 0.5); // over half a second
avatar.crossfade("GenericWave", &sona::PlayOptions::default(), 0.2)?;
```

### Python

```python
avatar.move(position=(1, 0, -2), turn_deg=90, over_seconds=0.5)
avatar.crossfade("GenericWave", 0.2)
```

### JavaScript

```js
avatar.move({ position: [1, 0, -2], turn: 90 }, { over: 0.5 });
avatar.play('GenericWave');
```

### Unity

Move the avatar's Transform; `Crossfade` changes what it plays. From the Components sample:

```csharp
if (moving != Walking && _waving <= 0
    && player.State == global::Sona.SonaAvatarState.Ready)
{
    Walking = moving;
    player.Crossfade(moving ? Walk : "idle", 0.25f);
}
```

### Godot

Move the node; `crossfade` changes what it plays. From the components demo:

```gdscript
var loaded: bool = player.get_state() == SonaAvatar3D.STATE_READY
if moving != walking and loaded and waving <= 0.0:
	walking = moving
	player.crossfade(WALK if moving else "idle", 0.25, true, 1.0, 0.0)
```

### Unreal

Move the actor or the component as any other; `Avatar->Crossfade(TEXT("GenericWave"), 0.2f, false)`
changes what it plays, and the 360sona Control Rig drives its IK ([the Unreal tutorial](tutorials/unreal.md)).

## 6. Shut down

### C

```c
sona_avatar_remove(avatar);       /* frees what only it used */
sona_renderer_destroy(renderer);  /* before your device goes */
sona_close(ctx);
```

### C++

```cpp
avatar.remove();
renderer.destroy();                            // before your device goes
ctx.close();
```

### C#

```csharp
avatar.Remove();
renderer.Dispose();                          // before your device goes
ctx.Dispose();
```

### Rust

```rust
avatar.remove();
drop(renderer); // before your device goes; the context closes when it is dropped
```

### Python

```python
avatar.remove()
ctx.close()   # or leave the "with sona.Context(...)" block
```

### JavaScript

```js
avatar.remove();
sona.destroy();
```

### Unity

Destroying a `SonaAvatar`'s GameObject removes the avatar; the `SonaContext` closes when it is destroyed.

### Godot

Freeing the node (`queue_free()`) removes the avatar.

### Unreal

When the actor ends play, its `USonaAvatarComponent` removes the avatar.

## Next

- The same in your language: [C++](tutorials/cpp.md), [C#](tutorials/csharp.md), [Rust](tutorials/rust.md),
  [Python](tutorials/python.md), [the web](tutorials/web.md); in an engine: [Unity](tutorials/unity.md),
  [Godot](tutorials/godot.md), [Unreal](tutorials/unreal.md).
- A whole program to start from: [the plaza starter](tutorials/starter-plaza.md).
- How the pieces fit: [concepts](concepts.md). Every call: [the C reference](reference.md).
