Optimizing Shader Performance in Three.js

Looking to achieve optimal performance when rendering simple textured shapes? The Phong model requires extra lighting and color adjustments, leading to unwarranted complexities. To simplify matters, a flat shader seemed like the best solution, yet some issues have arisen:

    <script id="vertShader" type="shader">
        varying vec2 vUv;
        void main() {
              vUv = uv;
              gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
        }
    </script>
    <script id="fragShader" type="shader">
        varying vec2 vUv;
        uniform sampler2D material;
        void main() {
            gl_FragColor = texture2D(material, vUv);
        }
    </script>

Under specific camera angles, shelves appear to vanish, revealing darker spots and allowing for visibility through them – an occurrence not witnessed with the Phong material. The issue seems to be related to the shadow textures embedded within each shelf space, possibly affecting loading times.

The standard obj loader, coupled with texture additions, sets the material to Phong, necessitating a switch to a custom shader:

    var objLoader = new THREE.OBJLoader( manager );
    objLoader.load( obj, function ( model ) {

        elements[name] = model;
        console.log('loaded ', name);
        var img = THREE.ImageUtils.loadTexture(mat);
        elements[name].traverse( function ( child ) {
            if ( child instanceof THREE.Mesh ) {
                child.material = new THREE.ShaderMaterial( {
                    uniforms: {
                        color: {type: 'f', value: 0.0},
                        material: {type: 't', value: img}
                    },
                    fragmentShader: document.getElementById('fragShader').text,
                    vertexShader: document.getElementById('vertShader').text,
                } );
            }
        });

If you have any insights or suggestions on resolving these challenges, please share them!

Answer №1

Each surface must be drawn in a specific direction, either clockwise or counter-clockwise. If a surface is viewed from the opposite side, it will appear to disappear. This issue may be related to your shader implementation. To address this, you can render surfaces from both sides (though this may impact performance) or determine the optimal side for rendering.

To enhance performance, consider using a standard material from THREE.js instead of creating your own shader:

child.material = new THREE.MeshBasicMaterial({
    side: THREE.DoubleSide,
    color: 0x000000
    // ...
});

I have previously worked on a project where I created a skybox material with textures. Here is an example of how this was implemented:

function getSkyboxMaterial() {
    var faceMaterials = getSkyboxFaces();
    var skyboxMaterial = new THREE.MeshFaceMaterial(faceMaterials);
    return skyboxMaterial;
}

function getSkyboxFaces() {
    var NUMBER_OF_FACES = 6, faces = [], texture, faceMaterial, texturePath, i;

    for (i = 0; i < NUMBER_OF_FACES; i++) {
        texturePath = IMAGE_PREFIX + DIRECTIONS[i] + IMAGE_SUFFIX;
        texture = loadFlippedTexture(texturePath);
        faceMaterial = getFaceMaterial(texture);
        faces.push(faceMaterial);
    }
    return faces;
}

function loadFlippedTexture(texturePath) {
    var texture = loadTexture(texturePath);
    flipTexture(texture); // Ensure proper orientation of skybox textures
    return texture;
}

function loadTexture(path) {
    return THREE.ImageUtils.loadTexture(path);
}

function flipTexture(texture) {
    texture.repeat.set(-1, 1);
    texture.offset.set(1, 0);
    return texture;
}

function getFaceMaterial(texture) {
    var faceMaterial = new THREE.MeshBasicMaterial({
        map: texture,
        side: THREE.DoubleSide
    });
    return faceMaterial;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Laravel and Inertia App to fetch data from an API endpoint

I am currently using Laravel with InertiaJS and VueJS for my App. Jetstream scaffolding is handling all the authentication tasks within the app. However, I am facing an issue with a few pages that need to access the api.php routes in my project. For examp ...

Ways to retrieve the inner text of a sibling element

Within GTM, I am attempting to retrieve the inner text of a sibling element when the clicked element is triggered. <div class="repair-item-n "> <div class="repair-slide--54894d33-6c88-488f-95d7-3ec9b6a3ade4"> <div class="restorati ...

useEffect runs endlessly

Currently, I am using React with hooks to handle API calls and implement autoscroll functionality on a data-heavy screen. However, I have encountered a problem where the autoscroll feature implemented through a separate useEffect is interfering with the ot ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

A useful Javascript function to wrap a string in <mark> tags within an HTML document

I have a paragraph that I can edit. I need to highlight certain words in this paragraph based on the JSON response I get from another page. Here's an example of the response: HTML: <p id="area" contenteditable> </p> <button class="bt ...

Is there a way to assign a sessionStorage key by clicking on certain elements in HTML?

I have encountered an issue while attempting to set a value in the sessionStorage. The problem lies in storing the sessionStorage "key" differently based on the item clicked. For instance, if I click on the first view chat, I should store a key of "1", and ...

Transform javascript classes into flash

Is there a way to transform a JavaScript class into Flash and implement it the same way as the original one? For example: var MyClass = function() { var exports = {}; var message = exports.message = function showMessage(msg) alert(msg); ...

Error icon appearing on Material UI's Stepper Component when not needed

I am currently using the Stepper component from Material UI and attempting to make the fill of a stepper that is in its error state appear red. If you need to see the Stepper component from Material UI's documentation, you can access it https://i.sst ...

The color of ngClass does not update according to the variable's value

When the value is true, I want to display a green text message and when it's false, I want it to be red. This is my angular app: In the controller, I declare a variable at the beginning and set it as true: $scope.IsColor = true; if (response.data.i ...

What is the best way to transmit a collection of JSON documents from the server?

Need help with vue.js code. It's not working as intended, any suggestions? Below is the code snippet: mounted(){ fetch('/', { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, ...

Adjusting the size of a dynamically generated rectangle using DrawingManager

I am currently working on a web application using Azure Maps along with the DrawingManager library. My goal is to allow users to save a drawn rectangle and potentially edit it by resizing later on. The strange thing is that while resizing rectangles works ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Using AJAX and jQuery, the result is retrieved and inserted into a <div> element

Having trouble populating a DIV with the result of a simple GET request using AJAX and jQuery. What could be causing the issue? <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <scrip ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Is Your Website Optimized for All Devices?

Creating this website was just a little project for me. I've been experimenting with different methods to ensure it's compatible with all devices and fits perfectly on each screen. Unfortunately, I'm pretty clueless when it comes to @media ...

Image is not showing up on the Carousel

I seem to have a problem with my carousel as the images are not showing up when the webpage initially loads. The issue arises in Dreamweaver where the JavaScript function only works after clicking on one of the arrow buttons. I believe that I might need to ...

There seems to be a problem with the output when trying to display the message "You said ${reply}"

In the following code snippet, vanilla.js is being used with ATOM as the text editor and running on nodejs via terminal: 'use strict'; const Readline = require('readline'); const rl = Readline.createInterface({ input:process.stdin, ...

What steps can you take to resolve the "TypeError: Cannot read property 'id' of undefined" issue?

I have been developing an app that involves using databases to add items for users based on their user ID, which is their username. However, whenever I attempt to add an item, I encounter an error that I can't seem to troubleshoot. The error message r ...

Creating a task list without using JavaScript in the web browser and without relying on a database

Looking for some guidance on building a todo app for a job interview where JavaScript is disabled in the browser and no database can be used. Any JavaScript needs to be handled on the server side. I have some basic knowledge of node/express and serving H ...