[three.js] Quaternion 4원수, 사원수 회전

Quaternion

Implementation of a quaternion. This is used for rotating things without encountering the dreaded gimbal lock issue, amongst other advantages.

Example

var quaternion = new THREE.Quaternion(); quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 ); var vector = new THREE.Vector3( 1, 0, 0 ); vector.applyQuaternion( quaternion );

Constructor

Quaternion( xyzw )

x - x coordinate
y - y coordinate
z - z coordinate
w - w coordinate

Properties

#.x

Changing this property will result in onChangeCallback being called.

#.y

Changing this property will result in onChangeCallback being called.

#.z

Changing this property will result in onChangeCallback being called.

#.w

Changing this property will result in onChangeCallback being called.

Methods

#.clone ()

Creates a new Quaternion with identical xyz and w properties to this one.

#.conjugate ()

Returns the rotational conjugate of this quaternion. The conjugate of a quaternion represents the same rotation in the opposite direction about the rotational axis.

#.copy ( q )

Copies the xy, z and w properties of q into this quaternion.

#.equals ( v )

v - Quaternion that this quaternion will be compared to.

Compares the xy, z and w properties of v to the equivalent properties of this quaternion to determine if they represent the same rotation.

#.dot ( v )

Calculates the dot product of quaternions v and this one.

#.fromArray ( arrayoffset )

array - array of format (x, y, z, w) used to construct the quaternion.
offset - (optional) an offset into the array.

Sets this quaternion's xy, z and w properties from an array.

#.inverse ()

Inverts this quaternion - calculate the conjugate and then normalizes the result.

#.length ()

Computes the Euclidean length (straight-line length) of this quaternion, considered as a 4 dimensional vector.

#.lengthSq ()

Computes the Euclidean length (straight-line length) of this quaternion, considered as a 4 dimensional vector. This can be useful if you are comparing the lengths of two quaternions, as this is a slightly more efficient calculation than length().

#.normalize ()

Normalizes this quaternion - that is, calculated the quaternion that performs the same rotation as this one, but has length equal to 1.

#.multiply ( q )

Multiplies this quaternion by q.

#.multiplyQuaternions ( ab )

Sets this quaternion to a x b.
Adapted from the method outlined here.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

#.onChange ( onChangeCallback )

Sets the onChangeCallback() method.

#.onChangeCallback ( )

This function is called whenever any of the following occurs:

By default it is the empty function, however you can change it if needed using onChangeonChangeCallback ).

#.premultiply ( q )

Pre-multiplies this quaternion by q.

#.slerp ( qbt )

qb - The other quaternion rotation
t - interpolation factor in the closed interval [0, 1].

Handles the spherical linear interpolation between quaternions. t represents the amount of rotation between this quaternion (where t is 0) and qb (where t is 1). This quaternion is set to the result. Also see the static version of the slerp below.// rotate a mesh towards a target quaternion mesh.quaternion.slerp( endQuaternion, 0.01 );

#.set ( xyzw )

Sets xyzw properties of this quaternion.

#.setFromAxisAngle ( axisangle )

Sets this quaternion from rotation specified by axis and angle.
Adapted from the method here.
Axis is assumed to be normalized, angle is in radians.

#.setFromEuler ( euler )

Sets this quaternion from the rotation specified by Euler angle.

#.setFromRotationMatrix ( m )

Sets this quaternion from rotation component of m.
Adapted from the method here.

#.setFromUnitVectors ( vFromvTo )

Sets this quaternion to the rotation required to rotate direction vector vFrom to direction vector vTo.
Adapted from the method here.
vFrom and vTo are assumed to be normalized.

#.toArray ( arrayoffset )

array - An optional array to store the quaternion. If not specified, a new array will be created.
offset - (optional) if specified, the result will be copied into this Array.

Returns the numerical elements of this quaternion in an array of format [x, y, z, w].

Static Methods

Static methods (as opposed to instance methods) are designed to be called directly from the class, rather than from a specific instance. So to use the static version of, call it like so:THREE.Quaternion.slerp( qStart, qEnd, qTarget, t );By contrast, to call the 'normal' or instanced slerp method, you would do the following://instantiate a quaternion with default values var q = new THREE.Quaternion(); //call the instanced slerp method q.slerp( qb, t )

#.slerp ( qStartqEndqTargett )

qStart - The starting quaternion (where t is 0)
qEnd - The ending quaternion (where t is 1)
qTarget - The target quaternion that gets set with the result
t - interpolation factor in the closed interval [0, 1].

Unlike the normal method, the static version of slerp sets a target quaternion to the result of the slerp operation.// Code setup var startQuaternion = new THREE.Quaternion().set( 0, 0, 0, 1 ).normalize(); var endQuaternion = new THREE.Quaternion().set( 1, 1, 1, 1 ).normalize(); var t = 0; // Update a mesh's rotation in the loop t = ( t + 0.01 ) % 1; // constant angular momentum THREE.Quaternion.slerp( startQuaternion, endQuaternion, mesh.quaternion, t );

