File size: 6,541 Bytes
7ac86fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<script lang="ts">
  import { onMount } from 'svelte';
  import ContinuousVideoPlayer from './ContinuousVideoPlayer.svelte';
  import NarrativeDisplay from './NarrativeDisplay.svelte';
  import ChoiceInterface from './ChoiceInterface.svelte';
  import SoraGenerator from './SoraGenerator.svelte';
  import { generateNarrative, buildSoraPrompt } from '$lib/api/openai';
  import {
    apiKey,
    currentScene,
    previousFinalFrame,
    addScene,
    updateCurrentScene,
    buildStoryContextText,
    setGenerating,
    setGenerationProgress,
    setGenerationError,
    isGenerating
  } from '$lib/stores/story';
  import type { StoryChoice, StoryScene, SoraGenerationParams } from '$lib/types';

  export let onError: ((error: string) => void) | undefined = undefined;

  let soraGenerator: any;
  let waitingForVideo = false;
  let showChoices = false;
  let currentVideoUrl: string | undefined;

  onMount(() => {
    // Start the adventure automatically
    startAdventure();
  });

  async function startAdventure() {
    if (!$apiKey) {
      const error = 'API key not set';
      setGenerationError(error);
      onError?.(error);
      return;
    }

    setGenerating(true);
    setGenerationError(null);

    try {
      // Generate the first scene
      const narrative = await generateNarrative($apiKey, {
        storyContext: '',
        isFirstScene: true
      });

      // Create the first scene
      const scene: StoryScene = {
        id: `scene-${Date.now()}`,
        narrative: narrative.narrative,
        choices: narrative.choices,
        timestamp: Date.now()
      };

      addScene(scene);

      // Generate the first video
      await generateVideoForCurrentScene(narrative.sceneDescription);

    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Failed to start adventure';
      setGenerationError(errorMsg);
      onError?.(errorMsg);
      setGenerating(false);
    }
  }

  async function generateVideoForCurrentScene(sceneDescription: string) {
    if (!$apiKey || !soraGenerator) return;

    waitingForVideo = true;
    showChoices = false;

    try {
      // Build the Sora prompt with context if available
      const storyContext = buildStoryContextText();
      const soraPrompt = buildSoraPrompt(sceneDescription, storyContext);

      // Create generation parameters
      const params: SoraGenerationParams = {
        prompt: soraPrompt,
        size: '1280x720',
        seconds: 8,
        model: 'sora-2',
        inputReference: $previousFinalFrame || undefined
      };

      // Trigger video generation
      await soraGenerator.generate();

    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Video generation failed';
      setGenerationError(errorMsg);
      onError?.(errorMsg);
      setGenerating(false);
      waitingForVideo = false;
    }
  }

  function handleVideoGenerated(event: CustomEvent<any>) {
    const result = event.detail;

    // Update current scene with video URL
    updateCurrentScene({ videoUrl: result.videoUrl });
    currentVideoUrl = result.videoUrl;

    waitingForVideo = false;
    setGenerating(false);
  }

  function handleVideoEnd(finalFrame: Blob) {
    // Store the final frame for continuity
    updateCurrentScene({ finalFrame });

    // Show choices after video ends
    showChoices = true;
  }

  async function handleChoiceSelected(choice: StoryChoice) {
    if (!$apiKey || $isGenerating) return;

    setGenerating(true);
    setGenerationError(null);
    showChoices = false;

    try {
      // Generate the next scene based on the choice
      const storyContext = buildStoryContextText();
      const narrative = await generateNarrative($apiKey, {
        storyContext,
        userChoice: choice.text,
        isFirstScene: false
      });

      // Create the new scene
      const scene: StoryScene = {
        id: `scene-${Date.now()}`,
        narrative: narrative.narrative,
        choices: narrative.choices,
        timestamp: Date.now()
      };

      addScene(scene);

      // Generate video for the new scene
      await generateVideoForCurrentScene(narrative.sceneDescription);

    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : 'Failed to continue story';
      setGenerationError(errorMsg);
      onError?.(errorMsg);
      setGenerating(false);
    }
  }

  function handleVideoError(error: string) {
    setGenerationError(error);
    onError?.(error);
  }

  function handleProgress(progress: number) {
    setGenerationProgress(progress);
  }

  function handleGenerationError(error: string) {
    setGenerationError(error);
    onError?.(error);
    setGenerating(false);
  }

  // Create Sora params for the generator component
  $: soraParams = $currentScene ? {
    prompt: buildSoraPrompt($currentScene.narrative, buildStoryContextText()),
    size: '1280x720',
    seconds: 8,
    model: 'sora-2',
    inputReference: $previousFinalFrame || undefined
  } as SoraGenerationParams : null;
</script>

<div class="story-engine">
  {#if $currentScene}
    <!-- Video Player -->
    <div class="video-section">
      <ContinuousVideoPlayer
        videoUrl={currentVideoUrl}
        onVideoEnd={handleVideoEnd}
        onError={handleVideoError}
      />
    </div>

    <!-- Narrative Display -->
    <NarrativeDisplay
      narrative={$currentScene.narrative}
      isVisible={!$isGenerating}
    />

    <!-- Sora Generator (hidden UI, controlled programmatically) -->
    {#if $apiKey && soraParams}
      <SoraGenerator
        bind:this={soraGenerator}
        apiKey={$apiKey}
        params={soraParams}
        onVideoGenerated={handleVideoGenerated}
        onProgress={handleProgress}
        onError={handleGenerationError}
      />
    {/if}

    <!-- Choices (shown after video ends) -->
    {#if showChoices && !$isGenerating}
      <ChoiceInterface
        choices={$currentScene.choices}
        onChoiceSelected={handleChoiceSelected}
        disabled={$isGenerating}
      />
    {/if}
  {:else if !$isGenerating}
    <div class="loading">
      <p>Initializing adventure...</p>
    </div>
  {/if}
</div>

<style>
  .story-engine {
    max-width: 1280px;
    margin: 0 auto;
    padding: 1rem;
  }

  .video-section {
    margin-bottom: 1rem;
  }

  .loading {
    text-align: center;
    padding: 4rem 2rem;
    color: #666;
  }

  .loading p {
    font-size: 1.1rem;
    margin: 0;
  }

  @media (max-width: 768px) {
    .story-engine {
      padding: 0.5rem;
    }
  }
</style>