Path.js 13.8 KB
Newer Older
M
Mr.doob 已提交
1 2
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
M
Mr.doob 已提交
3 4
 * Creates free form 2d path using series of points, lines or curves.
 *
M
Mr.doob 已提交
5 6 7 8 9
 **/

THREE.Path = function ( points ) {

	this.actions = [];
M
Mr.doob 已提交
10
	this.curves = [];
M
Mr.doob 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23

	if ( points ) {

		this.fromPoints( points );

	}

};

THREE.PathActions = {

	MOVE_TO: 'moveTo',
	LINE_TO: 'lineTo',
M
Mr.doob 已提交
24 25 26 27
	QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
	BEZIER_CURVE_TO: 'bezierCurveTo', 		// Bezier cubic curve
	CSPLINE_THRU: 'splineThru',				// Catmull-rom spline
	ARC: 'arc'								// Circle
M
Mr.doob 已提交
28 29 30

};

M
Mr.doob 已提交
31
// TODO Clean up PATH API
M
Mr.doob 已提交
32

M
Mr.doob 已提交
33 34
// Create path using straight lines to connect all points
// - vectors: array of Vector2
M
Mr.doob 已提交
35

M
Mr.doob 已提交
36
THREE.Path.prototype.fromPoints = function ( vectors ) {
M
Mr.doob 已提交
37 38 39

	this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );

M
Mr.doob 已提交
40 41
	var v, vlen = vectors.length;

M
Mr.doob 已提交
42 43 44 45 46 47 48 49
	for ( v = 1; v < vlen; v++ ) {

		this.lineTo( vectors[ v ].x, vectors[ v ].y );

	};

};

M
Mr.doob 已提交
50 51 52
// startPath() endPath()?

THREE.Path.prototype.moveTo = function ( x, y ) {
M
Mr.doob 已提交
53 54 55 56 57 58

	var args = Array.prototype.slice.call( arguments );
	this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );

};

M
Mr.doob 已提交
59
THREE.Path.prototype.lineTo = function ( x, y ) {
M
Mr.doob 已提交
60 61

	var args = Array.prototype.slice.call( arguments );
M
Mr.doob 已提交
62 63 64 65 66 67 68 69 70 71

	var lastargs = this.actions[ this.actions.length - 1 ].args;

	var x0 = lastargs[ lastargs.length - 2 ];
	var y0 = lastargs[ lastargs.length - 1 ];

	var curve = new THREE.LineCurve( x0, y0, x, y );
	this.curves.push( curve );

	this.actions.push( { action: THREE.PathActions.LINE_TO, args: args, curve: curve } );
M
Mr.doob 已提交
72 73 74 75 76 77

};

THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {

	var args = Array.prototype.slice.call( arguments );
M
Mr.doob 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90

	var lastargs = this.actions[ this.actions.length - 1 ].args;

	var x0 = lastargs[ lastargs.length - 2 ];
	var y0 = lastargs[ lastargs.length - 1 ];

	var curve = new THREE.QuadraticBezierCurve( x0, y0, aCPx, aCPy, aX, aY );
	this.curves.push( curve );

	this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args, curve: curve } );

	//console.log( curve, curve.getPoints(), curve.getSpacedPoints() );
	//console.log( curve.getPointAt(0), curve.getPointAt(0), curve.getUtoTmapping(0), curve.getSpacedPoints() );
M
Mr.doob 已提交
91 92 93 94 95

};

THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
                                               aCP2x, aCP2y,
M
Mr.doob 已提交
96
                                               aX, aY ) {
M
Mr.doob 已提交
97 98

	var args = Array.prototype.slice.call( arguments );
M
Mr.doob 已提交
99 100 101 102 103 104 105 106 107 108 109 110

	var lastargs = this.actions[ this.actions.length - 1 ].args;

	var x0 = lastargs[ lastargs.length - 2 ];
	var y0 = lastargs[ lastargs.length - 1 ];

	var curve = new THREE.CubicBezierCurve( x0, y0, aCP1x, aCP1y,
	                                                aCP2x, aCP2y,
	                                                aX, aY );
	this.curves.push( curve );

	this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args, curve: curve } );