#.slerpFlat ( dstdstOffsetsrc0srcOffset0src1srcOffset1t )

dst - The output array.
dstOffset - An offset into the output array.
src0 - The source array of the starting quaternion.
srcOffset0 - An offset into the array src0.
src1 - The source array of the target quatnerion.
srcOffset1 - An offset into the array src1.
t - Normalized interpolation factor (between 0 and 1).
 

Like the static slerp method above, but operates directly on flat arrays of numbers.

Source

src/math/Quaternion.js

[출처] https://threejs.org/docs/#api/math/Quaternion

import { Vector3 } from './Vector3';

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 */

function Quaternion( x, y, z, w ) {

	this._x = x || 0;
	this._y = y || 0;
	this._z = z || 0;
	this._w = ( w !== undefined ) ? w : 1;

}

Object.assign( Quaternion, {

	slerp: function ( qa, qb, qm, t ) {

		return qm.copy( qa ).slerp( qb, t );

	},

	slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {

		// fuzz-free, array-based Quaternion SLERP operation

		var x0 = src0[ srcOffset0 + 0 ],
			y0 = src0[ srcOffset0 + 1 ],
			z0 = src0[ srcOffset0 + 2 ],
			w0 = src0[ srcOffset0 + 3 ],

			x1 = src1[ srcOffset1 + 0 ],
			y1 = src1[ srcOffset1 + 1 ],
			z1 = src1[ srcOffset1 + 2 ],
			w1 = src1[ srcOffset1 + 3 ];

		if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {

			var s = 1 - t,

				cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,

				dir = ( cos >= 0 ? 1 : - 1 ),
				sqrSin = 1 - cos * cos;

			// Skip the Slerp for tiny steps to avoid numeric problems:
			if ( sqrSin > Number.EPSILON ) {

				var sin = Math.sqrt( sqrSin ),
					len = Math.atan2( sin, cos * dir );

				s = Math.sin( s * len ) / sin;
				t = Math.sin( t * len ) / sin;

			}

			var tDir = t * dir;

			x0 = x0 * s + x1 * tDir;
			y0 = y0 * s + y1 * tDir;
			z0 = z0 * s + z1 * tDir;
			w0 = w0 * s + w1 * tDir;

			// Normalize in case we just did a lerp:
			if ( s === 1 - t ) {

				var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );

				x0 *= f;
				y0 *= f;
				z0 *= f;
				w0 *= f;

			}

		}

		dst[ dstOffset ] = x0;
		dst[ dstOffset + 1 ] = y0;
		dst[ dstOffset + 2 ] = z0;
		dst[ dstOffset + 3 ] = w0;

	}

} );

Object.defineProperties( Quaternion.prototype, {

	x: {

		get: function () {

			return this._x;

		},

		set: function ( value ) {

			this._x = value;
			this.onChangeCallback();

		}

	},

	y: {

		get: function () {

			return this._y;

		},

		set: function ( value ) {

			this._y = value;
			this.onChangeCallback();

		}

	},

	z: {

		get: function () {

			return this._z;

		},

		set: function ( value ) {

			this._z = value;
			this.onChangeCallback();

		}

	},

	w: {

		get: function () {

			return this._w;

		},

		set: function ( value ) {

			this._w = value;
			this.onChangeCallback();

		}

	}

} );

