flamegraphRenderer.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. import {mat3, vec2} from 'gl-matrix';
  2. import {Flamegraph} from '../flamegraph';
  3. import {FlamegraphSearch} from '../flamegraph/flamegraphStateProvider/flamegraphSearch';
  4. import {FlamegraphTheme} from '../flamegraph/flamegraphTheme';
  5. import {FlamegraphFrame, getFlamegraphFrameSearchId} from '../flamegraphFrame';
  6. import {
  7. createProgram,
  8. createShader,
  9. getContext,
  10. makeProjectionMatrix,
  11. Rect,
  12. resizeCanvasToDisplaySize,
  13. } from '../gl/utils';
  14. import {fragment, vertex} from './shaders';
  15. class FlamegraphRenderer {
  16. canvas: HTMLCanvasElement | null;
  17. flamegraph: Flamegraph;
  18. gl: WebGLRenderingContext | null = null;
  19. program: WebGLProgram | null = null;
  20. theme: FlamegraphTheme;
  21. frames: ReadonlyArray<FlamegraphFrame> = [];
  22. roots: ReadonlyArray<FlamegraphFrame> = [];
  23. // Vertex and color buffer
  24. positions: Array<number> = [];
  25. bounds: Array<number> = [];
  26. colors: Array<number> = [];
  27. colorMap: Map<string | number, number[]> = new Map();
  28. lastDragPosition: vec2 | null = null;
  29. attributes: {
  30. a_bounds: number | null;
  31. a_color: number | null;
  32. a_position: number | null;
  33. } = {
  34. a_position: null,
  35. a_color: null,
  36. a_bounds: null,
  37. };
  38. uniforms: {
  39. u_border_width: WebGLUniformLocation | null;
  40. u_draw_border: WebGLUniformLocation | null;
  41. u_is_search_result: WebGLUniformLocation | null;
  42. u_model: WebGLUniformLocation | null;
  43. u_projection: WebGLUniformLocation | null;
  44. } = {
  45. u_border_width: null,
  46. u_draw_border: null,
  47. u_is_search_result: null,
  48. u_model: null,
  49. u_projection: null,
  50. };
  51. options: {
  52. draw_border: boolean;
  53. };
  54. constructor(
  55. canvas: HTMLCanvasElement,
  56. flamegraph: Flamegraph,
  57. theme: FlamegraphTheme,
  58. options: {draw_border: boolean} = {draw_border: false}
  59. ) {
  60. this.flamegraph = flamegraph;
  61. this.canvas = canvas;
  62. this.theme = theme;
  63. this.options = options;
  64. this.init();
  65. }
  66. init(): void {
  67. const VERTICES = 6;
  68. const COLOR_COMPONENTS = 4;
  69. this.colors = new Array(VERTICES * COLOR_COMPONENTS);
  70. this.frames = [...this.flamegraph.frames];
  71. this.roots = [...this.flamegraph.root.children];
  72. // Generate colors for the flamegraph
  73. const {colorBuffer, colorMap} = this.theme.COLORS.STACK_TO_COLOR(
  74. this.frames,
  75. this.theme.COLORS.COLOR_MAP,
  76. this.theme.COLORS.COLOR_BUCKET
  77. );
  78. this.colorMap = colorMap;
  79. this.colors = colorBuffer;
  80. this.initCanvasContext();
  81. this.initVertices();
  82. this.initShaders();
  83. }
  84. initVertices(): void {
  85. const POSITIONS_PER_PASS = 2;
  86. const BOUNDS_PER_PASS = 4;
  87. const VERTICES = 6;
  88. this.bounds = new Array(VERTICES * BOUNDS_PER_PASS * this.frames.length);
  89. this.positions = new Array(VERTICES * POSITIONS_PER_PASS * this.frames.length);
  90. const length = this.frames.length;
  91. for (let index = 0; index < length; index++) {
  92. const frame = this.frames[index];
  93. const x1 = frame.start;
  94. const x2 = frame.end;
  95. const y1 = frame.depth;
  96. const y2 = frame.depth + 1;
  97. // top left -> top right -> bottom left ->
  98. // bottom left -> top right -> bottom right
  99. const positionOffset = index * 12;
  100. this.positions[positionOffset] = x1;
  101. this.positions[positionOffset + 1] = y1;
  102. this.positions[positionOffset + 2] = x2;
  103. this.positions[positionOffset + 3] = y1;
  104. this.positions[positionOffset + 4] = x1;
  105. this.positions[positionOffset + 5] = y2;
  106. this.positions[positionOffset + 6] = x1;
  107. this.positions[positionOffset + 7] = y2;
  108. this.positions[positionOffset + 8] = x2;
  109. this.positions[positionOffset + 9] = y1;
  110. this.positions[positionOffset + 10] = x2;
  111. this.positions[positionOffset + 11] = y2;
  112. // @TODO check if we can pack bounds across vertex calls,
  113. // we are allocating 6x the amount of memory here
  114. const boundsOffset = index * VERTICES * BOUNDS_PER_PASS;
  115. for (let i = 0; i < VERTICES; i++) {
  116. const offset = boundsOffset + i * BOUNDS_PER_PASS;
  117. this.bounds[offset] = x1;
  118. this.bounds[offset + 1] = y1;
  119. this.bounds[offset + 2] = x2;
  120. this.bounds[offset + 3] = y2;
  121. }
  122. }
  123. }
  124. initCanvasContext(): void {
  125. if (!this.canvas) {
  126. throw new Error('Cannot initialize context from null canvas');
  127. }
  128. // Setup webgl canvas context
  129. this.gl = getContext(this.canvas, 'webgl');
  130. if (!this.gl) {
  131. throw new Error('Uninitialized WebGL context');
  132. }
  133. this.gl.enable(this.gl.BLEND);
  134. this.gl.blendFuncSeparate(
  135. this.gl.SRC_ALPHA,
  136. this.gl.ONE_MINUS_SRC_ALPHA,
  137. this.gl.ONE,
  138. this.gl.ONE_MINUS_SRC_ALPHA
  139. );
  140. resizeCanvasToDisplaySize(this.canvas);
  141. }
  142. initShaders(): void {
  143. if (!this.gl) {
  144. throw new Error('Uninitialized WebGL context');
  145. }
  146. // @ts-ignore
  147. this.uniforms = {};
  148. // @ts-ignore
  149. this.attributes = {};
  150. const vertexShader = createShader(this.gl, this.gl.VERTEX_SHADER, vertex());
  151. const fragmentShader = createShader(
  152. this.gl,
  153. this.gl.FRAGMENT_SHADER,
  154. fragment(this.theme)
  155. );
  156. // create program
  157. this.program = createProgram(this.gl, vertexShader, fragmentShader);
  158. const uProjectionMatrix = this.gl.getUniformLocation(this.program, 'u_projection');
  159. const uModelMatrix = this.gl.getUniformLocation(this.program, 'u_model');
  160. const uIsSearchResult = this.gl.getUniformLocation(
  161. this.program,
  162. 'u_is_search_result'
  163. );
  164. const uBorderWidth = this.gl.getUniformLocation(this.program, 'u_border_width');
  165. const uDrawBorder = this.gl.getUniformLocation(this.program, 'u_draw_border');
  166. if (!uProjectionMatrix) {
  167. throw new Error('Could not locate u_projection in shader');
  168. }
  169. if (!uModelMatrix) {
  170. throw new Error('Could not locate u_model in shader');
  171. }
  172. if (!uIsSearchResult) {
  173. throw new Error('Could not locate u_is_search_result in shader');
  174. }
  175. if (!uBorderWidth) {
  176. throw new Error('Could not locate u_border_width in shader');
  177. }
  178. if (!uDrawBorder) {
  179. throw new Error('Could not locate u_draw_border in shader');
  180. }
  181. this.uniforms.u_projection = uProjectionMatrix;
  182. this.uniforms.u_model = uModelMatrix;
  183. this.uniforms.u_is_search_result = uIsSearchResult;
  184. this.uniforms.u_border_width = uBorderWidth;
  185. this.uniforms.u_draw_border = uDrawBorder;
  186. {
  187. const aColorAttributeLocation = this.gl.getAttribLocation(this.program, 'a_color');
  188. if (aColorAttributeLocation === -1) {
  189. throw new Error('Could not locate a_color in shader');
  190. }
  191. // attributes get data from buffers
  192. this.attributes.a_color = aColorAttributeLocation;
  193. // Init color buffer
  194. const colorBuffer = this.gl.createBuffer();
  195. // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = colorBuffer)
  196. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, colorBuffer);
  197. this.gl.bufferData(
  198. this.gl.ARRAY_BUFFER,
  199. new Float32Array(this.colors),
  200. this.gl.STATIC_DRAW
  201. );
  202. const size = 4;
  203. const type = this.gl.FLOAT;
  204. const normalize = false;
  205. const stride = 0;
  206. const offset = 0;
  207. this.gl.vertexAttribPointer(
  208. aColorAttributeLocation,
  209. size,
  210. type,
  211. normalize,
  212. stride,
  213. offset
  214. );
  215. // Point to attribute location
  216. this.gl.enableVertexAttribArray(aColorAttributeLocation);
  217. }
  218. {
  219. // look up where the vertex data needs to go.
  220. const aPositionAttributeLocation = this.gl.getAttribLocation(
  221. this.program,
  222. 'a_position'
  223. );
  224. if (aPositionAttributeLocation === -1) {
  225. throw new Error('Could not locate a_color in shader');
  226. }
  227. // attributes get data from buffers
  228. this.attributes.a_position = aPositionAttributeLocation;
  229. // Init position buffer
  230. const positionBuffer = this.gl.createBuffer();
  231. // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer)
  232. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer);
  233. this.gl.bufferData(
  234. this.gl.ARRAY_BUFFER,
  235. new Float32Array(this.positions),
  236. this.gl.STATIC_DRAW
  237. );
  238. const size = 2;
  239. const type = this.gl.FLOAT;
  240. const normalize = false;
  241. const stride = 0;
  242. const offset = 0;
  243. this.gl.vertexAttribPointer(
  244. aPositionAttributeLocation,
  245. size,
  246. type,
  247. normalize,
  248. stride,
  249. offset
  250. );
  251. // Point to attribute location
  252. this.gl.enableVertexAttribArray(aPositionAttributeLocation);
  253. }
  254. {
  255. // look up where the bounds vertices needs to go.
  256. const aBoundsAttributeLocation = this.gl.getAttribLocation(
  257. this.program,
  258. 'a_bounds'
  259. );
  260. if (aBoundsAttributeLocation === -1) {
  261. throw new Error('Could not locate a_color in shader');
  262. }
  263. // attributes get data from buffers
  264. this.attributes.a_bounds = aBoundsAttributeLocation;
  265. // Init bounds buffer
  266. const boundsBuffer = this.gl.createBuffer();
  267. // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = boundsBuffer)
  268. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, boundsBuffer);
  269. this.gl.bufferData(
  270. this.gl.ARRAY_BUFFER,
  271. new Float32Array(this.bounds),
  272. this.gl.STATIC_DRAW
  273. );
  274. const size = 4;
  275. const type = this.gl.FLOAT;
  276. const normalize = false;
  277. const stride = 0;
  278. const offset = 0;
  279. this.gl.vertexAttribPointer(
  280. aBoundsAttributeLocation,
  281. size,
  282. type,
  283. normalize,
  284. stride,
  285. offset
  286. );
  287. // Point to attribute location
  288. this.gl.enableVertexAttribArray(aBoundsAttributeLocation);
  289. }
  290. // Use shader program
  291. this.gl.useProgram(this.program);
  292. }
  293. getColorForFrame(frame: FlamegraphFrame): number[] {
  294. return this.colorMap.get(frame.key) ?? this.theme.COLORS.FRAME_FALLBACK_COLOR;
  295. }
  296. getHoveredNode(configSpaceCursor: vec2): FlamegraphFrame | null {
  297. let hoveredNode: FlamegraphFrame | null = null;
  298. const findHoveredNode = (frame: FlamegraphFrame, depth: number) => {
  299. // This is outside
  300. if (hoveredNode) {
  301. return;
  302. }
  303. const frameRect = new Rect(frame.start, frame.depth, frame.end - frame.start, 1);
  304. // We treat entire flamegraph as a segment tree, this allows us to query in O(log n) time by
  305. // only looking at the nodes that are relevant to the current cursor position. We discard any values
  306. // on x axis that do not overlap the cursor, and descend until we find a node that overlaps at cursor y position
  307. if (!frameRect.containsX(configSpaceCursor)) {
  308. return;
  309. }
  310. // If our frame depth overlaps cursor y position, we have found our node
  311. if (frameRect.containsY(configSpaceCursor)) {
  312. hoveredNode = frame;
  313. return;
  314. }
  315. // Descend into the rest of the children
  316. for (let i = 0; i < frame.children.length; i++) {
  317. findHoveredNode(frame.children[i], depth + 1);
  318. }
  319. };
  320. for (let i = 0; i < this.roots.length; i++) {
  321. findHoveredNode(this.roots[i], 0);
  322. }
  323. return hoveredNode;
  324. }
  325. draw(
  326. configViewToPhysicalSpace: mat3,
  327. searchResults: FlamegraphSearch['results']
  328. ): void {
  329. if (!this.gl) {
  330. throw new Error('Uninitialized WebGL context');
  331. }
  332. this.gl.clearColor(0, 0, 0, 0);
  333. this.gl.clear(this.gl.COLOR_BUFFER_BIT);
  334. // We have no frames to draw
  335. if (!this.positions.length) {
  336. return;
  337. }
  338. this.gl.useProgram(this.program);
  339. const projectionMatrix = makeProjectionMatrix(
  340. this.gl.canvas.width,
  341. this.gl.canvas.height
  342. );
  343. // Projection matrix
  344. this.gl.uniformMatrix3fv(this.uniforms.u_projection, false, projectionMatrix);
  345. // Model to projection
  346. this.gl.uniformMatrix3fv(this.uniforms.u_model, false, configViewToPhysicalSpace);
  347. // Check if we should draw border
  348. this.gl.uniform1i(this.uniforms.u_draw_border, this.options.draw_border ? 1 : 0);
  349. // Tell webgl to convert clip space to px
  350. this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
  351. const physicalSpacePixel = new Rect(0, 0, 1, 1);
  352. const physicalToConfig = mat3.invert(mat3.create(), configViewToPhysicalSpace);
  353. const configSpacePixel = physicalSpacePixel.transformRect(physicalToConfig);
  354. this.gl.uniform2f(
  355. this.uniforms.u_border_width,
  356. configSpacePixel.width,
  357. configSpacePixel.height
  358. );
  359. const VERTICES = 6;
  360. const length = this.frames.length;
  361. let frame: FlamegraphFrame | null;
  362. // This is an optimization to avoid setting uniform1i for each draw call when user is not searching
  363. if (searchResults.size > 0) {
  364. for (let i = 0; i < length; i++) {
  365. frame = this.frames[i];
  366. const vertexOffset = i * VERTICES;
  367. this.gl.uniform1i(
  368. this.uniforms.u_is_search_result,
  369. searchResults.has(getFlamegraphFrameSearchId(frame)) ? 1 : 0
  370. );
  371. this.gl.drawArrays(this.gl.TRIANGLES, vertexOffset, VERTICES);
  372. }
  373. } else {
  374. this.gl.uniform1i(this.uniforms.u_is_search_result, 0);
  375. for (let i = 0; i < length; i++) {
  376. const vertexOffset = i * VERTICES;
  377. this.gl.drawArrays(this.gl.TRIANGLES, vertexOffset, VERTICES);
  378. }
  379. }
  380. }
  381. }
  382. export {FlamegraphRenderer};