# 3D Generation API

Generate 3D models, textures, and animations using AI-powered tools.

## Overview

The 3D Generation API enables creation of 3D assets from text prompts, images,
or existing meshes. It supports multiple generation methods and output formats
optimized for game engines and film production.

**Base Path:** `/v1/3d`

**Authentication:** Bearer token required

## Endpoints Summary

| Method | Path                   | Description                         |
| ------ | ---------------------- | ----------------------------------- |
| POST   | `/generate/text`       | Generate 3D model from text prompt  |
| POST   | `/generate/image`      | Generate 3D model from image(s)     |
| POST   | `/generate/sketch`     | Generate 3D model from sketch       |
| GET    | `/jobs/{jobId}`        | Get generation job status           |
| GET    | `/jobs/{jobId}/result` | Get generation result               |
| DELETE | `/jobs/{jobId}`        | Cancel generation job               |
| GET    | `/jobs`                | List generation jobs                |
| POST   | `/mesh/process`        | Process/optimize mesh               |
| POST   | `/mesh/retopology`     | Retopologize mesh                   |
| POST   | `/mesh/decimate`       | Reduce mesh polygon count           |
| POST   | `/mesh/uv-unwrap`      | Generate UV mapping                 |
| POST   | `/texture/generate`    | Generate textures for mesh          |
| POST   | `/texture/upscale`     | Upscale texture resolution          |
| POST   | `/texture/pbr`         | Generate PBR texture set            |
| POST   | `/rig/auto`            | Auto-rig character mesh             |
| POST   | `/rig/retarget`        | Retarget animation to rig           |
| POST   | `/animation/generate`  | Generate animation from description |
| GET    | `/providers`           | List available AI providers         |
| GET    | `/styles`              | List available generation styles    |
| GET    | `/presets`             | List generation presets             |

---

## Text-to-3D Generation

### Generate from Text

Create a 3D model from a text description.

```http
POST /v1/3d/generate/text
Authorization: Bearer <token>
Content-Type: application/json

{
  "prompt": "A medieval knight in full plate armor, battle-worn, detailed engravings",
  "negativePrompt": "low quality, blurry, deformed",
  "style": "realistic",
  "category": "character",
  "provider": "hunyuan",
  "format": "glb",
  "resolution": "high",
  "polyCount": "medium",
  "generateTextures": true,
  "textureResolution": 2048,
  "generateRig": true,
  "rigType": "humanoid",
  "seed": 12345,
  "projectId": "proj_abc123",
  "callbackUrl": "https://your-server.com/webhook"
}
```

**Request Parameters:**

| Field               | Type    | Required | Description                                                                                                                                                       |
| ------------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt`            | string  | Yes      | Text description of the desired 3D model                                                                                                                          |
| `negativePrompt`    | string  | No       | Elements to avoid in generation                                                                                                                                   |
| `style`             | string  | No       | Generation style (see styles endpoint)                                                                                                                            |
| `category`          | string  | No       | Asset category: `character`, `creature`, `prop`, `vehicle`, `environment`, `architecture`, `weapon`, `clothing`, `furniture`, `organic`, `mechanical`, `abstract` |
| `provider`          | string  | No       | AI provider: `hunyuan`, `meshy`, `tripo`, `csm` (default: best available)                                                                                         |
| `format`            | string  | No       | Output format: `glb`, `gltf`, `fbx`, `obj`, `usd` (default: `glb`)                                                                                                |
| `resolution`        | string  | No       | Quality level: `draft`, `standard`, `high`, `ultra`                                                                                                               |
| `polyCount`         | string  | No       | Polygon budget: `low` (<10k), `medium` (10-50k), `high` (50-200k), `ultra` (200k+)                                                                                |
| `generateTextures`  | boolean | No       | Generate textures (default: true)                                                                                                                                 |
| `textureResolution` | number  | No       | Texture size: 512, 1024, 2048, 4096                                                                                                                               |
| `generateRig`       | boolean | No       | Auto-rig if character/creature                                                                                                                                    |
| `rigType`           | string  | No       | Rig skeleton type: `humanoid`, `quadruped`, `custom`                                                                                                              |
| `seed`              | number  | No       | Random seed for reproducibility                                                                                                                                   |
| `projectId`         | string  | No       | Associate with project                                                                                                                                            |
| `callbackUrl`       | string  | No       | Webhook URL for completion notification                                                                                                                           |

**Response (202 Accepted):**

```json
{
  "success": true,
  "data": {
    "jobId": "job_3d_abc123",
    "status": "pending",
    "message": "3D generation job queued",
    "estimatedTime": 120,
    "queuePosition": 3
  }
}
```

**Generation Styles:**

| Style          | Description                          |
| -------------- | ------------------------------------ |
| `realistic`    | Photorealistic rendering             |
| `stylized`     | Stylized/artistic look               |
| `cartoon`      | Cartoon/cel-shaded                   |
| `low_poly`     | Low-polygon aesthetic                |
| `anime`        | Anime/manga style                    |
| `pbr`          | Physically-based rendering optimized |
| `sculpted`     | High-detail sculpt look              |
| `hand_painted` | Hand-painted texture style           |

---

### Generate from Image

Create a 3D model from one or more reference images.

```http
POST /v1/3d/generate/image
Authorization: Bearer <token>
Content-Type: application/json