Object.assign( Quaternion.prototype, {

	set: function ( x, y, z, w ) {

		this._x = x;
		this._y = y;
		this._z = z;
		this._w = w;

		this.onChangeCallback();

		return this;

	},

	clone: function () {

		return new this.constructor( this._x, this._y, this._z, this._w );

	},

	copy: function ( quaternion ) {

		this._x = quaternion.x;
		this._y = quaternion.y;
		this._z = quaternion.z;
		this._w = quaternion.w;

		this.onChangeCallback();

		return this;

	},

	setFromEuler: function ( euler, update ) {

		if ( ! ( euler && euler.isEuler ) ) {

			throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );

		}

		var x = euler._x, y = euler._y, z = euler._z, order = euler.order;

		// http://www.mathworks.com/matlabcentral/fileexchange/
		// 	20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
		//	content/SpinCalc.m

		var cos = Math.cos;
		var sin = Math.sin;

		var c1 = cos( x / 2 );
		var c2 = cos( y / 2 );
		var c3 = cos( z / 2 );

		var s1 = sin( x / 2 );
		var s2 = sin( y / 2 );
		var s3 = sin( z / 2 );

		if ( order === 'XYZ' ) {

			this._x = s1 * c2 * c3 + c1 * s2 * s3;
			this._y = c1 * s2 * c3 - s1 * c2 * s3;
			this._z = c1 * c2 * s3 + s1 * s2 * c3;
			this._w = c1 * c2 * c3 - s1 * s2 * s3;

		} else if ( order === 'YXZ' ) {

			this._x = s1 * c2 * c3 + c1 * s2 * s3;
			this._y = c1 * s2 * c3 - s1 * c2 * s3;
			this._z = c1 * c2 * s3 - s1 * s2 * c3;
			this._w = c1 * c2 * c3 + s1 * s2 * s3;

		} else if ( order === 'ZXY' ) {

			this._x = s1 * c2 * c3 - c1 * s2 * s3;
			this._y = c1 * s2 * c3 + s1 * c2 * s3;
			this._z = c1 * c2 * s3 + s1 * s2 * c3;
			this._w = c1 * c2 * c3 - s1 * s2 * s3;

		} else if ( order === 'ZYX' ) {

			this._x = s1 * c2 * c3 - c1 * s2 * s3;
			this._y = c1 * s2 * c3 + s1 * c2 * s3;
			this._z = c1 * c2 * s3 - s1 * s2 * c3;
			this._w = c1 * c2 * c3 + s1 * s2 * s3;

		} else if ( order === 'YZX' ) {

			this._x = s1 * c2 * c3 + c1 * s2 * s3;
			this._y = c1 * s2 * c3 + s1 * c2 * s3;
			this._z = c1 * c2 * s3 - s1 * s2 * c3;
			this._w = c1 * c2 * c3 - s1 * s2 * s3;

		} else if ( order === 'XZY' ) {

			this._x = s1 * c2 * c3 - c1 * s2 * s3;
			this._y = c1 * s2 * c3 - s1 * c2 * s3;
			this._z = c1 * c2 * s3 + s1 * s2 * c3;
			this._w = c1 * c2 * c3 + s1 * s2 * s3;

		}

		if ( update !== false ) this.onChangeCallback();

		return this;

	},

	setFromAxisAngle: function ( axis, angle ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm

		// assumes axis is normalized

		var halfAngle = angle / 2, s = Math.sin( halfAngle );

		this._x = axis.x * s;
		this._y = axis.y * s;
		this._z = axis.z * s;
		this._w = Math.cos( halfAngle );

		this.onChangeCallback();

		return this;

	},

	setFromRotationMatrix: function ( m ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

		// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

		var te = m.elements,

			m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
			m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
			m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],

			trace = m11 + m22 + m33,
			s;

		if ( trace > 0 ) {

			s = 0.5 / Math.sqrt( trace + 1.0 );

			this._w = 0.25 / s;
			this._x = ( m32 - m23 ) * s;
			this._y = ( m13 - m31 ) * s;
			this._z = ( m21 - m12 ) * s;

		} else if ( m11 > m22 && m11 > m33 ) {

			s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );

			this._w = ( m32 - m23 ) / s;
			this._x = 0.25 * s;
			this._y = ( m12 + m21 ) / s;
			this._z = ( m13 + m31 ) / s;

		} else if ( m22 > m33 ) {

			s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );

			this._w = ( m13 - m31 ) / s;
			this._x = ( m12 + m21 ) / s;
			this._y = 0.25 * s;
			this._z = ( m23 + m32 ) / s;

		} else {

			s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );

			this._w = ( m21 - m12 ) / s;
			this._x = ( m13 + m31 ) / s;
			this._y = ( m23 + m32 ) / s;
			this._z = 0.25 * s;

		}

		this.onChangeCallback();

		return this;

	},

	setFromUnitVectors: function () {

		// assumes direction vectors vFrom and vTo are normalized

		var v1 = new Vector3();
		var r;

		var EPS = 0.000001;

		return function setFromUnitVectors( vFrom, vTo ) {

			if ( v1 === undefined ) v1 = new Vector3();

			r = vFrom.dot( vTo ) + 1;

			if ( r < EPS ) {

				r = 0;

				if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {

					v1.set( - vFrom.y, vFrom.x, 0 );

				} else {

					v1.set( 0, - vFrom.z, vFrom.y );

				}

			} else {

				v1.crossVectors( vFrom, vTo );

			}

			this._x = v1.x;
			this._y = v1.y;
			this._z = v1.z;
			this._w = r;

			return this.normalize();

		};

	}(),

	inverse: function () {

		return this.conjugate().normalize();

	},

	conjugate: function () {

		this._x *= - 1;
		this._y *= - 1;
		this._z *= - 1;

		this.onChangeCallback();

		return this;

	},

	dot: function ( v ) {

		return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;

	},

	lengthSq: function () {

		return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;

	},

	length: function () {

		return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );

	},

	normalize: function () {

		var l = this.length();

		if ( l === 0 ) {

			this._x = 0;
			this._y = 0;
			this._z = 0;
			this._w = 1;

		} else {

			l = 1 / l;

			this._x = this._x * l;
			this._y = this._y * l;
			this._z = this._z * l;
			this._w = this._w * l;

		}

		this.onChangeCallback();

		return this;

	},

	multiply: function ( q, p ) {

		if ( p !== undefined ) {

			console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
			return this.multiplyQuaternions( q, p );

		}

		return this.multiplyQuaternions( this, q );

	},

	premultiply: function ( q ) {

		return this.multiplyQuaternions( q, this );

	},

	multiplyQuaternions: function ( a, b ) {

		// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm

		var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
		var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;

		this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
		this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
		this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
		this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;

		this.onChangeCallback();

		return this;

	},

	slerp: function ( qb, t ) {

		if ( t === 0 ) return this;
		if ( t === 1 ) return this.copy( qb );

		var x = this._x, y = this._y, z = this._z, w = this._w;

		// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/

		var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;

		if ( cosHalfTheta < 0 ) {

			this._w = - qb._w;
			this._x = - qb._x;
			this._y = - qb._y;
			this._z = - qb._z;

			cosHalfTheta = - cosHalfTheta;

		} else {

			this.copy( qb );

		}

		if ( cosHalfTheta >= 1.0 ) {

			this._w = w;
			this._x = x;
			this._y = y;
			this._z = z;

			return this;

		}

		var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );

		if ( Math.abs( sinHalfTheta ) < 0.001 ) {

			this._w = 0.5 * ( w + this._w );
			this._x = 0.5 * ( x + this._x );
			this._y = 0.5 * ( y + this._y );
			this._z = 0.5 * ( z + this._z );

			return this;

		}

		var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
		var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
			ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;

		this._w = ( w * ratioA + this._w * ratioB );
		this._x = ( x * ratioA + this._x * ratioB );
		this._y = ( y * ratioA + this._y * ratioB );
		this._z = ( z * ratioA + this._z * ratioB );

		this.onChangeCallback();

		return this;

	},

	equals: function ( quaternion ) {

		return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this._x = array[ offset ];
		this._y = array[ offset + 1 ];
		this._z = array[ offset + 2 ];
		this._w = array[ offset + 3 ];

		this.onChangeCallback();

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this._x;
		array[ offset + 1 ] = this._y;
		array[ offset + 2 ] = this._z;
		array[ offset + 3 ] = this._w;

		return array;

	},

	onChange: function ( callback ) {

		this.onChangeCallback = callback;

		return this;

	},

	onChangeCallback: function () {}

} );


