Fix surface orientations on potentially corrupted .stl files

I am facing a challenge in Three.js where I need to fix the normals on files that are coming in with potential issues. It's unclear whether the problem lies in the scanning process or during the file uploads. While we are investigating the upload function, I am also looking for ways to repair these bad normals. Any suggestions or tips on how to rectify the file or determine the correct normals would be greatly appreciated.

Below is the code snippet where we extract the normals and our method for doing so. Please note that the code functions properly in general, but encounters issues specifically when dealing with bad normals. I have also linked one of the problematic files for reference: Get File here

We are utilizing VTK with C++ on the backend, so any solution or suggestion involving either of these technologies would be valuable.

my.geometry = geometry;

    var front = new THREE.MeshPhongMaterial(
    {color: 0xe2e4dc, shininess: 50, side: THREE.DoubleSide});

var mesh = [new THREE.Mesh(geometry, front)];

my.scene.add(mesh[0]);
my.objects.push(mesh[0]);

var rc = new THREE.Raycaster();

var modelData = {'objects': [mesh[0].id], 'id': mesh[0].id};

var normalFound = false;
for (var dy = 80; dy >= -80; dy = dy - 10) {
  console.log('finding a normal on', 0, dy, -200);
  rc.set(new THREE.Vector3(0, dy, -200), new THREE.Vector3(0, 0, 1));

  var hit = rc.intersectObjects([mesh[0]]);

  if (hit.length) {
    my.normal = hit[0].face.normal.normalize();
    console.log('normal', my.normal.z);

    modelData['normal'] = my.normal;

    if ((my.normal.z > 0.9 && my.normal.z < 1.1)) {
      my.requireOrienteering = true;
      modelData['arch'] = 'lower';
      normalFound = true;
      console.log('we have a lower arch');
    } else if ((my.normal.z < -0.9 && my.normal.z > -1.1)) {
      modelData['arch'] = 'upper';
      normalFound = true;
      console.log('we have an upper arch');
      }

    break;
  }
}

Answer №1

To determine the normals, one simply needs to calculate the cross product of two given vectors in geometry. This results in a vector that is perpendicular to the original input vectors. The next step involves normalizing this vector to ensure accurate lighting calculations.

When dealing with smooth surfaces, it's necessary to compute all normals at a specific point and then average them out. On the other hand, flat surfaces will have multiple normals at each vertex, with one for each surface.

For quads, the pseudo code would appear as follows:

foreach quad : mesh
foreach vertex : quad
    vector1 = neighborVertex.pos - vertex.pos;
    vector2 = otherNeighborVertex.pos - vertex.pos;
    vertex.normal = normalize(cross(vector1, vector2));
end foreach;
end foreach;

Answer №2

When working with VTK, make sure to utilize the filter known as vtkPolyDataNormals to calculate the normals in your file. Before running this filter, it is advisable to enable ConsistencyOn(), NonManifoldTraversalOn(), and AutoOrientNormalsOn().

If point-normals are preferred over per-cell normals and your geometry includes sharp corners, remember to specify a feature angle using SetFeatureAngle() and activate SplittingOn().

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

What is the best way to retrieve the number of clients in a room using socket.io?

I am using socket.io version 1.3.5 My objective is to retrieve the number of clients in a specific room. This is the code implementation I have: socket.on('create or join', function (numClients, room) { socket.join(room); }); ...

What could be the reason for the absence of {{ list.title }} on display

I'm currently learning how to develop my first MEAN stack app by following a tutorial on YouTube. However, I've encountered an issue where the title of the list is not displaying correctly. I'm using Insomnia to create the lists. Here's ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

What is the best way to send a function or callback to a child process in Node.js?

In this scenario, imagine having a parent.js file with a method called parent var childProcess = require('child_process'); var options = { someData: {a:1, b:2, c:3}, asyncFn: function (data, callback) { /*do other async stuff here*/ } } ...

ng-if is executed prior to the specified time

This unique Soundcloud player was created using Plangular, a directive that utilizes AngularJS and the Soundcloud API. Due to certain restrictions with third party apps not being able to stream some Soundcloud tracks, I have implemented ng-if="track" and n ...

Error in AngularJS - filterProvider not recognized

When the two script statements below are combined, they cause an error: "Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter." Can someone explain why this happens? 1st segment Find Person: <input type="text" ng-m ...

What is the best way to store my JSON output in a JavaScript variable?

In my jsonOutput.php page, the code looks like this: $response['imgsrc'] = $filename[1]; echo json_encode($response); When executed, it produces a JSON output like {"imgsrc":"071112164139.jpg"} My query now is, how can I make use of ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

What is the best way to extract a certain property from a JSON string using JavaScript?

Can you guide me on how to extract the value of agent_code from this string using JavaScript? Additionally, could you please provide an explanation of the underlying logic? Abridged JSON Data: [{"name":"NYC","zone_id":"1","totalagents":"40","agents":[{ ...

Techniques for transferring form data from JavaScript to Java

Currently in my application, I have a signup form and I am facing an issue with storing the data in the backend. Since I am not well-versed in the backend development, I am struggling with this task. I'm using Netbeans 7.0 as my IDE and MySQL 5.6 for ...

Stop input elements from receiving focus when the dialog is displayed on the webpage

I successfully integrated a dialog in my html code. My current goal is to: Within my dialog, there is a form with various form elements. Additionally, there is another form on the main page located underneath the dialog. Currently, when I press the tab ...

Tips for accessing information from different sources within Vue 3

In my Vue 3 setup() method, I have an array [] stored as a constant. This array consists of X objects and represents the responses of a form. My goal is to showcase each object on a single dynamic page within our internal dashboard by using v-for in the t ...

Tips for triggering the API call only when a change is detected

#In the provided code snippet, the useEffect hook is being used to fetch data from an API using the apiData() function. The data retrieved consists of objects with properties such as id, name, parent name, and isActive. The isActive property is linked to ...

Prevent postback in case of validation error

In my current setup, I have a textbox control with the following specifications: <asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]" On ...

Checkbox remains selected even after navigating back

I am currently working on a code that involves using checkboxes. When I click on them, the checkbox value is appended to the URL with a hash. However, when I go back or press the back button, the URL changes but the checkboxes remain checked. Below is the ...

computational method for organizing balls in a circular formation

I need help arranging 10 spheres in a ring using code. So far, this is what I have, but it's not working as expected. const sphereGeometry = new THREE.SphereGeometry(300, 20, 20); const sphereMaterial = new THREE.MeshLambertM ...

Utilizing Mootools to Access and Obtain the Current Query String Parameters

Is there a way to extract the current querystring values using mootools? I have implemented mootools ajax for php pagination. The initial call includes the following parameters: format=html&nolayout=true&p[0]=1000-1500&p[1]=1500-2000&p[2] ...

Obtain the HTTP status code in Node.js

Currently, I am looking to retrieve the HTTP status code of a URL that is passed to a function. Up to this point, I have been using the request module for this purpose. The challenge I've encountered is that the request module fetches all the content ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

The resize() function in jQuery triggers a stack overflow exception

I am trying to manage the resizing of a div on my website, but I am encountering a stackoverflow exception when using the resize function. Can someone please help me understand what I am doing wrong? For reference, here is a jsfiddle example: https://jsfi ...