{
  "images": [
    {
      "url": "https://example.com/front.jpg",
      "view": "front"
    },
    {
      "url": "https://example.com/side.jpg",
      "view": "left"
    }
  ],
  "reconstructionMode": "multiview",
  "prompt": "High-quality game asset",
  "format": "glb",
  "generateTextures": true
}
```

**Request Parameters:**

| Field                | Type    | Required | Description                                                                    |
| -------------------- | ------- | -------- | ------------------------------------------------------------------------------ |
| `images`             | array   | Yes      | Array of image objects                                                         |
| `images[].url`       | string  | Yes      | Image URL (https or data URI)                                                  |
| `images[].view`      | string  | No       | View angle: `front`, `back`, `left`, `right`, `top`, `bottom`, `perspective`   |
| `reconstructionMode` | string  | No       | Mode: `single` (one image), `multiview` (multiple angles), `turntable` (video) |
| `prompt`             | string  | No       | Additional guidance for generation                                             |
| `removeBackground`   | boolean | No       | Auto-remove image background                                                   |
| `format`             | string  | No       | Output format                                                                  |
| `generateTextures`   | boolean | No       | Generate textures from images                                                  |

**Response:** Same as text-to-3D

---

## Job Management

### Get Job Status

Check the status of a generation job.

```http
GET /v1/3d/jobs/{jobId}
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "jobId": "job_3d_abc123",
    "status": "processing",
    "progress": 45,
    "stage": "generating_mesh",
    "stages": [
      { "name": "queued", "completed": true, "duration": 5000 },
      { "name": "generating_mesh", "completed": false, "progress": 60 },
      { "name": "generating_textures", "completed": false },
      { "name": "post_processing", "completed": false }
    ],
    "estimatedTimeRemaining": 65,
    "createdAt": "2024-01-15T10:00:00Z",
    "startedAt": "2024-01-15T10:00:05Z"
  }
}
```

**Job Statuses:**

| Status       | Description            |
| ------------ | ---------------------- |
| `pending`    | Job is queued          |
| `processing` | Currently generating   |
| `completed`  | Successfully completed |
| `failed`     | Generation failed      |
| `cancelled`  | Job was cancelled      |

### Get Job Result

Retrieve the generated 3D model.

```http
GET /v1/3d/jobs/{jobId}/result
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": {
    "jobId": "job_3d_abc123",
    "status": "completed",
    "model": {
      "url": "https://cdn.yemaya.io/3d/job_3d_abc123/model.glb",
      "format": "glb",
      "fileSize": 15000000,
      "polyCount": 45000,
      "vertexCount": 48000,
      "materialCount": 3,
      "boundingBox": {
        "min": [-1.0, 0.0, -0.5],
        "max": [1.0, 2.0, 0.5]
      }
    },
    "textures": [
      {
        "type": "diffuse",
        "url": "https://cdn.yemaya.io/3d/job_3d_abc123/diffuse.png",
        "resolution": 2048
      },
      {
        "type": "normal",
        "url": "https://cdn.yemaya.io/3d/job_3d_abc123/normal.png",
        "resolution": 2048
      },
      {
        "type": "roughness",
        "url": "https://cdn.yemaya.io/3d/job_3d_abc123/roughness.png",
        "resolution": 2048
      }
    ],
    "rig": {
      "type": "humanoid",
      "boneCount": 65,
      "url": "https://cdn.yemaya.io/3d/job_3d_abc123/rig.json"
    },
    "preview": {
      "thumbnail": "https://cdn.yemaya.io/3d/job_3d_abc123/thumb.png",
      "turntable": "https://cdn.yemaya.io/3d/job_3d_abc123/turntable.mp4"
    },
    "metadata": {
      "provider": "hunyuan",
      "generationTime": 95000,
      "seed": 12345,
      "prompt": "A medieval knight..."
    },
    "createdAt": "2024-01-15T10:00:00Z",
    "completedAt": "2024-01-15T10:01:35Z"
  }
}
```

### List Jobs

Get a list of generation jobs.

```http
GET /v1/3d/jobs?status=completed&limit=20
Authorization: Bearer <token>
```

**Query Parameters:**

| Parameter   | Type   | Description              |
| ----------- | ------ | ------------------------ |
| `status`    | string | Filter by status         |
| `projectId` | string | Filter by project        |
| `category`  | string | Filter by asset category |
| `page`      | number | Page number              |
| `limit`     | number | Items per page           |

### Cancel Job

Cancel a pending or processing job.

```http
DELETE /v1/3d/jobs/{jobId}
Authorization: Bearer <token>
```

---

## Mesh Processing

### Process Mesh

Apply processing operations to an existing mesh.

```http
POST /v1/3d/mesh/process
Authorization: Bearer <token>
Content-Type: application/json

