ViewHelper.js 12 KB

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