File size: 8,019 Bytes
cf772b4
3625ad2
cf772b4
 
 
 
 
 
3625ad2
cf772b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3625ad2
cf772b4
3625ad2
cf772b4
3625ad2
cf772b4
 
 
 
 
 
3625ad2
cf772b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3625ad2
cf772b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3625ad2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

document.addEventListener('DOMContentLoaded', () => {
    // Initialize PIXI application
    const app = new PIXI.Application({
        width: 800,
        height: 600,
        backgroundColor: 0x111111,
        view: document.getElementById('previewContainer')
    });

    // File upload handling
    const setupFileUpload = () => {
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const uploadBtn = document.getElementById('uploadBtn');
        const resetBtn = document.getElementById('zoomResetBtn');
        
        // Set up drag and drop
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        function highlight() {
            dropZone.classList.add('border-indigo-400');
        }
        
        function unhighlight() {
            dropZone.classList.remove('border-indigo-400');
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, unhighlight, false);
        });
        
        dropZone.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const files = e.dataTransfer.files;
            handleFiles(files);
        }
        
        uploadBtn.addEventListener('click', () => fileInput.click());
        fileInput.addEventListener('change', () => handleFiles(fileInput.files));
        
        function handleFiles(files) {
            if (!files.length) return;
            const file = files[0];
            if (!file.type.startsWith('image/')) {
                alert('Please upload an image file.');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = async (e) => {
                await loadCharacter(e.target.result);
            };
            reader.readAsDataURL(file);
        }
        
        resetBtn.addEventListener('click', () => {
            app.stage.removeChildren();
            document.querySelector('#previewContainer p').style.display = 'block';
        });
    };

    // Character rigging functionality
    const loadCharacter = async (imageSrc) => {
        try {
            // Load character texture
            const texture = await PIXI.Texture.fromURL(imageSrc);
            const sprite = new PIXI.Sprite(texture);
            
            // Center and scale sprite
            sprite.anchor.set(0.5);
            sprite.x = app.screen.width / 2;
            sprite.y = app.screen.height / 2;
            sprite.scale.set(0.5);
            
            app.stage.addChild(sprite);
            document.querySelector('#previewContainer p').style.display = 'none';
            
            // Initialize rigging controls
            initRiggingControls(sprite);
            
        } catch (error) {
            console.error('Error loading character:', error);
            alert('Failed to load character image');
        }
    };

    // Rigging controls
    const initRiggingControls = (sprite) => {
        // Zoom controls
        document.getElementById('zoomInBtn').addEventListener('click', () => {
            sprite.scale.x *= 1.1;
            sprite.scale.y *= 1.1;
        });
        
        document.getElementById('zoomOutBtn').addEventListener('click', () => {
            sprite.scale.x = Math.max(0.1, sprite.scale.x * 0.9);
            sprite.scale.y = Math.max(0.1, sprite.scale.y * 0.9);
        });
        
        // Pivot point controls
        document.querySelectorAll('.pivot-control input').forEach(input => {
            input.addEventListener('input', (e) => {
                const part = e.target.dataset.part;
                const axis = e.target.dataset.axis;
                // Update pivot point position
                // This would be connected to actual rigging logic
            });
        });
        
        // Auto-detect pivots using free API
        document.getElementById('autoPivotsBtn').addEventListener('click', async () => {
            try {
                // This would call a free pose detection API
                const response = await fetch('https://api.posenet.com/detect', {
                    method: 'POST',
                    body: JSON.stringify({ image: sprite.texture.baseTexture.source.src })
                });
                const data = await response.json();
                // Update pivot points based on detected keypoints
                console.log('Detected pivots:', data);
            } catch (error) {
                console.error('Pivot detection failed:', error);
            }
        });
    };

    // Initialize
    setupFileUpload();
// Initialize PixiJS for rigging with API integration
    async function initPixi(imageSrc) {
        try {
            console.log('Initializing character rigging');
            
            // Create form data for API request
            const formData = new FormData();
            const blob = await fetch(imageSrc).then(r => r.blob());
            formData.append('image', blob, 'character.png');
            formData.append('name', document.getElementById('charName').value || 'Unnamed');
            formData.append('type', document.getElementById('charType').value);
            
            // Send to API endpoint
            const response = await fetch('/api/upload', {
                method: 'POST',
                body: formData
            });
            
            if (!response.ok) {
                throw new Error(`API Error: ${response.status}`);
            }
            
            const data = await response.json();
            console.log('Character uploaded:', data);
            
            // Initialize PixiJS with the returned character data
            const app = new PIXI.Application({
                width: 600,
                height: 600,
                transparent: true,
                view: document.getElementById('previewContainer')
            });
            
            const sprite = PIXI.Sprite.from(imageSrc);
            sprite.anchor.set(0.5);
            sprite.x = app.screen.width / 2;
            sprite.y = app.screen.height / 2;
            app.stage.addChild(sprite);
            
            // Store character ID for future API calls
            previewContainer.dataset.characterId = data.id;
            
        } catch (error) {
            console.error('Rigging initialization failed:', error);
            alert('Failed to initialize rigging. Please try again.');
        }
    }
    
    // Setup API event listeners
    document.querySelectorAll('[data-api-call]').forEach(btn => {
        btn.addEventListener('click', async () => {
            const endpoint = btn.dataset.apiCall;
            try {
                const charId = previewContainer.dataset.characterId;
                if (!charId) throw new Error('No character loaded');
                
                const response = await fetch(`/api/${endpoint}`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({ character_id: charId })
                });
                
                if (!response.ok) throw new Error(await response.text());
                const result = await response.json();
                console.log(`${endpoint} success:`, result);
                
            } catch (error) {
                console.error(`${endpoint} failed:`, error);
                alert(`API Error: ${error.message}`);
            }
        });
    });
    
    console.log('BoneWizardry 3000 Unleashed initialized');
});