{
  "meshUrl": "https://example.com/model.glb",
  "operations": [
    { "type": "center", "options": {} },
    { "type": "scale", "options": { "factor": 1.5 } },
    { "type": "smooth", "options": { "iterations": 2 } },
    { "type": "decimate", "options": { "ratio": 0.5 } }
  ],
  "outputFormat": "glb"
}
```

**Available Operations:**

| Operation        | Description              | Options                            |
| ---------------- | ------------------------ | ---------------------------------- |
| `center`         | Center mesh at origin    | -                                  |
| `scale`          | Scale mesh               | `factor`: scale multiplier         |
| `rotate`         | Rotate mesh              | `x`, `y`, `z`: rotation in degrees |
| `translate`      | Move mesh                | `x`, `y`, `z`: offset values       |
| `smooth`         | Smooth mesh surface      | `iterations`: number of passes     |
| `decimate`       | Reduce polygon count     | `ratio`: 0.0-1.0                   |
| `triangulate`    | Convert to triangles     | -                                  |
| `flip_normals`   | Flip face normals        | -                                  |
| `recalc_normals` | Recalculate normals      | `angle`: threshold angle           |
| `remove_doubles` | Merge duplicate vertices | `threshold`: distance              |
| `fill_holes`     | Fill mesh holes          | `maxSize`: max hole size           |

### Auto-Retopology

Generate clean topology from a high-poly mesh.

```http
POST /v1/3d/mesh/retopology
Authorization: Bearer <token>
Content-Type: application/json

{
  "meshUrl": "https://example.com/sculpt.obj",
  "targetPolyCount": 10000,
  "preserveDetails": true,
  "generateUVs": true,
  "symmetry": "x"
}
```

### Generate UVs

Create UV mapping for a mesh.

```http
POST /v1/3d/mesh/uv-unwrap
Authorization: Bearer <token>
Content-Type: application/json

{
  "meshUrl": "https://example.com/model.glb",
  "method": "smart_project",
  "packMargin": 0.01,
  "stretchMinimize": true
}
```

**UV Methods:**

| Method             | Description                       |
| ------------------ | --------------------------------- |
| `smart_project`    | Automatic projection-based unwrap |
| `cube_project`     | Box projection                    |
| `cylinder_project` | Cylindrical projection            |
| `sphere_project`   | Spherical projection              |
| `lightmap_pack`    | Optimized for lightmaps           |

---

## Texture Generation

### Generate Textures

Generate textures for an existing mesh.

```http
POST /v1/3d/texture/generate
Authorization: Bearer <token>
Content-Type: application/json

