Jump to content

Test: Difference between revisions

From Survivalcraft Wiki
No edit summary
No edit summary
Line 20: Line 20:
<div style="margin-bottom: 10px; font-family: sans-serif;">
<div style="margin-bottom: 10px; font-family: sans-serif;">
     <label for="bearTexture" style="font-weight: bold; margin-right: 10px;">Bear Type:</label>
     <label for="bearTexture" style="font-weight: bold; margin-right: 10px;">Bear Type:</label>
     <select id="bearTexture" style="padding: 5px; border: 1px solid #ccc; border-radius: 4px;">
     <select id="bearTexture-{{PAGENAME}}" style="padding: 5px; border: 1px solid #ccc; border-radius: 4px;">
         <option value="brown">Brown Bear</option>
         <option value="brown">Brown Bear</option>
         <option value="black">Black Bear</option>
         <option value="black">Black Bear</option>
Line 27: Line 27:


<model-viewer
<model-viewer
     id="bearModelViewer"
     id="bearModelViewer-{{PAGENAME}}"
     src="https://survivalcraft.wiki/content/Models/Bear.glb"
     src="https://survivalcraft.wiki/content/Models/Bear.glb"
     alt="3D Bear Model from Survivalcraft"
     alt="3D Bear Model from Survivalcraft"
Line 44: Line 44:
</model-viewer>
</model-viewer>


<div id="statusMessage" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif;">
<div id="statusMessage-{{PAGENAME}}" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif;">
     Loading model...
     Loading model...
</div>
</div>


<div id="controlsInfo" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif; display: none;">
<div id="controlsInfo-{{PAGENAME}}" style="margin-top: 10px; font-size: 12px; color: #666; font-family: sans-serif; display: none;">
     <strong>Controls:</strong> Click and drag to rotate • Scroll to zoom • Right-click and drag to pan
     <strong>Controls:</strong> Click and drag to rotate • Scroll to zoom • Right-click and drag to pan
