# Bézier curves

## Recommended Posts

Hey folks,

As I needed curves, I ran into some maths (thx wikipedia as my university years are far ago now) and, especially for you tonight, ladies and gentlemen, tandam !!!, here are quadratic and cubic Bézier curves :

http://www.babylonjs-playground.com/#1023O

(if you don't want to read the code, jump right to line 100 for function calls)

`quadraticBezier(vector3Origin, vector3Control, vector3Destination, segmentNumber) `

returns an array of segmentNumber Vector3 along a quadratic Bézier curve (amazing, isn't it ?) from the origin vector to the destination vector, curved by the control vector.

`cubicBezier(vector3Origin, vector3Control1, vector3Control2, vector3Destination, segmentNumber) `

does the same, but you give 2 control points here instead of only one.

Then you can easily use these arrays for drawing meshes or simple lines as I did with createLines, though I don't think it's the best way to do.

Hope it helps.

##### Share on other sites

Great job, Jerome!  I'm not very experienced with these things, but, this is pretty close to being a 3D "function plotter", isn't it?

Yum!  Thanks again for the knowledge and code!  You're a trailblazing son of a gun!  Fun stuff!  Well done!

For what it's worth, my heart, and I'm sure the hearts of many other forum users... goes out to our French friends.  I hope that tragic situation in France... can be resolved without anyone else getting hurt.

##### Share on other sites

wouaw is excellent. just:

new BABYLON.Vector3.Zero()

new BABYLON.Mesh.CreateLines()

new BABYLON.Mesh.CreatePlane()

These are static function does not need to 'new'

http://www.babylonjs-playground.com/#1023O#1

##### Share on other sites

@Wingutt : thanx for your support... in every domain

yep, it's this kind of function

I'll add soon lines thru control points in the example so everyone could understand

@dad72 : thanx for the fix, I'm not yet so familiar with BJS API and willing to make things maybe too fast

##### Share on other sites

Hey Jerome... I still have an unmet challenge (begging) that is available, should you want to try it.

http://www.html5gamedevs.com/topic/2571-the-wingnut-chronicles/page-14#entry32889

You seem to be a darned good plot-meister.  Please feel free to take-on the challenge of Spherical Harmonics... because the resulting mesh is just plain cool (not as cool as yours, but still cool).     The demo is in threeJS with the help of ToxiclibsJS, and maybe we don't have the necessary "face" functions in BJS... but... still, I dream and hope.

Everyone/Anyone... get spherical harmonics in BJS... and you'll have Wingy's undying hero worship.  It's all about the tiny 'sup' object.  Make a functionally equivalent BJS version, and we win!  Thanks, either way.

##### Share on other sites

arf, I no master at anything

just trying to retrieve some maths in the depths of my memory since my young years and using my poor coding skills to hack other's programs to understand how they did or fusing down my brain to get the point about wikipedia math definitions

mmmhh... your challenge is interesting, I'll give a look

an implementation seems to be here : http://paulbourke.net/geometry/sphericalh/

##### Share on other sites

No probleme Jerome.

And big thanks Wingnut for your compassion of our situation in France. Terrorists have been killed in the late afternoon.

##### Share on other sites

Thanks dad72.  It's all SO sad.  It knots my stomach, big time.

Jerome and anyone else...  http://urbanproductions.com/wingy/babylon/SphericalHarmonics/sh6.htm is an operational online demo (3js).  Read the post at the link I sent... tells just how very close we are.  Paul Bourke's website is linked-to in that demo, so we're all on the same page.  I love that generated mesh.  It's one of those "I can't stop pushing the generate button" things.  And I also love the tooty frooty colors.

What the hell, let's show the Sup (support) object right here.

`function Sup(scene) {	if(THREE === undefined){		throw new Error("THREE.js has not been loaded");	}	this.scene = scene;	this.objectDictionary = {};	this.f3 = function(geometry,i1,i2,i3, normal, index){		//unlike toxiclibs, a face in three.js are indices related to the vertices array		geometry.faces[index] = new THREE.Face3( i1,i2,i3, new THREE.Vector3( normal.x, normal.y, normal.z ) );	}	this.v3 = function(geometry,a, index){		var threeV = new THREE.Vector3(a.x,a.y,a.z);		geometry.vertices[index] = threeV;	}	this.createLineGeometry = function(line3d){		var geometry = new THREE.Geometry();		sup.v3(geometry,line3d.a, 0);		sup.v3(geometry,line3d.b, 1);		geometry.computeCentroids();		geometry.computeVertexNormals();		return geometry;	}	// create a THREE.Geometry with matching vertices to your triangleMesh	// @param {toxi.geom.mesh.TriangleMesh} triangleMesh the toxiclibs.js triangle mesh to convert	// @param {THREE.Geometry} [geometry] optional geometry to pass in if you would prefer to update	// a geometry instead of create a new one	// @returns {THREE.Geometry}	this.createMeshGeometry = function(triangleMesh, geometry){		geometry = geometry || new THREE.Geometry();		var addFace = function(f, faceIndex){			var vectors = [f.a,f.b,f.c],				startIndex = geometry.vertices.length;			//make sure this wasnt a vertices from a previous face			var	i = 0,				len = 3;			for(i=0;i<len;i++){				var toxiV = vectors[i];				sup.v3(geometry,toxiV, startIndex+i);			}			var normal = f.normal.copy();			normal.y *= -1;			sup.f3(geometry,startIndex,startIndex+1,startIndex+2, normal, faceIndex);		};		for(var j=0,flen=triangleMesh.faces.length;j<flen;j++){			addFace(triangleMesh.faces[j], j);		}		geometry.computeCentroids();    	//using toxiclibsjs normals		//geometry.computeFaceNormals();		geometry.computeVertexNormals();		return geometry;	}	this.createMesh = function(triangleMesh,material){		if(material === undefined){			material = new THREE.MeshBasicMaterial();		}		var geometry = sup.createMeshGeometry(triangleMesh);		return new THREE.Mesh(geometry,material);	}	this.createParticle = function(position, materials){		var particle = new THREE.Particle(materials);		particle.position.x = position.x;		particle.position.y = position.y;		particle.position.z = position.z;		return particle;	}	this.prototype = {		addLine: function(line3d, material){			if(material === undefined){				material = new THREE.LineBasicMaterial();			}			var geom = sup.createLineGeometry(line3d);			var line = new THREE.Line(geom,material);			this.scene.add(line);			return line;		},		// add a toxiclibs.js mesh to the three.js scene		// @param {Object|toxi.geom.mesh.TriangleMesh} obj_or_mesh either an options object or		// the toxiclibsjs mesh		// @param {toxi.geom.mesh.Trianglemesh} [obj_or_mesh.geometry] the mesh in the options object		// @param {THREE.Material} [obj_or_mesh.material] the three.js material for the mesh		// @param {boolean} [obj_or_mesh.holdInDictionary] should ToxiclibsSupport hold a reference?		// @param {THREE.Material} [threeMaterials] the three.js material for the mesh		addMesh: function(obj_or_mesh,threeMaterials){			var toxiTriangleMesh;			if(arguments.length == 1){ //it needs to be a param object				toxiTriangleMesh = obj_or_mesh.geometry;				threeMaterials = obj_or_mesh.materials;				holdInDictionary = obj_or_mesh.holdInDictionary;			} else {				toxiTriangleMesh = obj_or_mesh;			}			var threeMesh = this.createMesh(toxiTriangleMesh,threeMaterials);			this.scene.add(threeMesh);			return threeMesh;		},		addParticles: function(positions, material){			if(material === undefined){				material = new THREE.ParticleBasicMaterial();			}			positions =  Array.isArray( positions ) ? positions : [ positions ];			var particle = new THREE.Geometry();			for(var i=0,len = positions.length;i<len;i++){				sup.v3(particle,positions[i]);			}			var particleSystem = new THREE.ParticleSystem(particle,material);			sup.scene.add(particleSystem);			return particle;		},		createMeshGeometry: function(triangleMesh){			return sup.createMeshGeometry(triangleMesh);		},		createMesh: function(triangleMesh,material){			return sup.createMesh(triangleMesh,material);		}	}}`

It's not a very big object.  I created/stole this object... by removing all the ThreeJS support from the ToxicLibs framework, and putting it all on this object.  In other words, these are the ThreeJS interface functions needed to render the ToxicLibs-built mesh... in ThreeJS.  This is why I say that if we (anyone) can make a Sup object for BJS (same functionality), then we have success.  In fact, I think the particle part of it... is only used to make a few background stars... which I turned off in the above demo.

I don't know how much ToxicLibs functionality is needed in the end.  It's a heavy duty utils package that is WAY over my head.  Of course I would love to reduce external dependencies to a minimum, but I just want to use spherical harmonics objects in my BJS scenes and games.  They are fascinating and fun to browse/fly.  To be frank, spherical harmonics mesh are the most gorgeous math-generated objects I have ever seen.  droooooooool.

Anyway, sorry for the tangent... let's get back to yacking about Jerome's cool Bezier plots.

##### Share on other sites

If I understand well, you are trying to port this very imbricated threejs-toxiclibs object to bjs with no dependency at all. And the rendering seems hard to achieve.

I think I'll give a try to do it... but starting from scratch, from the math equation only.

Because it's quite difficult to migrate with so many different libs and approaches imho.

I'll give a try, yes. I like this challenge :-)

But I need to learn some Typescript/gulp before, if it's intended to be pushed into the framework (is it ? harmonics and tutty frutty colors are so beautiful, but are they useful ? same question for torus knot : it's a must show for a framework to present a torus knot, but who does use it really ? don't know) and go on watching the huge endless DK/Davrous video tutorial, and maybe simply do my pro job too

Arrrg... so many things to do and learn and so little time !

and BTW, are you the running guy : http://urbanproductions.com/aboutus.html ?

##### Share on other sites

Hi jerome,

Brilliant!  You've touched upon a key process for understanding motion by plotting patterns.  There is a pinned thread in the babylonjs forum that deals with dimensional space and the the understanding and mathematical manipulation thereof.  It is named created by gwenael.  I would love to see you post any further thoughts on plotting motion here, as it is a topic that I believe should be kept alive.

You have touched on a key method to understanding motion, and a major method to manipulating matrices' mathematically.  There are several common mathematical processes that developers use to plot deltas in matrices' which are used by graphic artists world wide.  In plotting animations (deltas in vector matrices',) it is far more comprehensive for practically anyone to understand the behavior of an an "animated" object when it is graphically plotted.  Once this is understood, then anyone with basic algebra skills can manipulate the animation to whatever they might imagine with fairly simple math.

​It took me considerable time to learn this as an animator, as I once thought that the best animation could come only from my mind and studied animation skills.  But these days, most of my animation comes from writing mathematical algorithms driving pixels, voxels,and graphic objects with matrices' driving their pitch, roll, and yaw.  Please post on the Spaces forum, and I look forward to your discoveries and input on this vital subject.

Cheers,

Dbawel

##### Share on other sites

Thanks dbawel :-)

Did I do really what you said ?

So I'll post now on : Spaces (world, parent, pivot, local)

First I've to read (and understand) your very accurate posts about Euler angles too. A big trip back into my distant young years !

arg, so many things to (re-)learn and so little time again !

As I work in a university institute, I always can ask some math profs when I feel stuck in some equation, eerf.

I use 3D rotation matrices for generating terminal graph node positions (computed server-side in ruby language from the previous vector) in my network weathermap project (still porting from threejs to babylonjs) : http://logiciels.iut-rodez.fr/proto/weathermap/

##### Share on other sites

Jerome, that's a friend, Bob.    He lets me use his domain to store some demos.  (thanks bob!)

Another fun math area that fascinates me... is Fibonacci numbers, and in particular, how often Fibonacci numbers appear in nature.  So much so, that I suspect Fibonacci numbers MIGHT be the key to the secret of life itself.  I have done some light studying of Fibonacci and heterodyning in musical harmonies, and it is my far-fetched theory that plants actually hear a "harmony" that humans cannot, and so they produce Fibonacci things such as pine cones, and grow their leafs with Golden Mean patterns.

I'm quite sure Fibonacci numbers (the Golden Mean) can produce mesh/plots (such as conch shells) just as beautiful as Spherical Harmonics.  Drooooooool.

And yes, I agree that certain advanced shapes/primitives could possibly be outside of the purpose of a webGL framework.  But don't let that worry you one bit.    Our "Tools" area is begging for an Advanced Shapes library (ie. a BABYLON.AdvancedVertexData object).  I have heard BJS authors/admin mention more than once... that they are interested in expanding our repository of geometry.  Our framework authors are very accommodating, and I can guarantee that any advancement that users can make in that direction... will not be wasted or lost.  I will personally see to it's safety and long-life, even if I have to store our new advanced vertexData object under my bed in a tin can.

By the way, there is good merit in Dbawel's comments about the pinned thread, but that can be covered just by making a link to THIS thread... in THAT thread.  Jerome, you feel free to talk about your projects... in any place you wish.  We have it all "pinned" whether it is officially pinned or not.  We have a great forum search and Google is tracking every post we make, here.  We'll find your words and demos, pinned or not.

##### Share on other sites

Fibbonacci spirals are so beautiful ! I like nautilus shells.

I'll try to implement too such a shell-like tube as soon as I can... just for fun and for the beauty of the shape.

My thought about the utility of this or this mesh in the framework was just regarding its weight and efficiency. DK focusses on performances.

That's said, even useless (and not bjs included ) function should be coded imho (in the playground ?), just for its beauty and the pleasure of art. :-)

Misunderstanding about the pinned thread : I meant I was honoured by DBawel's invitation but I needed to read his very documented post about 3D geometry before  I feel able to smartly contribuate at his level.

Maths  and 3D geometry are far ago to me :-p

##### Share on other sites

WOW! Fibonacci! This just got interesting!

You just dove straight into the depths of fundamental mathematical concepts.  I'm not necessarily sold on the golden number as the key to unified theory, however, Fibonacci has given ground to fractals and other math in nature.  For anyone who is reading this thinking "What the hell are they talking about?," the link that Wingnut posted above is a pretty good explanation of the Golden number and how it directly explains math in nature.

And Jerome (Bob?), it is clear that you retain skills above my pay grade.

Why does this matter?  Try and create a pine cone in any 3D graphic application.  And in practical use for the BabylonJS community, this is extremely useful for generating particles as well as voxels.

I like where this is going.

Cheers,

Dbawel

##### Share on other sites

I made a port of your cubic  bezier function to Path class (part of my project to add triangulation and path animation in babylonjs)

`var polygon =  BABYLON.Polygon.StartingAt(-10, -10)    .addLineTo(10, -10)    .addLineTo(10, -5)    .addCubicBezierTo(0, 0, 0, 7, 10, 5)    .addLineTo(10, 10)    .addLineTo(5, 10)    .addLineTo(-10, 10)    .close();            var ground = new BABYLON.PolygonMeshBuilder("ground1", polygon, this.scene)    .build();var groundMaterial = new BABYLON.StandardMaterial("groundMaterial", this.scene);groundMaterial.wireframe = true;ground.material = groundMaterial;`

for while it's just on my "side project" (https://github.com/ElemarJR/BABYLON.Triangulation). Soon, I will create a PR to BJS.

##### Share on other sites

waaaowww

you're THE triangulation man !

##### Share on other sites

@Dbawel - "Bob" was the guy in the picture that Jerome asked me about.  (The guy running from the train.)  I'm pretty sure Jerome's real name is Jerome.

http://jerome.bousquie.fr/  -  I think that is our Jerome, right there.  He is possibly a Ruthénois, and the area he lives-in is pretty cool, and really old.  He is going to fly-in a bunch of us... to tour that area of France, and he's going to take care of all costs.  What a guy!

But back on subject... hey ElemarJR... excellent triangulation (whatever the hell THAT is).  You math folk are just THE COOLEST.  Let's see some more stuff you guys are doing.  Dbawel is a Hollywood animation god, ya know?  Impress him, and maybe you'll land in California.  Ever seen the girls out there?  phew.  Oh yeah, stay on subject, Wingy.

##### Share on other sites

touched me :-)  (oops, this old web site needs some debugging... space key to emit clouds, cursor keys to fly)

and ElemarJR, you are THE guy !

##### Share on other sites

added the control points so people can better understand bezier curves

http://www.babylonjs-playground.com/#1023O#3

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.