{
  "meshUrl": "https://example.com/model.glb",
  "prompt": "Worn leather armor with metal studs, battle damage",
  "style": "realistic",
  "resolution": 2048,
  "generatePBR": true,
  "pbrMaps": ["diffuse", "normal", "roughness", "metallic", "ao"]
}
```

**PBR Map Types:**

| Map         | Description             |
| ----------- | ----------------------- |
| `diffuse`   | Base color/albedo       |
| `normal`    | Normal map              |
| `roughness` | Roughness map           |
| `metallic`  | Metallic map            |
| `ao`        | Ambient occlusion       |
| `height`    | Height/displacement map |
| `emissive`  | Emission map            |

### Upscale Texture

Increase texture resolution using AI.

```http
POST /v1/3d/texture/upscale
Authorization: Bearer <token>
Content-Type: application/json

{
  "textureUrl": "https://example.com/texture_1k.png",
  "targetResolution": 4096,
  "preserveDetails": true,
  "denoising": 0.3
}
```

---

## Auto-Rigging

### Rig Character

Automatically rig a character mesh.

```http
POST /v1/3d/rig/auto
Authorization: Bearer <token>
Content-Type: application/json

{
  "meshUrl": "https://example.com/character.glb",
  "rigType": "humanoid",
  "options": {
    "fingerBones": true,
    "facialBones": true,
    "ikSetup": true,
    "skinWeights": "auto"
  }
}
```

**Rig Types:**

| Type              | Description                |
| ----------------- | -------------------------- |
| `humanoid`        | Standard humanoid skeleton |
| `humanoid_simple` | Simplified humanoid        |
| `quadruped`       | Four-legged creature       |
| `bird`            | Bird/flying creature       |
| `fish`            | Aquatic creature           |
| `insect`          | Multi-legged insect        |
| `custom`          | Custom bone structure      |

### Retarget Animation

Transfer animation from one rig to another.

```http
POST /v1/3d/rig/retarget
Authorization: Bearer <token>
Content-Type: application/json

{
  "sourceAnimation": "https://example.com/walk_cycle.fbx",
  "targetRig": "https://example.com/character_rigged.glb",
  "options": {
    "preserveFootContact": true,
    "adjustHips": true,
    "boneMapping": "auto"
  }
}
```

---

## Animation Generation

### Generate Animation

Create animation from text description.

```http
POST /v1/3d/animation/generate
Authorization: Bearer <token>
Content-Type: application/json