</div>
</div>
</html>
{{#tag:script|type="module"|
    const modelViewer = document.getElementById('bearModelViewer');
    const bearTextureSelector = document.getElementById('bearTexture');
    const statusMessage = document.getElementById('statusMessage');
    const controlsInfo = document.getElementById('controlsInfo');


     // Define texture URLs for different bear types
<script type="module">
    const textures = {
(async () => {
        brown: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Brown.png',
     const jsCodeBase64 = `
        black: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Black.png'
        const modelViewer = document.getElementById('bearModelViewer-{{PAGENAME}}');
    };
        const bearTextureSelector = document.getElementById('bearTexture-{{PAGENAME}}');
        const statusMessage = document.getElementById('statusMessage-{{PAGENAME}}');
        const controlsInfo = document.getElementById('controlsInfo-{{PAGENAME}}');
 
        const textures = {
            brown: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Brown.png',
            black: 'https://survivalcraft.wiki/content/Textures/Creatures/Bear_Black.png'
        };


    let mainModelMaterial = null; // We'll store a reference to the bear's main material here
        let mainModelMaterial = null;


    // --- Event Listeners ---
        modelViewer.addEventListener('load', async () => {
            console.log('3D model loaded successfully!');
            statusMessage.textContent = 'Model loaded successfully!';
            controlsInfo.style.display = 'block';


    // When the model is fully loaded and ready
            if (modelViewer.model && modelViewer.model.materials.length > 0) {
    modelViewer.addEventListener('load', async () => {
                mainModelMaterial = modelViewer.model.materials[0];
        console.log('3D model loaded successfully!');
                console.log('Identified main model material:', mainModelMaterial);
        statusMessage.textContent = 'Model loaded successfully!';
                await applyBearTexture();
        controlsInfo.style.display = 'block';
            } else {
                console.warn('Could not find any materials in the loaded model. Texture changing might not work.');
                statusMessage.textContent = 'Model loaded, but materials not found for texture swap.';
                statusMessage.style.color = '#d63031';
            }
        });


         // Attempt to get the first material from the loaded model.
         modelViewer.addEventListener('error', (event) => {
        // Most simple GLB models have a single primary material.
             console.error('Error loading 3D model:', event);
        if (modelViewer.model && modelViewer.model.materials.length > 0) {
             statusMessage.textContent = 'Error loading model. Check your browser console.';
            mainModelMaterial = modelViewer.model.materials[0];
            console.log('Identified main model material:', mainModelMaterial);
            // Apply the default (brown) texture right after the model loads
            await applyBearTexture();
        } else {
             console.warn('Could not find any materials in the loaded model. Texture changing might not work.');
             statusMessage.textContent = 'Model loaded, but materials not found for texture swap.';
             statusMessage.style.color = '#d63031';
             statusMessage.style.color = '#d63031';
         }
         });
    });


    // Handle any errors during model loading
        modelViewer.addEventListener('progress', (event) => {
    modelViewer.addEventListener('error', (event) => {
            const progress = event.detail.totalProgress;
        console.error('Error loading 3D model:', event);
            statusMessage.textContent = \`Loading model... \${Math.round(progress * 100)}%\`;
        statusMessage.textContent = 'Error loading model. Check your browser console.';
        });
        statusMessage.style.color = '#d63031';
    });


    // Update loading progress
        bearTextureSelector.addEventListener('change', applyBearTexture);
    modelViewer.addEventListener('progress', (event) => {
        const progress = event.detail.totalProgress;
        statusMessage.textContent = `Loading model... ${Math.round(progress * 100)}%`;
    });


    // Listen for changes in the bear type dropdown
        async function applyBearTexture() {
    bearTextureSelector.addEventListener('change', applyBearTexture);
            if (!mainModelMaterial) {
                console.warn('Model material not yet available. Cannot change texture.');
                return;
            }


    // --- Functions ---
            const selectedTextureKey = bearTextureSelector.value;
            const textureUrl = textures[selectedTextureKey];


    /**
            if (!textureUrl) {
    * Applies the selected texture to the bear model.
                console.warn(\`No texture URL defined for "\${selectedTextureKey}".\`);
    * Uses model-viewer's internal texture management.
                return;
    */
            }
    async function applyBearTexture() {
        if (!mainModelMaterial) {
            console.warn('Model material not yet available. Cannot change texture.');
            return; // Exit if material isn't ready
        }


        const selectedTextureKey = bearTextureSelector.value;
            console.log(\`Attempting to apply "\${selectedTextureKey}" texture from: \${textureUrl}\`);
        const textureUrl = textures[selectedTextureKey];


        if (!textureUrl) {
            try {
             console.warn(`No texture URL defined for "${selectedTextureKey}".`);
                const newTexture = await modelViewer.createTexture(textureUrl);
             return;
                mainModelMaterial.pbrMetallicRoughness.baseColorTexture.setTexture(newTexture);
                console.log(\`Successfully applied \${selectedTextureKey} texture.\`);
             } catch (error) {
                console.error(\`Failed to apply \${selectedTextureKey} texture:\`, error);
                statusMessage.textContent = \`Error applying \${selectedTextureKey} texture.\`;
                statusMessage.style.color = '#d63031';
             }
         }
         }


         console.log(`Attempting to apply "${selectedTextureKey}" texture from: ${textureUrl}`);
         document.addEventListener('DOMContentLoaded', () => {
            console.log('DOM fully loaded and parsed.');


        try {
            if (typeof customElements.get('model-viewer') === 'undefined') {
            // 1. Create a new texture object using model-viewer's utility
                console.error('The <model-viewer> component failed to load or register.');
            const newTexture = await modelViewer.createTexture(textureUrl);
                statusMessage.textContent = 'Error: 3D viewer component not available.';
                statusMessage.style.color = '#d63031';
            }
        });
    `;


            // 2. Apply this new texture to the material's baseColorTexture property.
    // Decode and execute the JavaScript
            // This is the primary texture that gives the model its color.
    const decodedJsCode = atob(jsCodeBase64.trim());
            mainModelMaterial.pbrMetallicRoughness.baseColorTexture.setTexture(newTexture);
    const scriptElement = document.createElement('script');
 
    scriptElement.type = 'module';
            console.log(`Successfully applied ${selectedTextureKey} texture.`);
    scriptElement.textContent = decodedJsCode;
        } catch (error) {
    document.head.appendChild(scriptElement);
            console.error(`Failed to apply ${selectedTextureKey} texture:`, error);
})();
            statusMessage.textContent = `Error applying ${selectedTextureKey} texture.`;
</script>
            statusMessage.style.color = '#d63031';
</html>
        }
    }
 
    // --- Initial Checks (for debugging) ---
    document.addEventListener('DOMContentLoaded', () => {
        console.log('DOM fully loaded and parsed.');
 
        // Verify if the model-viewer custom element has been registered
        if (typeof customElements.get('model-viewer') === 'undefined') {
            console.error('The <model-viewer> component failed to load or register.');
            statusMessage.textContent = 'Error: 3D viewer component not available.';
            statusMessage.style.color = '#d63031';
        }
    });
}}

Revision as of 18:38, 28 July 2025


⚠️ Unable to load 3D model.
Check your browser console for details.

Loading model...
Cell 1 Cell 2
Cell 3 Cell 4