export { Quaternion };                                                                                                                                  

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
54 javascript : js Array에서 한 원소 삭제 : JavaScript: Remove Element from an Array 졸리운_곰 2018.05.24 323
53 [자바스크립트] 동일한 단어를 문자열에서 찾기, match() 함수 file 졸리운_곰 2018.05.24 346
52 Javascript 함수 생성 2가지 방법의 차이점 file 졸리운_곰 2018.05.24 498
51 React 시작하기 [javascript] 졸리운_곰 2018.05.20 508
50 javascript 에서 큐, 스택, 트리 졸리운_곰 2018.02.27 513
49 CKEditor. Plugin 직접 만들기. 예: Cy-GistInsert file 졸리운_곰 2018.02.21 459
48 템플릿 엔진을 벗어나고 싶은 이유, React 와 Angular 2 사이의 갈등 중간 정리 졸리운_곰 2017.09.26 1354
47 [CSS 기초] DIV 태그를 이용하여 프레임 나누기 file 졸리운_곰 2017.08.25 496
46 jQuery 스타일 & 속성 다루기 file 졸리운_곰 2017.08.25 597
45 Cross-origin resource sharing file 졸리운_곰 2017.08.05 402
44 HTTP 접근 제어 (CORS) 졸리운_곰 2017.08.05 290
43 자바스크립트 문자열 비교 예제; 대소 문자 구분/구분 없이 졸리운_곰 2017.07.22 1285
42 [javascript] hashtable 같은 key=value 예제 졸리운_곰 2017.07.22 483
41 Three.js-Object-Rotation-with-Quaternion file 졸리운_곰 2017.07.08 435
40 Javascript [자바스크립트] 변수 선언과 유효범위 졸리운_곰 2017.07.08 582
39 remove-innerhtml-from-div 태그 안의 html코드 삭제 졸리운_곰 2017.07.08 633
38 HTML5 동영상 임베딩 졸리운_곰 2017.06.18 421
37 Javascript 문자열을 실수(부동소수점) 변수로 변환 가을의곰 2017.06.10 518
36 HTML div 왼쪽, 오른쪽 배치 가을의곰 2017.06.10 493
35 HTML DIV tag: 테두리 너비 지정하는 방법 - WIDTH : 픽셀(px) 또는 퍼센트(%) file 가을의곰 2017.06.10 827
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED