Scene.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { Rect } from "./2d";
  2. import { Animator, Interpolator } from "./Animator";
  3. import { Gesture } from "./Gesture";
  4. import { m4 } from "./m4";
  5. export interface Disposable {
  6. dispose(): void;
  7. }
  8. export interface Layer {
  9. preDraw(): void;
  10. draw(): void;
  11. tap(cx: number, cy: number, sx: number, sy: number): void;
  12. scale(scale: number): void;
  13. dispose(): void;
  14. }
  15. export class LayerAB implements Layer {
  16. preDraw(): void {}
  17. draw(): void {}
  18. tap(cx: number, cy: number, sx: number, sy: number): void {}
  19. scale(scale: number): void {}
  20. dispose(): void {}
  21. }
  22. export class Padding {
  23. constructor(
  24. readonly left: number,
  25. readonly top: number,
  26. readonly right: number,
  27. readonly bottom: number,
  28. ) {}
  29. equals(other: Padding) {
  30. return (
  31. this.left == other.left &&
  32. this.top == other.top &&
  33. this.right == other.right &&
  34. this.bottom == other.bottom
  35. );
  36. }
  37. }
  38. export class Scene implements Disposable {
  39. layers: Array<Layer> = [];
  40. testLayers: Array<Layer> = [];
  41. animators: Array<Animator> = [];
  42. userMat: m4.Matrix4 = m4.identity();
  43. bestFitMat: m4.Matrix4 = m4.identity();
  44. projectionMat: m4.Matrix4 = m4.identity();
  45. resultMat: m4.Matrix4 = m4.identity();
  46. width: number = 0;
  47. height: number = 0;
  48. contentWidth: number = 0;
  49. contentHeight: number = 0;
  50. padding = new Padding(0, 0, 0, 0);
  51. pendingDraw = false;
  52. // clearColorValue: [number, number, number, number] = [1, 1, 1, 1]; // 默认白色
  53. clearColorValue: [number, number, number, number] = [0, 0, 0, 0]; // 默认透明
  54. /** 游戏完成后调用,将 canvas 底色改为透明,让 body 渐变色透出 */
  55. setClearTransparent() {
  56. this.clearColorValue = [0, 0, 0, 0];
  57. this.invalidate();
  58. }
  59. constructor(
  60. readonly gl: WebGL2RenderingContext,
  61. public readonly ratio: number,
  62. public animationFrameProvider: AnimationFrameProvider = window,
  63. public interact: boolean = true,
  64. ) {
  65. this.updateViewport();
  66. let self = this;
  67. if (window && interact) {
  68. new Gesture(gl.canvas as HTMLElement, {
  69. // drag: self.drag.bind(self),
  70. // zoom: self.scaleAt.bind(self),
  71. tap: self.tap.bind(self),
  72. });
  73. }
  74. m4.identity();
  75. }
  76. updateViewport() {
  77. console.log("viewport update.");
  78. const gl = this.gl;
  79. const canvas = gl.canvas as HTMLCanvasElement;
  80. //canvas.width = canvas.clientWidth * this.ratio
  81. //canvas.height = canvas.clientHeight * this.ratio
  82. this.invalidate();
  83. if (canvas.width != this.width || canvas.height != this.height) {
  84. this.width = canvas.width;
  85. this.height = canvas.height;
  86. m4.projection(this.width, this.height, this.projectionMat);
  87. this.updateBestFit();
  88. this.updateResultMat();
  89. }
  90. }
  91. private isBestMatSet: boolean = false;
  92. private updateBestFit() {
  93. if (this.contentWidth == 0 || this.width == 0) return;
  94. const box = new Rect(
  95. this.padding.left,
  96. this.padding.top,
  97. this.width - this.padding.right - this.padding.left,
  98. this.height - this.padding.top - this.padding.bottom,
  99. );
  100. const scale = Math.min(
  101. box.width / this.contentWidth,
  102. box.height / this.contentHeight,
  103. );
  104. const tx = box.center.x - (this.contentWidth * scale) / 2;
  105. const ty = box.center.y - (this.contentHeight * scale) / 2;
  106. m4.identity(this.bestFitMat);
  107. this.bestFitMat[0] = scale;
  108. this.bestFitMat[5] = scale;
  109. this.bestFitMat[12] = tx;
  110. this.bestFitMat[13] = ty;
  111. if (!this.isBestMatSet) {
  112. m4.copy(this.bestFitMat, this.userMat);
  113. this.invalidate();
  114. this.isBestMatSet = true;
  115. }
  116. }
  117. updateResultMat() {
  118. if (this.contentWidth == 0 || this.width == 0) return;
  119. const box = new Rect(
  120. this.padding.left,
  121. this.padding.top,
  122. this.width - this.padding.right - this.padding.left,
  123. this.height - this.padding.top - this.padding.bottom,
  124. );
  125. // const scale = Math.min(box.width / this.contentWidth, box.height / this.contentHeight)
  126. // const tx = box.center.x - this.contentWidth * scale / 2
  127. // const ty = box.center.y - this.contentHeight * scale / 2
  128. // m4.identity(this.resultMat)
  129. // this.resultMat[0] = scale
  130. // this.resultMat[5] = scale
  131. // this.resultMat[12] = tx
  132. // this.resultMat[13] = ty
  133. let rate = this.width > this.height ? 0.7 : 0.8;
  134. let scaleX = (this.width * rate) / this.contentWidth;
  135. let scaleY = (this.height * rate) / this.contentHeight;
  136. let scale = Math.min(scaleX, scaleY);
  137. const tx = box.center.x - (this.contentWidth * scale) / 2;
  138. const ty = box.center.y - (this.contentHeight * scale) / 2;
  139. m4.identity(this.resultMat);
  140. this.resultMat[0] = scale;
  141. this.resultMat[5] = scale;
  142. this.resultMat[12] = tx;
  143. this.resultMat[13] = ty;
  144. }
  145. setContentPadding(padding: Padding) {
  146. if (!this.padding.equals(padding)) {
  147. this.padding = padding;
  148. this.updateBestFit();
  149. this.updateResultMat();
  150. }
  151. }
  152. setContentSize(width: number, height: number) {
  153. if (width != this.contentWidth || height != this.contentWidth) {
  154. this.contentWidth = width;
  155. this.contentHeight = height;
  156. this.updateBestFit();
  157. this.updateResultMat();
  158. }
  159. }
  160. addLayer(layer: Layer) {
  161. this.layers.push(layer);
  162. this.invalidate();
  163. }
  164. invalidate() {
  165. if (this.pendingDraw) return;
  166. this.pendingDraw = true;
  167. //requestAnimationFrame(() => {
  168. this.animationFrameProvider.requestAnimationFrame(() => {
  169. this.draw();
  170. });
  171. }
  172. draw() {
  173. this.animators.forEach((a) => a.update());
  174. this.layers.forEach((l) => l.preDraw());
  175. const gl = this.gl;
  176. gl.viewport(0, 0, this.width, this.height);
  177. gl.clearColor(...this.clearColorValue);
  178. gl.clear(gl.COLOR_BUFFER_BIT);
  179. gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
  180. gl.enable(gl.BLEND);
  181. gl.disable(gl.DEPTH_TEST);
  182. this.layers.forEach((l) => l.draw());
  183. this.pendingDraw = false;
  184. this.animators = this.animators.filter((a) => !a.removable());
  185. if (this.animators.length > 0) {
  186. this.invalidate();
  187. }
  188. }
  189. get drawMatrix(): m4.Matrix4 {
  190. return m4.multiply(this.projectionMat, this.userMat);
  191. }
  192. drag(dx: number, dy: number) {
  193. let t = m4.translation(dx * this.ratio, dy * this.ratio, 0);
  194. this.userMat = m4.multiply(t, this.userMat);
  195. this.invalidate();
  196. }
  197. scaleAt(scale: number, focusX: number, focusY: number) {
  198. focusX *= this.ratio;
  199. focusY *= this.ratio;
  200. let t = m4.scaleAt(scale, scale, focusX, focusY);
  201. this.userMat = m4.multiply(t, this.userMat);
  202. this.layers.forEach((l) => l.scale(this.userMat[0]));
  203. this.invalidate();
  204. }
  205. tap(x: number, y: number) {
  206. let sx = x * this.ratio;
  207. let sy = y * this.ratio;
  208. let [cx, cy] = m4.transformPoint(
  209. m4.inverse(this.userMat),
  210. new Float32Array([sx, sy, 0]),
  211. );
  212. this.layers.forEach((l) => l.tap(cx, cy, sx, sy));
  213. }
  214. addAnimator(animator: Animator) {
  215. this.animators.push(animator);
  216. this.invalidate();
  217. }
  218. addTestLayer(layer: Layer) {
  219. this.testLayers.push(layer);
  220. if (this.testLayers.length <= 1) this.layers.push(layer);
  221. this.invalidate();
  222. }
  223. toggleTestLayer() {
  224. if (this.testLayers.length == 0) return;
  225. let testLayerIndex = this.testLayers.findIndex((l) => {
  226. return this.layers.indexOf(l) >= 0;
  227. });
  228. let next = (testLayerIndex + 1) % this.testLayers.length;
  229. let nextLayer = this.testLayers[next];
  230. if (testLayerIndex >= 0) {
  231. this.layers = this.layers.filter(
  232. (l) => l != this.testLayers[testLayerIndex],
  233. );
  234. }
  235. console.log(`toggleTestLayer, layer=${nextLayer}`);
  236. this.layers.push(nextLayer);
  237. this.invalidate();
  238. }
  239. setScale(scale: number) {
  240. m4.scaling(scale, scale, 1, this.userMat);
  241. this.invalidate();
  242. }
  243. updateUserMat(mat: m4.Matrix4) {
  244. m4.copy(mat, this.userMat);
  245. this.invalidate();
  246. }
  247. matrixAnimationTo(
  248. endMat: m4.Matrix4,
  249. duration: number,
  250. interpolator?: Interpolator,
  251. onEnd?: Function,
  252. ) {
  253. const startMat = m4.copy(this.userMat);
  254. const mat = new Float32Array(16);
  255. const animator = new Animator(
  256. duration,
  257. () => {
  258. m4.lerp(startMat, endMat, mat, animator.value());
  259. this.updateUserMat(mat);
  260. },
  261. () => {
  262. onEnd?.();
  263. },
  264. interpolator,
  265. );
  266. this.addAnimator(animator);
  267. }
  268. resetToBestFit() {
  269. this.matrixAnimationTo(this.bestFitMat, 600);
  270. }
  271. dispose() {
  272. while (this.layers.length > 0) {
  273. let layer = this.layers.pop();
  274. layer?.dispose();
  275. }
  276. }
  277. }