{
  "rigUrl": "https://example.com/character_rigged.glb",
  "prompt": "Character performs a victory dance with fist pump",
  "duration": 3.0,
  "style": "exaggerated",
  "looping": true,
  "fps": 30
}
```

**Animation Styles:**

| Style         | Description             |
| ------------- | ----------------------- |
| `realistic`   | Motion-captured quality |
| `stylized`    | Stylized game animation |
| `exaggerated` | Cartoon exaggeration    |
| `subtle`      | Minimal, subtle motion  |

---

## Providers & Presets

### List Providers

Get available AI providers and their capabilities.

```http
GET /v1/3d/providers
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "hunyuan",
      "name": "Hunyuan 3D",
      "capabilities": ["text_to_3d", "image_to_3d", "texturing"],
      "qualityTier": "high",
      "averageTime": 120,
      "costPerGeneration": 0.1,
      "available": true
    },
    {
      "id": "meshy",
      "name": "Meshy AI",
      "capabilities": ["text_to_3d", "image_to_3d", "texturing", "stylization"],
      "qualityTier": "medium",
      "averageTime": 60,
      "costPerGeneration": 0.05,
      "available": true
    }
  ]
}
```

### List Styles

Get available generation styles.

```http
GET /v1/3d/styles
Authorization: Bearer <token>
```

### List Presets

Get preconfigured generation presets.

```http
GET /v1/3d/presets
Authorization: Bearer <token>
```

**Response:**

```json
{
  "success": true,
  "data": [
    {
      "id": "game_character_high",
      "name": "High-Quality Game Character",
      "description": "Optimized for modern game engines",
      "settings": {
        "polyCount": "high",
        "textureResolution": 4096,
        "generateRig": true,
        "rigType": "humanoid",
        "format": "glb"
      }
    },
    {
      "id": "mobile_prop",
      "name": "Mobile Game Prop",
      "description": "Low-poly optimized for mobile",
      "settings": {
        "polyCount": "low",
        "textureResolution": 512,
        "format": "glb"
      }
    }
  ]
}
```

---

## WebSocket Events

Subscribe to real-time generation progress via WebSocket.

### Subscribe to Job Updates

```json
{
  "type": "subscribe",
  "timestamp": "2024-01-15T10:00:00Z",
  "channel": "job",
  "resourceId": "job_3d_abc123",
  "events": ["generation:progress", "generation:complete", "generation:failed"]
}
```

### Event: generation:progress

```json
{
  "type": "generation:progress",
  "timestamp": "2024-01-15T10:00:30Z",
  "jobId": "job_3d_abc123",
  "jobType": "text_to_3d",
  "progress": 45,
  "stage": "generating_mesh",
  "message": "Generating base mesh structure...",
  "estimatedSecondsRemaining": 65
}
```

### Event: generation:complete

```json
{
  "type": "generation:complete",
  "timestamp": "2024-01-15T10:01:35Z",
  "jobId": "job_3d_abc123",
  "jobType": "text_to_3d",
  "resultUrl": "https://cdn.yemaya.io/3d/job_3d_abc123/model.glb",
  "previewUrl": "https://cdn.yemaya.io/3d/job_3d_abc123/thumb.png",
  "processingTime": 95000
}
```

---

## Error Codes

| Code                   | Description                                 |
| ---------------------- | ------------------------------------------- |
| `INVALID_PROMPT`       | Prompt is empty or contains invalid content |
| `INVALID_IMAGE`        | Image URL is invalid or inaccessible        |
| `UNSUPPORTED_FORMAT`   | Requested format not supported              |
| `MESH_TOO_COMPLEX`     | Input mesh exceeds complexity limits        |
| `PROVIDER_UNAVAILABLE` | Selected AI provider is offline             |
| `GENERATION_FAILED`    | Generation process failed                   |
| `QUOTA_EXCEEDED`       | Generation quota exceeded                   |
| `JOB_NOT_FOUND`        | Job ID does not exist                       |
| `JOB_EXPIRED`          | Job results have expired                    |

---

## Rate Limits

| Endpoint                | Limit      |
| ----------------------- | ---------- |
| Generation endpoints    | 10/minute  |
| Processing endpoints    | 30/minute  |
| Status/result endpoints | 100/minute |

---

## Best Practices

1. **Use Callbacks**: For long-running generations, use `callbackUrl` instead of
   polling
2. **Choose Appropriate Quality**: Match `resolution` and `polyCount` to your
   use case
3. **Batch Similar Jobs**: Group similar generations to optimize queue
   processing
4. **Cache Results**: Store generated assets; regeneration is not guaranteed to
   produce identical results
5. **Handle Failures Gracefully**: Implement retry logic with exponential
   backoff

---

## SDK Examples

### TypeScript

```typescript
import { YemayaClient } from '@yemaya/sdk';

const client = new YemayaClient({ apiKey: 'yek_...' });

// Generate 3D model from text
const job = await client.generation3d.generateFromText({
  prompt: 'A medieval castle with tall towers',
  style: 'realistic',
  format: 'glb',
  generateTextures: true,
});

// Wait for completion
const result = await client.generation3d.waitForJob(job.jobId, {
  onProgress: (progress) => console.log(`Progress: ${progress}%`),
});

console.log('Model URL:', result.model.url);
```

### Python

```python
from yemaya import YemayaClient

client = YemayaClient(api_key="yek_...")

# Generate 3D model
job = client.generation_3d.generate_from_text(
    prompt="A medieval castle with tall towers",
    style="realistic",
    format="glb"
)

# Wait for completion
result = client.generation_3d.wait_for_job(
    job.job_id,
    on_progress=lambda p: print(f"Progress: {p}%")
)

print(f"Model URL: {result.model.url}")
```
