BufferGeometry is not being displayed

After working extensively with BufferGeometry, I considered myself quite familiar with it. However, I am currently facing an issue while trying to create a simple square plane - there is no visible plane, no errors, and everything seems to be set up correctly. Despite researching similar posts, none of the suggested solutions have worked for me so far.

Upon inspecting the scene, I can see that the mesh exists, has the correct material, and the geometry is properly defined. Yet, all I get is a black viewport. There must be a basic step that I am overlooking but I just can't seem to figure it out. What could I be doing wrong?

Fiddle + code: http://jsfiddle.net/TheJim01/kafybhge/34/

// BufferGeometry Tester

var hostDiv, scene, renderer, camera, root, controls, light;

var WIDTH = 500;//window.innerWidth,
    HEIGHT = 500;//window.innerHeight,
    FOV = 35,
    NEAR = 1,
    FAR = 1000;

function createBufferGeometryMesh(){
    var geo = new THREE.BufferGeometry();

    var vertices = 
        [
            -10.,  10., 0., // 0 - top left
             10.,  10., 0., // 1 - top right
             10., -10., 0., // 2 - bottom right
            -10., -10., 0.  // 3 - bottom left
        ],
    normals =
        [
            0., 0., 1.,
            0., 0., 1.,
            0., 0., 1.,
            0., 0., 1.
        ],
    indices = [ 0, 1, 2, 0, 2, 3 ];

    geo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
    geo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
    geo.addAttribute( 'index', new THREE.BufferAttribute( new Uint32Array( indices ), 1 ) );

    var mat = new THREE.MeshPhongMaterial( {
                    color: 0xffffff,
                    ambient: 0xffffff,
                    specular: 0xffffff,
                    shininess: 50,
                    side: THREE.DoubleSide
                } );

    var msh = new THREE.Mesh(geo, mat);

    return msh;
}

function init() {
    hostDiv = document.createElement('div');
    document.body.appendChild(hostDiv);

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(WIDTH, HEIGHT);
    hostDiv.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(FOV, WIDTH / HEIGHT, NEAR, FAR);
    camera.position.z = 50;

    controls = new THREE.TrackballControls(camera, renderer.domElement);

    light = new THREE.PointLight(0xffffff, 1, 1000);
    light.position.copy(camera.position);

    scene = new THREE.Scene();
    scene.add(camera);
    scene.add(light);

    var square = createBufferGeometryMesh();
    scene.add(square);

    animate();
}

function render() {
    renderer.render(scene, camera);
}

function animate() {
    light.position.copy(camera.position);    

    requestAnimationFrame(animate);
    render();
    controls.update();
}

init();

Despite this current challenge, here's a previous example of my work using BufferGeometry. This code functions correctly when substituted in place of the createBufferGeometryMesh() above. I have experimented with defining the buffers explicitly, but unfortunately, it hasn't made any difference.

function colorCube(scale){
    scale = scale || 1;
    var geo = new THREE.BufferGeometry();

    // Definition of cube faces ... (code continues)
}

Answer №1

After realizing my mistakes, it became clear that my misunderstanding of how normals function in relation to drawing faces was the root issue in my code.

I had incorrectly assumed that vertex normals determined the direction of a face, when in reality they are only used for lighting calculations on the surface. The direction of a face is actually defined by the order of the vertices (face normal). Additionally, I had been using the left-hand system instead of the right-hand system that three.js utilizes.

In my initial code snippet, I wrote:

indices = [ 0, 1, 2, 0, 2, 3 ];

To correct the orientation of the faces, the code should have been:

indices = [ 0, 2, 1, 0, 3, 2 ];

Though the differences may seem subtle, they were crucial in ensuring that the face normals pointed in the correct directions (-Z vs. +Z). By fixing the indexing based on the right-hand system, the faces were now properly oriented to receive light.

To further solidify my understanding, I conducted an experiment where I reversed the vertex normals to oppose the face normals. As expected, this resulted in the square appearing black as the lighting was reflected inward, creating a dark effect.

The key lesson learned from this experience is that face direction (face normal) is determined by the vertex order and should follow the right-hand system, while vertex normals impact the lighting on the surface independently of defining face direction.

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

How can I use ngx-editor to insert an HTML block at the current cursor position by clicking a button?

