ViewHelper.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import {
  2. CylinderGeometry,
  3. CanvasTexture,
  4. Color,
  5. Euler,
  6. Mesh,
  7. MeshBasicMaterial,
  8. Object3D,
  9. OrthographicCamera,
  10. Quaternion,
  11. Raycaster,
  12. Sprite,
  13. SpriteMaterial,
  14. SRGBColorSpace,
  15. Vector2,
  16. Vector3,
  17. Vector4
  18. } from 'three';
  19. /**
  20. * A special type of helper that visualizes the camera's transformation
  21. * in a small viewport area as an axes helper. Such a helper is often wanted
  22. * in 3D modeling tools or scene editors like the [three.js editor](https://threejs.org/editor).
  23. *
  24. * The helper allows to click on the X, Y and Z axes which animates the camera
  25. * so it looks along the selected axis.
  26. *
  27. * @augments Object3D
  28. * @three_import import { ViewHelper } from 'three/addons/helpers/ViewHelper.js';
  29. */
  30. class ViewHelper extends Object3D {
  31. /**
  32. * Constructs a new view helper.
  33. *
  34. * @param {Camera} camera - The camera whose transformation should be visualized.
  35. * @param {HTMLElement} [domElement] - The DOM element that is used to render the view.
  36. */
  37. constructor( camera, domElement ) {
  38. super();
  39. /**
  40. * This flag can be used for type testing.
  41. *
  42. * @type {boolean}
  43. * @readonly
  44. * @default true
  45. */
  46. this.isViewHelper = true;
  47. /**
  48. * The camera whose transformation is visualized. It can be reassigned at
  49. * any time to rebind the helper to a different camera.
  50. *
  51. * @type {Camera}
  52. */
  53. this.camera = camera;
  54. /**
  55. * Whether the helper is currently animating or not.
  56. *
  57. * @type {boolean}
  58. * @readonly
  59. * @default false
  60. */
  61. this.animating = false;
  62. /**
  63. * The helper's center point.
  64. *
  65. * @type {Vector3}
  66. */
  67. this.center = new Vector3();
  68. /**
  69. * Controls the position of the helper in the viewport.
  70. * Use `top`/`bottom` for vertical positioning and `left`/`right` for horizontal.
  71. * If `left` is `null`, `right` is used. If `top` is `null`, `bottom` is used.
  72. *
  73. * @type {{top: number|null, right: number, bottom: number, left: number|null}}
  74. */
  75. this.location = {
  76. top: null,
  77. right: 0,
  78. bottom: 0,
  79. left: null
  80. };
  81. const color1 = new Color( '#ff4466' );
  82. const color2 = new Color( '#88ff44' );
  83. const color3 = new Color( '#4488ff' );
  84. const color4 = new Color( '#000000' );
  85. const options = {};
  86. const scope = this;
  87. const interactiveObjects = [];
  88. const raycaster = new Raycaster();
  89. const mouse = new Vector2();
  90. const dummy = new Object3D();
  91. const orthoCamera = new OrthographicCamera( - 2, 2, 2, - 2, 0, 4 );
  92. orthoCamera.position.set( 0, 0, 2 );
  93. const geometry = new CylinderGeometry( 0.04, 0.04, 0.8, 5 ).rotateZ( - Math.PI / 2 ).translate( 0.4, 0, 0 );
  94. const xAxis = new Mesh( geometry, getAxisMaterial( color1 ) );
  95. const yAxis = new Mesh( geometry, getAxisMaterial( color2 ) );
  96. const zAxis = new Mesh( geometry, getAxisMaterial( color3 ) );
  97. yAxis.rotation.z = Math.PI / 2;
  98. zAxis.rotation.y = - Math.PI / 2;
  99. this.add( xAxis );
  100. this.add( zAxis );
  101. this.add( yAxis );
  102. const spriteMaterial1 = getSpriteMaterial( color1 );
  103. const spriteMaterial2 = getSpriteMaterial( color2 );
  104. const spriteMaterial3 = getSpriteMaterial( color3 );
  105. const spriteMaterial4 = getSpriteMaterial( color4 );
  106. const posXAxisHelper = new Sprite( spriteMaterial1 );
  107. const posYAxisHelper = new Sprite( spriteMaterial2 );
  108. const posZAxisHelper = new Sprite( spriteMaterial3 );
  109. const negXAxisHelper = new Sprite( spriteMaterial4 );
  110. const negYAxisHelper = new Sprite( spriteMaterial4 );
  111. const negZAxisHelper = new Sprite( spriteMaterial4 );
  112. posXAxisHelper.position.x = 1;
  113. posYAxisHelper.position.y = 1;
  114. posZAxisHelper.position.z = 1;
  115. negXAxisHelper.position.x = - 1;
  116. negYAxisHelper.position.y = - 1;
  117. negZAxisHelper.position.z = - 1;
  118. negXAxisHelper.material.opacity = 0.2;
  119. negYAxisHelper.material.opacity = 0.2;
  120. negZAxisHelper.material.opacity = 0.2;
  121. posXAxisHelper.userData.type = 'posX';
  122. posYAxisHelper.userData.type = 'posY';
  123. posZAxisHelper.userData.type = 'posZ';
  124. negXAxisHelper.userData.type = 'negX';
  125. negYAxisHelper.userData.type = 'negY';
  126. negZAxisHelper.userData.type = 'negZ';
  127. this.add( posXAxisHelper );
  128. this.add( posYAxisHelper );
  129. this.add( posZAxisHelper );
  130. this.add( negXAxisHelper );
  131. this.add( negYAxisHelper );
  132. this.add( negZAxisHelper );
  133. interactiveObjects.push( posXAxisHelper );
  134. interactiveObjects.push( posYAxisHelper );
  135. interactiveObjects.push( posZAxisHelper );
  136. interactiveObjects.push( negXAxisHelper );
  137. interactiveObjects.push( negYAxisHelper );
  138. interactiveObjects.push( negZAxisHelper );
  139. const point = new Vector3();
  140. const dim = 128;
  141. const turnRate = 2 * Math.PI; // turn rate in angles per second
  142. /**
  143. * Renders the helper in a separate view in the viewport.
  144. * Position is controlled by the `location` property.
  145. *
  146. * @param {WebGLRenderer|WebGPURenderer} renderer - The renderer.
  147. */
  148. this.render = function ( renderer ) {
  149. this.quaternion.copy( this.camera.quaternion ).invert();
  150. this.updateMatrixWorld();
  151. point.set( 0, 0, 1 );
  152. point.applyQuaternion( this.camera.quaternion );
  153. //
  154. const location = this.location;
  155. let x, y;
  156. if ( location.left !== null ) {
  157. x = location.left;
  158. } else {
  159. x = domElement.offsetWidth - dim - location.right;
  160. }
  161. if ( location.top !== null ) {
  162. // Position from top
  163. y = renderer.isWebGPURenderer ? location.top : domElement.offsetHeight - dim - location.top;
  164. } else {
  165. // Position from bottom
  166. y = renderer.isWebGPURenderer ? domElement.offsetHeight - dim - location.bottom : location.bottom;
  167. }
  168. renderer.clearDepth();
  169. renderer.getViewport( viewport );
  170. renderer.setViewport( x, y, dim, dim );
  171. renderer.render( this, orthoCamera );
  172. renderer.setViewport( viewport.x, viewport.y, viewport.z, viewport.w );
  173. };
  174. const targetPosition = new Vector3();
  175. const targetQuaternion = new Quaternion();
  176. const q1 = new Quaternion();
  177. const q2 = new Quaternion();
  178. const viewport = new Vector4();
  179. let radius = 0;
  180. /**
  181. * This method should be called when a click or pointer event
  182. * has happened in the app.
  183. *
  184. * @param {PointerEvent} event - The event to process.
  185. * @return {boolean} Whether an intersection with the helper has been detected or not.
  186. */
  187. this.handleClick = function ( event ) {
  188. if ( this.animating === true ) return false;
  189. const rect = domElement.getBoundingClientRect();
  190. const location = this.location;
  191. let offsetX, offsetY;
  192. if ( location.left !== null ) {
  193. offsetX = rect.left + location.left;
  194. } else {
  195. offsetX = rect.left + domElement.offsetWidth - dim - location.right;
  196. }
  197. if ( location.top !== null ) {
  198. offsetY = rect.top + location.top;
  199. } else {
  200. offsetY = rect.top + domElement.offsetHeight - dim - location.bottom;
  201. }
  202. mouse.x = ( ( event.clientX - offsetX ) / dim ) * 2 - 1;
  203. mouse.y = - ( ( event.clientY - offsetY ) / dim ) * 2 + 1;
  204. raycaster.setFromCamera( mouse, orthoCamera );
  205. const intersects = raycaster.intersectObjects( interactiveObjects );
  206. if ( intersects.length > 0 ) {
  207. const intersection = intersects[ 0 ];
  208. const object = intersection.object;
  209. prepareAnimationData( object, this.center );
  210. this.animating = true;
  211. return true;
  212. } else {
  213. return false;
  214. }
  215. };
  216. /**
  217. * Sets labels for each axis. By default, they are unlabeled.
  218. *
  219. * @param {string|undefined} labelX - The label for the x-axis.
  220. * @param {string|undefined} labelY - The label for the y-axis.
  221. * @param {string|undefined} labelZ - The label for the z-axis.
  222. */
  223. this.setLabels = function ( labelX, labelY, labelZ ) {
  224. options.labelX = labelX;
  225. options.labelY = labelY;
  226. options.labelZ = labelZ;
  227. updateLabels();
  228. };
  229. /**
  230. * Sets the label style. Has no effect when the axes are unlabeled.
  231. *
  232. * @param {string} [font='24px Arial'] - The label font.
  233. * @param {string} [color='#000000'] - The label color.
  234. * @param {number} [radius=14] - The label radius.
  235. */
  236. this.setLabelStyle = function ( font, color, radius ) {
  237. options.font = font;
  238. options.color = color;
  239. options.radius = radius;
  240. updateLabels();
  241. };
  242. /**
  243. * Updates the helper. This method should be called in the app's animation
  244. * loop.
  245. *
  246. * @param {number} delta - The delta time in seconds.
  247. */
  248. this.update = function ( delta ) {
  249. const step = delta * turnRate;
  250. // animate position by doing a slerp and then scaling the position on the unit sphere
  251. q1.rotateTowards( q2, step );
  252. this.camera.position.set( 0, 0, 1 ).applyQuaternion( q1 ).multiplyScalar( radius ).add( this.center );
  253. // animate orientation
  254. this.camera.quaternion.rotateTowards( targetQuaternion, step );
  255. if ( q1.angleTo( q2 ) === 0 ) {
  256. this.animating = false;
  257. }
  258. };
  259. /**
  260. * Frees the GPU-related resources allocated by this instance. Call this
  261. * method whenever this instance is no longer used in your app.
  262. */
  263. this.dispose = function () {
  264. geometry.dispose();
  265. xAxis.material.dispose();
  266. yAxis.material.dispose();
  267. zAxis.material.dispose();
  268. posXAxisHelper.material.map.dispose();
  269. posYAxisHelper.material.map.dispose();
  270. posZAxisHelper.material.map.dispose();
  271. negXAxisHelper.material.map.dispose();
  272. negYAxisHelper.material.map.dispose();
  273. negZAxisHelper.material.map.dispose();
  274. posXAxisHelper.material.dispose();
  275. posYAxisHelper.material.dispose();
  276. posZAxisHelper.material.dispose();
  277. negXAxisHelper.material.dispose();
  278. negYAxisHelper.material.dispose();
  279. negZAxisHelper.material.dispose();
  280. };
  281. function prepareAnimationData( object, focusPoint ) {
  282. switch ( object.userData.type ) {
  283. case 'posX':
  284. targetPosition.set( 1, 0, 0 );
  285. targetQuaternion.setFromEuler( new Euler( 0, Math.PI * 0.5, 0 ) );
  286. break;
  287. case 'posY':
  288. targetPosition.set( 0, 1, 0 );
  289. targetQuaternion.setFromEuler( new Euler( - Math.PI * 0.5, 0, 0 ) );
  290. break;
  291. case 'posZ':
  292. targetPosition.set( 0, 0, 1 );
  293. targetQuaternion.setFromEuler( new Euler() );
  294. break;
  295. case 'negX':
  296. targetPosition.set( - 1, 0, 0 );
  297. targetQuaternion.setFromEuler( new Euler( 0, - Math.PI * 0.5, 0 ) );
  298. break;
  299. case 'negY':
  300. targetPosition.set( 0, - 1, 0 );
  301. targetQuaternion.setFromEuler( new Euler( Math.PI * 0.5, 0, 0 ) );
  302. break;
  303. case 'negZ':
  304. targetPosition.set( 0, 0, - 1 );
  305. targetQuaternion.setFromEuler( new Euler( 0, Math.PI, 0 ) );
  306. break;
  307. default:
  308. console.error( 'ViewHelper: Invalid axis.' );
  309. }
  310. //
  311. radius = scope.camera.position.distanceTo( focusPoint );
  312. targetPosition.multiplyScalar( radius ).add( focusPoint );
  313. dummy.position.copy( focusPoint );
  314. dummy.lookAt( scope.camera.position );
  315. q1.copy( dummy.quaternion );
  316. dummy.lookAt( targetPosition );
  317. q2.copy( dummy.quaternion );
  318. }
  319. function getAxisMaterial( color ) {
  320. return new MeshBasicMaterial( { color: color, toneMapped: false } );
  321. }
  322. function useOffscreenCanvas() {
  323. let result = false;
  324. try {
  325. // this check has been adapted from WebGLTextures
  326. result = typeof OffscreenCanvas !== 'undefined' && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  327. } catch ( err ) {
  328. // Ignore any errors
  329. }
  330. return result;
  331. }
  332. function createCanvas( width, height ) {
  333. let canvas;
  334. if ( useOffscreenCanvas() ) {
  335. canvas = new OffscreenCanvas( width, height );
  336. } else {
  337. canvas = document.createElement( 'canvas' );
  338. canvas.width = width;
  339. canvas.height = height;
  340. }
  341. return canvas;
  342. }
  343. function getSpriteMaterial( color, text ) {
  344. const { font = '24px Arial', color: labelColor = '#000000', radius = 14 } = options;
  345. const canvas = createCanvas( 64, 64 );
  346. const context = canvas.getContext( '2d' );
  347. context.beginPath();
  348. context.arc( 32, 32, radius, 0, 2 * Math.PI );
  349. context.closePath();
  350. context.fillStyle = color.getStyle();
  351. context.fill();
  352. if ( text ) {
  353. context.font = font;
  354. context.textAlign = 'center';
  355. context.fillStyle = labelColor;
  356. context.fillText( text, 32, 41 );
  357. }
  358. const texture = new CanvasTexture( canvas );
  359. texture.colorSpace = SRGBColorSpace;
  360. return new SpriteMaterial( { map: texture, toneMapped: false } );
  361. }
  362. function updateLabels() {
  363. posXAxisHelper.material.map.dispose();
  364. posYAxisHelper.material.map.dispose();
  365. posZAxisHelper.material.map.dispose();
  366. posXAxisHelper.material.dispose();
  367. posYAxisHelper.material.dispose();
  368. posZAxisHelper.material.dispose();
  369. posXAxisHelper.material = getSpriteMaterial( color1, options.labelX );
  370. posYAxisHelper.material = getSpriteMaterial( color2, options.labelY );
  371. posZAxisHelper.material = getSpriteMaterial( color3, options.labelZ );
  372. }
  373. }
  374. }
  375. export { ViewHelper };
粤ICP备19079148号