M
Mr.doob 已提交
111 112 113 114 115 116

};

THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {

	var args = Array.prototype.slice.call( arguments );
M
Mr.doob 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
	var lastargs = this.actions[ this.actions.length - 1 ].args;

	var x0 = lastargs[ lastargs.length - 2 ];
	var y0 = lastargs[ lastargs.length - 1 ];

	var npts = [ new THREE.Vector2( x0, y0 ) ];
	npts =  npts.concat( pts );

	var curve = new THREE.SplineCurve( npts );
	this.curves.push( curve );

	this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args, curve: curve } );

	//console.log( curve, curve.getPoints(), curve.getSpacedPoints() );

};
M
Mr.doob 已提交
133

M
Mr.doob 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
// FUTURE: Change the API or follow canvas API?
// TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )

THREE.Path.prototype.arc = function ( aX, aY, aRadius,
									  aStartAngle, aEndAngle, aClockwise ) {

	var args = Array.prototype.slice.call( arguments );

	var curve = new THREE.ArcCurve( aX, aY, aRadius,
									aStartAngle, aEndAngle, aClockwise );
	this.curves.push( curve );

	// console.log( 'arc', args );

	this.actions.push( { action: THREE.PathActions.ARC, args: args } );

 };

/*
// FUTURE ENHANCEMENTS

 example usage?

 Path.addExprFunc('sineCurveTo', sineCurveGetPtFunction)
 Path.sineCurveTo(x,y, amptitude);
 sineCurve.getPoint(t);
 return sine(disnt) * ampt

 // Create a new func eg. sin (theta) x
 THREE.Path.prototype.addExprFunc = function(exprName, func) {
 };
*/


THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {

	if ( !divisions ) divisions = 40;

	var points = [];

	for ( var i = 0; i < divisions; i++ ) {

		points.push( this.getPoint( i / divisions ) );

		//if( !this.getPoint( i / divisions ) ) throw "DIE";

	}
M
Mr.doob 已提交
181

M
Mr.doob 已提交
182 183 184 185 186 187 188 189 190
	if ( closedPath ) {

		points.push( points[ 0 ] );

	}

	return points;

};
M
Mr.doob 已提交
191 192 193

/* Return an array of vectors based on contour of the path */

M
Mr.doob 已提交
194
THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
M
Mr.doob 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215

	divisions = divisions || 12;

	var points = [];

	var i, il, item, action, args;
	var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
		laste, j,
		t, tx, ty;

	for ( i = 0, il = this.actions.length; i < il; i++ ) {

		item = this.actions[ i ];

		action = item.action;
		args = item.args;

		switch( action ) {

		case THREE.PathActions.MOVE_TO:

M
Mr.doob 已提交
216
			// points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
M
Mr.doob 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

			break;

		case THREE.PathActions.LINE_TO:

			points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );

			break;

		case THREE.PathActions.QUADRATIC_CURVE_TO:

			cpx  = args[ 2 ];
			cpy  = args[ 3 ];

			cpx1 = args[ 0 ];
			cpy1 = args[ 1 ];

			if ( points.length > 0 ) {

				laste = points[ points.length - 1 ];

				cpx0 = laste.x;
				cpy0 = laste.y;

			} else {

				laste = this.actions[ i - 1 ].args;

				cpx0 = laste[ laste.length - 2 ];
				cpy0 = laste[ laste.length - 1 ];

			}

			for ( j = 1; j <= divisions; j ++ ) {

				t = j / divisions;

				tx = THREE.FontUtils.b2( t, cpx0, cpx1, cpx );
				ty = THREE.FontUtils.b2( t, cpy0, cpy1, cpy );

				points.push( new THREE.Vector2( tx, ty ) );

		  	}

			break;

		case THREE.PathActions.BEZIER_CURVE_TO:

			cpx  = args[ 4 ];
			cpy  = args[ 5 ];

			cpx1 = args[ 0 ];
			cpy1 = args[ 1 ];

			cpx2 = args[ 2 ];
			cpy2 = args[ 3 ];

			if ( points.length > 0 ) {

				laste = points[ points.length - 1 ];

				cpx0 = laste.x;
				cpy0 = laste.y;

			} else {

				laste = this.actions[ i - 1 ].args;

				cpx0 = laste[ laste.length - 2 ];
				cpy0 = laste[ laste.length - 1 ];

			}


			for ( j = 1; j <= divisions; j ++ ) {

				t = j / divisions;

				tx = THREE.FontUtils.b3( t, cpx0, cpx1, cpx2, cpx );
				ty = THREE.FontUtils.b3( t, cpy0, cpy1, cpy2, cpy );

				points.push( new THREE.Vector2( tx, ty ) );

			}

			break;

		case THREE.PathActions.CSPLINE_THRU:

			laste = this.actions[ i - 1 ].args;
M
Mr.doob 已提交
307

M
Mr.doob 已提交
308
			var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
M
Mr.doob 已提交
309
			var spts = [ last ];
M
Mr.doob 已提交
310

M
Mr.doob 已提交
311
			var n = divisions * args[ 0 ].length;
M
Mr.doob 已提交
312

M
Mr.doob 已提交
313
			spts = spts.concat( args[ 0 ] );
M
Mr.doob 已提交
314

M
Mr.doob 已提交
315 316
			var spline = new THREE.SplineCurve( spts );
			for ( j = 1; j <= n; j ++ ) {
M
Mr.doob 已提交
317

M
Mr.doob 已提交
318
				points.push( spline.getPointAt( j / n ) ) ;
M
Mr.doob 已提交
319 320 321 322 323

			}

			break;

M
Mr.doob 已提交
324
		case THREE.PathActions.ARC:
M
Mr.doob 已提交
325

M
Mr.doob 已提交
326
			laste = this.actions[ i - 1 ].args;
M
Mr.doob 已提交
327

M
Mr.doob 已提交
328 329 330 331
			var aX = args[ 0 ], aY = args[ 1 ],
				aRadius = args[ 2 ],
				aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
				aClockwise = !!args[ 5 ];
M
Mr.doob 已提交
332

M
Mr.doob 已提交
333 334
			var lastx = laste[ laste.length - 2 ],
				lasty = laste[ laste.length - 1 ];
M
Mr.doob 已提交
335

M
Mr.doob 已提交
336
			if ( laste.length == 0 ) {
M
Mr.doob 已提交
337

M
Mr.doob 已提交
338
				lastx = lasty = 0;
M
Mr.doob 已提交
339

M
Mr.doob 已提交
340
			}
M
Mr.doob 已提交
341 342


M
Mr.doob 已提交
343 344 345 346
			var deltaAngle = aEndAngle - aStartAngle;
			var angle;
			var tdivisions = divisions * 2;
			var t;
M
Mr.doob 已提交
347

M
Mr.doob 已提交
348
			for ( j = 1; j <= tdivisions; j ++ ) {
M
Mr.doob 已提交
349

M
Mr.doob 已提交
350
				t = j / tdivisions;
M
Mr.doob 已提交
351

M
Mr.doob 已提交
352
				if ( !aClockwise ) {
M
Mr.doob 已提交
353

M
Mr.doob 已提交
354
					t = 1 - t;
M
Mr.doob 已提交
355

M
Mr.doob 已提交
356 357 358 359 360 361 362 363 364 365
				}

				angle = aStartAngle + t * deltaAngle;

				tx = lastx + aX + aRadius * Math.cos( angle );
				ty = lasty + aY + aRadius * Math.sin( angle );

				//console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);

				points.push( new THREE.Vector2( tx, ty ) );
M
Mr.doob 已提交
366

M
Mr.doob 已提交
367 368 369
			}

			//console.log(points);
M
Mr.doob 已提交
370

M
Mr.doob 已提交
371
		  break;
M
Mr.doob 已提交
372

M
Mr.doob 已提交
373
		} // end switch
M
Mr.doob 已提交
374 375 376

	}

M
Mr.doob 已提交
377
	if ( closedPath ) {
M
Mr.doob 已提交
378

M
Mr.doob 已提交
379
		points.push( points[ 0 ] );
M
Mr.doob 已提交
380

M
Mr.doob 已提交
381 382 383 384 385 386 387
	}

	return points;

};

THREE.Path.prototype.getMinAndMax = function () {
M
Mr.doob 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410

	var points = this.getPoints();

	var maxX, maxY;
	var minX, minY;

	maxX = maxY = Number.NEGATIVE_INFINITY;
	minX = minY = Number.POSITIVE_INFINITY;

	var p, i, il;

	for ( i = 0, il = points.length; i < il; i ++ ) {

		p = points[ i ];

		if ( p.x > maxX ) maxX = p.x;
		else if ( p.x < minX ) minX = p.x;

		if ( p.y > maxY ) maxY = p.y;
		else if ( p.y < maxY ) minY = p.y;

	}

M
Mr.doob 已提交
411
	// TODO Include CG or find mid-pt?
M
Mr.doob 已提交
412 413 414 415 416 417 418 419 420 421 422 423

	return {

		minX: minX,
		minY: minY,
		maxX: maxX,
		maxY: maxY

	};

};

M
Mr.doob 已提交
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603

// To get accurate point with reference to
// entire path distance at time t,
// following has to be done

// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')

THREE.Path.prototype.getPoint = function( t ) {

	var d = t * this.getLength();
	var curveLengths = this.sums;
	var i = 0, diff, curve;

	// To think about boundaries points.

	while ( i < curveLengths.length ) {

		if ( curveLengths[ i ] >= d ) {

			diff = curveLengths[ i ] - d;
			curve = this.curves[ i ];

			var u = 1 - diff / curve.getLength();

			return curve.getPointAt( u );

			break;
		}

		i++;

	}

	return null;

	// loop where sum != 0, sum > d , sum+1 <d

};

// Compute lengths and cache them

THREE.Path.prototype.getLength = function() {

	// Loop all actions/path
	// Push sums into cached array

	var lengths = [], sums = 0;
	var i, il = this.curves.length;

	for ( i = 0; i < il ; i++ ) {

		sums += this.curves[ i ].getLength();
		lengths.push( sums );

	}

	this.sums = lengths;

	return sums;

};


/// Generate geometry from path points (for Line or ParticleSystem objects)

THREE.Path.prototype.createPointsGeometry = function( divisions ) {

    var pts = this.getPoints( divisions, true );
	return this.createGeometry( pts );

};

// Generate geometry from equidistance sampling along the path

THREE.Path.prototype.createSpacedPointsGeometry = function( divisions ) {

    var pts = this.getSpacedPoints( divisions, true );
	return this.createGeometry( pts );

};

THREE.Path.prototype.createGeometry = function( points ) {

	var geometry = new THREE.Geometry();

    for( var i = 0; i < points.length; i ++ ) {

        geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) ) );

    }

    return geometry;

};


// ALL THINGS BELOW TO BE REFACTORED
// QN: Transform final pts or transform ACTIONS or add transform filters?

// FUTURE refactor path = an array of lines -> straight, bezier, splines, arc, funcexpr lines
// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html

THREE.Path.prototype.transform = function( path ) {

	path = new THREE.Path();
	path.moveTo( 0, 0 );
	path.quadraticCurveTo( 100, 20, 140, 80 );

	console.log( path.cacheArcLengths() );

	var thisBounds = this.getMinAndMax();
	var oldPts = this.getPoints();

	var i, il, p, oldX, oldY, xNorm;

	for ( i = 0, il = oldPts.length; i < il; i ++ ) {

		p = oldPts[ i ];

		oldX = p.x;
		oldY = p.y;

		var xNorm = oldX/ thisBounds.maxX;

		// If using actual distance, for length > path, requires line extrusions
		//xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance

		var pathPt = path.getPoint( xNorm );
		var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );

		p.x = pathPt.x + normal.x;
		p.y = pathPt.y + normal.y;

		//p.x = a * oldX + b * oldY + c;
		//p.y = d * oldY + e * oldX + f;

	}

	return oldPts;

};

// Read http://www.tinaja.com/glib/nonlingr.pdf
// nonlinear transforms

THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {

	// a - horizontal size
	// b - lean
	// c - x offset
	// d - vertical size
	// e - climb
	// f - y offset

	var oldPts = this.getPoints();

	var i, il, p, oldX, oldY;

	for ( i = 0, il = oldPts.length; i < il; i ++ ) {

		p = oldPts[i];

		oldX = p.x;
		oldY = p.y;

		p.x = a * oldX + b * oldY + c;
		p.y = d * oldY + e * oldX + f;

	}

	return oldPts;

};


// FUTURE Export JSON Format

M
Mr.doob 已提交
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
/* Draws this path onto a 2d canvas easily */

THREE.Path.prototype.debug = function( canvas ) {

	var bounds = this.getMinAndMax();

	if ( !canvas ) {

		canvas = document.createElement( "canvas" );

		canvas.setAttribute( 'width',  bounds.maxX + 100 );
		canvas.setAttribute( 'height', bounds.maxY + 100 );

		document.body.appendChild( canvas );

	}

	var ctx = canvas.getContext( "2d" );
	ctx.fillStyle = "white";
	ctx.fillRect( 0, 0, canvas.width, canvas.height );

	ctx.strokeStyle = "black";
	ctx.beginPath();

	var i, il, item, action, args;

	// Debug Path

	for ( i = 0, il = this.actions.length; i < il; i ++ ) {

		item = this.actions[ i ];

		args = item.args;
		action = item.action;

		// Short hand for now

		if ( action != THREE.PathActions.CSPLINE_THRU ) {

			ctx[ action ].apply( ctx, args );

		}

		/*
		switch ( action ) {

			case THREE.PathActions.MOVE_TO:

				ctx[ action ]( args[ 0 ], args[ 1 ] );
				break;

			case THREE.PathActions.LINE_TO:

				ctx[ action ]( args[ 0 ], args[ 1 ] );
				break;

			case THREE.PathActions.QUADRATIC_CURVE_TO:

				ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
				break;

			case THREE.PathActions.CUBIC_CURVE_TO:

				ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
				break;

		}
		*/

	}

	ctx.stroke();
	ctx.closePath();

M
Mr.doob 已提交
678
	// Debug Points
M
Mr.doob 已提交
679 680 681

	ctx.strokeStyle = "red";

M
Mr.doob 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
	/* TO CLEAN UP */

	//var p, points = this.getPoints();

	var theta = -90 /180 * Math.PI;
	var p, points = this.transform( 0.866, - 0.866,0, 0.500 , 0.50,-50 );

	//0.866, - 0.866,0, 0.500 , 0.50,-50

	// Math.cos(theta),Math.sin(theta),100,
	// Math.cos(theta),-Math.sin(theta),-50

	// translate, scale, rotation

	// a - horizontal size
	// b - lean
	// c - x offset
	// d - vertical size
	// e - climb
	// f - y offset
	// 1,0,0,
	// -1,0,100
M
Mr.doob 已提交
704 705 706 707 708 709 710 711 712 713 714 715 716

	for ( i = 0, il = points.length; i < il; i ++ ) {

		p = points[ i ];

		ctx.beginPath();
		ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
		ctx.stroke();
		ctx.closePath();

	}

};