I am currently using ngx-editor within Angular 7. My goal is to insert HTML at the cursor's position upon clicking on parameters from a list. The current view displays how the parameter is appended when clicked, as shown in the image attached https:// ...

Design a dynamic top navigation bar in Angular or any other framework that automatically adjusts to the size of the screen, similar to the responsive bookmarks bar in

Could you offer guidance or suggestions on how to design a navigation bar (using Angular 1, jQuery, CSS, etc) that emulates the functionality of Google Chrome bookmarks bar when resizing the page? Essentially, as the page size decreases, a new button/symbo ...

Dynamic drop-down navigation with rearranging menu

I am attempting to design a drop-down navigation bar with 2 rows. Initially, only 1 row is visible. Upon clicking the visible row, both rows should appear. Subsequently, when one of the 2 rows is clicked, only that specific row should be displayed. Below a ...

Sorting in reverse order within a table

Is there a way to reverse the order in which my function renders table rows with incremental id? (first row with id=n, last with 1) Here is the code snippet I am using: renderRows = () => { const { receipts } = this.props const reversedReceipt ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

Using HTML5 and an ASP.NET web method to allow for file uploads

My attempt to upload a file to the server using an HTML5 input control with type="file" is not working as expected. Below is the client-side JavaScript code I am using: var fd = new FormData(); fd.append("fileToUpload", document.getElementById(&ap ...

`Formatting Dates with Google Script`

I am looking to modify the date format from "mmm-dd-yyyy" (Nov-11-2019) using my existing code. Here is the code snippet: var timeStamp = data[i][timeStampappr]; var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + &ap ...

Permanently dismiss Bootstrap 4 alert using a cookie

Recently, I came across a bootstrap 4 alert that I found quite useful. Here is the code snippet for it: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <button type="button" class="clo ...

Updating $scope in AngularJS works in JavaScript, but the changes are not reflected in the HTML

After making a request to the server and receiving a correct response, I have an array of objects called $scope.photos. However, when attempting to add a new photo by sending a request and then trying two different methods to update the $scope in the HTML, ...

Implementing raw static HTML files in webpack: a step-by-step guide

Recently, I created a basic template called test.html <div>raw text with content</div> All I'm trying to achieve is to import the raw file without any alterations For example: require('./test.html'); // This should return "&l ...

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

The selected option in Bootstrap is displayed twice in the Bootstrap modal

I am facing an issue with Bootstrap Select-box showing multiple times in a bootstrap modal wizard. I have tried various solutions from Stack Overflow but none of them seem to work. A screenshot of the problem can be seen below: https://i.sstatic.net/glp3E ...

Looking to add a dropdown feature to my current main navigation bar

I've been struggling to add a drop-down menu to my website's main menu. Every time I try, something goes wrong - sometimes the menu appears inline, other times it completely messes up the layout. Here is the HTML code snippet: <ul class="m ...

I encountered an error while trying to load the resource from http://premieroptie.nl/wp-content/themes/theme51771/favicon.ico: net::ERR_NAME_NOT_RESOLVED

Upon opening my website URL, computertechnet.nl, I noticed an error when inspecting and checking the console tab. The specific error message is: Failed to load resource: net::ERR_NAME_NOT_RESOLVED for . In addition, a second warning was displayed: G ...

Optimizing HTML and Script loading sequences for efficient execution

I have a query regarding the loading order of scripts in web browsers. I am interested in knowing the most efficient way to redirect users to a mobile website on the client side. For example, if I place a mobile detection script within the <head> se ...

Having trouble with Grunt and Autoprefixer integration not functioning properly

Joining a non-profit open source project, I wanted to contribute by helping out, but I'm struggling with Grunt configuration. Despite my research, I can't seem to figure out why it's not working. I am trying to integrate a plugin that allow ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

tips for transitioning between various json entities

Recently, I created a login page code using JavaScript that runs on a Node Express.js server. Users can input their username/email and password, and all the data gets stored in a JSON file structured like this: {"username":"admin"," ...

Encountering a 404 Error on all routes except the home page when working with the Express Application Generator

While working on developing a day planner, I encountered an issue with the routes. I am consistently receiving a 404 error for any route other than the main Home page route (index or "/"). Below is the content of the app.js file: var express = require(&ap ...