Enhance the appearance of your custom three.js Geometry by incorporating different textures

I have been struggling to implement UV-mapping on my custom geometry in three.js. Despite trying various solutions, none seem to be working. Can someone provide a clear explanation of how UV-mapping functions and the correct way to implement it?

var s = 100;
var MapHeight = function(x, y, mult){
    var map = new Array(x);
    for(var i = 0; i < x; i++){
        map[i] = new Array(y);
        for (var j = 0; j < y; j++) {
            map[i][j] = Math.sin((i*12+j)/10)*mult;
        }
    }
    return map;
};
var heightMap = MapHeight(s, s, 0.3);
var loader = new THREE.TextureLoader();
var sandTex = loader.load("Textures/sand.jpeg");
var div = 2;
var Sand = function(color){
    var geo = new THREE.Geometry();
    var i;
    for (i = 0; i < s; i++) {
        for (var j = 0; j < s; j++) {
            geo.vertices.push(new THREE.Vector3(i/div, heightMap[i][j], j/div));
        }
    }
    for (i = 0; i < (s)*(s-1); i++) {
        if (!Number.isInteger((i+1)/s)){
            geo.faces.push(new THREE.Face3(i, i+1, i+s+1));
            geo.faces.push(new THREE.Face3(i, i+s+1, i+s));
        }
    }
    geo.computeVertexNormals();
    geo.computeFaceNormals();
    geo.center();
    var mesh = new THREE.Mesh(
        geo,
        new THREE.MeshStandardMaterial({map: map})
    );
    return mesh;
};

My attempts to add UV-mapping to my geometry have resulted in either a black material or my program failing to run properly.

Answer №1

Make sure to add texture coordinates per face to the first layer UV layer.
Check out THREE.Geometry.faceVertexUvs

Initialize an array at the UV layer:

geo.faceVertexUvs[0] = [];

Then, add a set of three THREE.Vector2 for each triangle face:

geo.faceVertexUvs[0].push([
    new THREE.Vector2(u0, v1),
    new THREE.Vector2(u1, v1),
    new THREE.Vector2(u2, v2)
]);

Implement this in your code as shown below:

var geo = new THREE.Geometry();
var i;
var uv = [];
for (i = 0; i < s; i++) {
    for (var j = 0; j < s; j++) {
        geo.vertices.push(new THREE.Vector3(i/div, heightMap[i][j], j/div));
        uv.push(new THREE.Vector2((i-1)/s, (j-1)/s));
    }
}

geo.faceVertexUvs[0] = [];
for (i = 0; i < (s)*(s-1); i++) {
    if (!Number.isInteger((i+1)/s)){

        var vi = [i, i+1, i+s+1, i+s];

        geo.faces.push(new THREE.Face3(vi[0], vi[1], vi[2]));
        geo.faces.push(new THREE.Face3(vi[0], vi[2], vi[3]));

        geo.faceVertexUvs[0].push([ uv[vi[0]], uv[vi[1]], uv[vi[2]] ]);
        geo.faceVertexUvs[0].push([ uv[vi[0]], uv[vi[2]], uv[vi[3]] ]);
    }
}
geo.computeVertexNormals();
geo.computeFaceNormals();

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

Steps to retain localStorage data while redirecting to another external webpage

Encountering an issue with saving localStorage data across redirects. See the code snippet below: // Invoke newSitelogin(). Save response(credentials) in localStorage. Redirect to new URL. newSitelogin({ uuid, password }) .then(() => { window.ope ...

Is there a way to segment a string into words using a dictionary and finding the longest match in JS/Jquery?

Imagine you have a string like this: var str = "thisisinsane"; and a list of words from a dictionary such as: var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; How can we separate the words in str? In this specific case, there a ...

Refreshing a div using ajax technology

I am attempting to use Ajax to update an h3 element with the id data. The Ajax call is making a get request to fetch data from an API, but for some reason, the HTML content is not getting updated. This is how the JSON data looks: {ticker: "TEST", Price: 7 ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

Getting a JSON response from a JSP page through an AJAX request

I'm encountering an issue with a JSP page that is supposed to send a JSON response when requested through an AJAX call. However, the response is being directed to the error part of the AJAX call instead of the success part. Below is the code in my JS ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Animate the transition effect as soon as the block is displayed

Looking to create a smooth page transition using CSS changes with the help of Javascript (jQuery). Initially, one of the pages is set to display none. page1 = $('.page1'); page2 = $('.page2'); page1.removeClass('animate').cs ...

Is there a way to execute "npm run dev" within cPanel while I am currently working on a Laravel project?

Currently, I am working on a Laravel project and require to execute the following command in Cpanel terminal: npm run dev https://i.sstatic.net/bzxNj.png ...

Is it possible to utilize various providers in Next-Auth while still maintaining the same email address?

I am currently developing a Next.js application using NextAuth. At the moment, I have implemented login functionality with Google, credentials, and GitHub. However, I encountered an issue where if a user logs in with Google using the email "[email pro ...

Having trouble with the Post Request feature as an error message pops up saying "unable to post /addstudent/add"

I'm encountering an issue with the post request I'm trying to send. I've attempted to work on it both in Postman and with forms, but I keep getting an error that says "cannot POST /addstudent/add". Below you'll find the code snippets fo ...

Techniques, modules and functions in Javascript

How should I properly document this code snippet: // Define a collection of colors with methods colors = { // Define method for color red "red" : function() { // Do something... } // Define object for color black "black" : { // Add ...

Utilizing DRACOLoader alongside GLTFLoader within ReactJs

I have encountered a scenario where I am attempting to load a GLTF file that has been compressed using DRACO Compression. While I have successfully executed it using plain javascript, I am encountering challenges when trying to integrate the loader with Re ...

The CSS stylesheet is not being applied to the components in Next.js

I am currently facing an issue with styling my React/Next component. Despite trying to apply a stylesheet to enhance its appearance, the CSS doesn't seem to be taking effect. Could someone please provide guidance on how I can resolve this? I have att ...

Display the text from a function in an imported component using React

Attempting to break down HTML chunks into smaller pieces stored in the components folder. (Note: the HTML is actually written in JSX). The goal is to import the [Navigation] component and have it display its content. I am aware that there are tools avail ...

What methods can be used to determine if a webm file contains audio or video content?

In the process of creating an uploader using ReactJS, I encounter an issue related to identifying whether uploaded files are video or audio. Specifically, when users upload audio files with a .webm extension (e.g., music.webm) and the MIME type is set as & ...

Creating a JSON data array for Highcharts visualization: rearranging values for xAxis and columns

I am facing an issue with my column chart where JSON data is being parsed in the "normal" form: Years are displayed on the xAxis and values on the yAxis (check out the fiddle here): array( array( "name" => "Bangladesh", ...

Can a correctly typed text alter the image?

I am working on a feature where the image changes when the user enters the correct text, indicating that it was typed correctly. However, I am facing an issue where if the first two characters are entered correctly but the third one is not, the image still ...

Is it time to advance to the next input field when reaching the maxLength?

In my Vue form, I have designed a combined input field for entering a phone number for styling purposes. The issue I am facing is that the user needs to press the tab key to move to the next input field of the phone number. Is there a way to automaticall ...

Issue encountered with ngrok causing an unidentified error in node.js while executing a server script

Recently, I've been encountering an error while trying to execute a server script in node.js. The error message I keep receiving is quite perplexing. https://i.sstatic.net/DMMSj.png Upon further investigation, I discovered that the problematic piece ...