Step-by-step guide to making a personalized mesh in Babylon.js

Currently, I am utilizing the Babylonjs 3D WebGL library and finding it to be a fantastic tool. However, I am facing a challenge in replicating a feature that exists in the THREE.JS library.

My scenario involves 2D polygons stored in a database. I retrieve the polygon data and proceed to create a customized mesh by extruding it.

When working with THREE.JS, the process is quite straightforward. I can simply add points to an array:

...
points.push( new THREE.Vector2( part.x, -part.y ) );
...
var shape = new THREE.Shape( points );
var extrusion = {
    amount: building.height,
    bevelEnabled: false
};
var geometry = new THREE.ExtrudeGeometry( shape, extrusion );
var mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial({
    ambient: 0xbbbbb,
    color: 0xff0000
});
...
scene.add( mesh );

Recreating this in BabylonJS has proven to be a challenge. I have come across some helpful information, though:

One example I found (from the MSDN link) demonstrates creating a mesh from vertices and faces:

var plane = new BABYLON.Mesh(name, scene);

 var indices = [];
 var positions = [];
 var normals = [];
 var uvs = [];

 // Vertices
 var halfSize = size / 2.0;
 positions.push(-halfSize, -halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(0.0, 0.0);

 positions.push(halfSize, -halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(1.0, 0.0);

 positions.push(halfSize, halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(1.0, 1.0);

 positions.push(-halfSize, halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(0.0, 1.0);

 // Indices
 indices.push(0);
 indices.push(1);
 indices.push(2);

 indices.push(0);
 indices.push(2);
 indices.push(3);

 plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind);
 plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind);
 plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind);
 plane.setIndices(indices);

 return plane;

Although this method works, it involves manually calculating the index buffer, which is not required in THREE.JS. Furthermore, the sample provided deals with a plane and does not address extrusion specifically.

My quest now is to explore if there are simpler ways in BabylonJS to achieve the same functionality effortlessly.

Answer №1

While there is currently no support for extrusion, it is a feature that could bring great value. Rest assured, I will add it to our roadmap for consideration. If you would like to delve deeper into this topic, feel free to inquire on the babylon.js forum.

EDIT:

You now have the ability to create custom shapes.

Answer №2

Experience the Latest Update in 2019 with PolygonMeshBuilder for Custom Mesh Creation

It's important to note that the PolygonMeshBuilder utilizes Earcut. Therefore, when working on projects outside of the playground, you'll need to include a reference to their CDN or download their npm package.

Include Earcut as a dependency in your index HTML

<script src="https://preview.babylonjs.com/earcut.min.js"></script>

Now, you have the ability to create custom meshes by extruding polygons and adding holes.

//Define Polygon shape in XoZ plane
var shape = [ 
                new BABYLON.Vector3(4, 0, -4), 
                new BABYLON.Vector3(2, 0, 0), 
                new BABYLON.Vector3(5, 0, 2), 
                new BABYLON.Vector3(1, 0, 2), 
                new BABYLON.Vector3(-5, 0, 5), 
                new BABYLON.Vector3(-3, 0, 1), 
                new BABYLON.Vector3(-4, 0, -4), 
                new BABYLON.Vector3(-2, 0, -3), 
                new BABYLON.Vector3(2, 0, -3)
          ];

//Define Holes in XoZ plane
var holes = [];
    holes[0] = [ new BABYLON.Vector3(1, 0, -1),
             new BABYLON.Vector3(1.5, 0, 0),
             new BABYLON.Vector3(1.4, 0, 1),
             new BABYLON.Vector3(0.5, 0, 1.5)
           ];
    holes[1] = [ new BABYLON.Vector3(0, 0, -2),
             new BABYLON.Vector3(0.5, 0, -1),
             new BABYLON.Vector3(0.4, 0, 0),
             new BABYLON.Vector3(-1.5, 0, 0.5)
           ];

var polygon = BABYLON.MeshBuilder.ExtrudePolygon("polygon",{  
  shape:shape, 
  holes:holes,
  depth: 2, 
  sideOrientation: BABYLON.Mesh.DOUBLESIDE }, scene);

Outcome:

For a visual reference, check out this playground:

Advanced Application

Explore creating staircases:

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 method for implementing a file upload feature using jQuery and php?

Could someone explain how to create a jQuery multiple image upload feature (uploading without refreshing the page after choosing a file, only displaying the image but not inserting it into a database), and submit additional form data along with all images ...

What is the best way to retrieve a particular field from a Firestore Document using JavaScript?

Within my Firestore database, I have a structure of users that looks like this: https://i.sstatic.net/jgeCq.png The rules set up for this database are as follows: match /users/{userID} { match /public { allow read: if request.auth != nu ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Styled-components causing issues with conditional rendering

Within my React component, I have multiple properties and I want styles to only apply if a property has a value. I attempted the following code: export const Text = ({text, color, size, fontFamily}) => { const StyledParagraph = styled.p` m ...

Utilize JavaScript declarations on dynamically added strings during Ajax loading

Is there a way to append HTML strings to the page while ensuring that JavaScript functions and definitions are applied correctly? I have encountered a confusing issue where I have multiple HTML elements that need to be interpreted by JavaScript. Take, for ...

Populate a Dropdown Menu with Directory Content for User Selection of d3.js JSON Data

I have a d3 forced-directed graph that is currently using a static JSON file for data: d3.json("../Data/sample.json", function(error, graph) { //do stuff }); However, I would like to give the user the ability to select the data file from a drop-down ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Update the gulp watch function to use gulp@4

We are currently in the process of transitioning from <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb9c8e978bbbc8d5c2d5ca">[email protected]</a> to gulp@4, and encountering difficulties during the switch. Upon r ...

Tinymce editor does not display icons as expected

I am attempting to create a custom styled list that is editable with tinymce. The list-items are using Material-Check-Icons as bullet-points, which are added as css-pseudo-elements ::before. This setup works well, but when I integrate tinymce (v5) into the ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

What is the best way to sort a table by column index using HTML?

I find myself in a situation where I am not well-versed in HTML, Javascript, and CSS. Here is the scenario: <div class="table"> <table class="display-table"> <thead> <tr> ...

I'm baffled on how to find access to ParametricGeometry within Three.js

I've been looking into how to access ParametricGeometry because I keep encountering this message when I attempt to use it: "THREE.ParametricGeometry has been relocated to /examples/jsm/geometries/ParametricGeometry.js" Any ideas on how to do this wou ...

Issues with importing files have been reported on Node.js version 11.8.0

I'm currently working on a program that utilizes a large object filled with dictionary words. I've decided to import this object from a separate file due to its size, but I encountered an error stating that Node.js doesn't recognize the obje ...

How do I overwrite this calculation using JQuery?

I have a website: link There are two pages on my site that have the same div elements... I want one page to perform a certain calculation on the divs, and another page to perform a different calculation... New JavaScript Code: jQuery(document).ready(fu ...

Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment. My main goal is to execute everything from IIS Express. However, I'm encou ...

The AJAX response is not functioning as expected

I've encountered an issue with my AJAX code for an online food store. Every time I run it, a pop-up message saying something went wrong appears instead of the expected output. I suspect there might be an error in either the connection handlers or the ...

When attempting to utilize VueJs v-bind:type on an input element, it appears to be ineffective when the type property name is

Code: <!DOCTYPE html> <html> <head> <title>Creating a Vue app</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3046455570021e061e0100">[ ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

Generate a unique identifier for the HTML content

Is there a more efficient way to assign unique id tags to certain words using vanilla javascript? For example: <p>All the king's horses ran away.</p> For instance, "All" would have the id "term1", "King's" would have "term2", and ...

Tips for looping through each cell in a column of a DataTable to verify its content

I have a table generated using the jquery DataTables API. One of the columns displays word frequencies for each word in the table. If a frequency is less than 40, I want to change that cell to display "unranked" instead of the actual number. How can I ite ...