LabelCollection.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. import BoundingRectangle from "../Core/BoundingRectangle.js";
  2. import Cartesian2 from "../Core/Cartesian2.js";
  3. import Color from "../Core/Color.js";
  4. import defaultValue from "../Core/defaultValue.js";
  5. import defined from "../Core/defined.js";
  6. import destroyObject from "../Core/destroyObject.js";
  7. import DeveloperError from "../Core/DeveloperError.js";
  8. import Matrix4 from "../Core/Matrix4.js";
  9. import writeTextToCanvas from "../Core/writeTextToCanvas.js";
  10. import bitmapSDF from "../ThirdParty/bitmap-sdf.js";
  11. import BillboardCollection from "./BillboardCollection.js";
  12. import BlendOption from "./BlendOption.js";
  13. import HeightReference from "./HeightReference.js";
  14. import HorizontalOrigin from "./HorizontalOrigin.js";
  15. import Label from "./Label.js";
  16. import LabelStyle from "./LabelStyle.js";
  17. import SDFSettings from "./SDFSettings.js";
  18. import TextureAtlas from "./TextureAtlas.js";
  19. import VerticalOrigin from "./VerticalOrigin.js";
  20. import GraphemeSplitter from "../ThirdParty/graphemesplitter.js";
  21. // A glyph represents a single character in a particular label. It may or may
  22. // not have a billboard, depending on whether the texture info has an index into
  23. // the the label collection's texture atlas. Invisible characters have no texture, and
  24. // no billboard. However, it always has a valid dimensions object.
  25. function Glyph() {
  26. this.textureInfo = undefined;
  27. this.dimensions = undefined;
  28. this.billboard = undefined;
  29. }
  30. // GlyphTextureInfo represents a single character, drawn in a particular style,
  31. // shared and reference counted across all labels. It may or may not have an
  32. // index into the label collection's texture atlas, depending on whether the character
  33. // has both width and height, but it always has a valid dimensions object.
  34. function GlyphTextureInfo(labelCollection, index, dimensions) {
  35. this.labelCollection = labelCollection;
  36. this.index = index;
  37. this.dimensions = dimensions;
  38. }
  39. // Traditionally, leading is %20 of the font size.
  40. var defaultLineSpacingPercent = 1.2;
  41. var whitePixelCanvasId = "ID_WHITE_PIXEL";
  42. var whitePixelSize = new Cartesian2(4, 4);
  43. var whitePixelBoundingRegion = new BoundingRectangle(1, 1, 1, 1);
  44. function addWhitePixelCanvas(textureAtlas, labelCollection) {
  45. var canvas = document.createElement("canvas");
  46. canvas.width = whitePixelSize.x;
  47. canvas.height = whitePixelSize.y;
  48. var context2D = canvas.getContext("2d");
  49. context2D.fillStyle = "#fff";
  50. context2D.fillRect(0, 0, canvas.width, canvas.height);
  51. textureAtlas.addImage(whitePixelCanvasId, canvas).then(function (index) {
  52. labelCollection._whitePixelIndex = index;
  53. });
  54. }
  55. // reusable object for calling writeTextToCanvas
  56. var writeTextToCanvasParameters = {};
  57. function createGlyphCanvas(
  58. character,
  59. font,
  60. fillColor,
  61. outlineColor,
  62. outlineWidth,
  63. style,
  64. verticalOrigin
  65. ) {
  66. writeTextToCanvasParameters.font = font;
  67. writeTextToCanvasParameters.fillColor = fillColor;
  68. writeTextToCanvasParameters.strokeColor = outlineColor;
  69. writeTextToCanvasParameters.strokeWidth = outlineWidth;
  70. // Setting the padding to something bigger is necessary to get enough space for the outlining.
  71. writeTextToCanvasParameters.padding = SDFSettings.PADDING;
  72. if (verticalOrigin === VerticalOrigin.CENTER) {
  73. writeTextToCanvasParameters.textBaseline = "middle";
  74. } else if (verticalOrigin === VerticalOrigin.TOP) {
  75. writeTextToCanvasParameters.textBaseline = "top";
  76. } else {
  77. // VerticalOrigin.BOTTOM and VerticalOrigin.BASELINE
  78. writeTextToCanvasParameters.textBaseline = "bottom";
  79. }
  80. writeTextToCanvasParameters.fill =
  81. style === LabelStyle.FILL || style === LabelStyle.FILL_AND_OUTLINE;
  82. writeTextToCanvasParameters.stroke =
  83. style === LabelStyle.OUTLINE || style === LabelStyle.FILL_AND_OUTLINE;
  84. writeTextToCanvasParameters.backgroundColor = Color.BLACK;
  85. return writeTextToCanvas(character, writeTextToCanvasParameters);
  86. }
  87. function unbindGlyph(labelCollection, glyph) {
  88. glyph.textureInfo = undefined;
  89. glyph.dimensions = undefined;
  90. var billboard = glyph.billboard;
  91. if (defined(billboard)) {
  92. billboard.show = false;
  93. billboard.image = undefined;
  94. if (defined(billboard._removeCallbackFunc)) {
  95. billboard._removeCallbackFunc();
  96. billboard._removeCallbackFunc = undefined;
  97. }
  98. labelCollection._spareBillboards.push(billboard);
  99. glyph.billboard = undefined;
  100. }
  101. }
  102. function addGlyphToTextureAtlas(textureAtlas, id, canvas, glyphTextureInfo) {
  103. textureAtlas.addImage(id, canvas).then(function (index) {
  104. glyphTextureInfo.index = index;
  105. });
  106. }
  107. var splitter = new GraphemeSplitter();
  108. function rebindAllGlyphs(labelCollection, label) {
  109. var text = label._renderedText;
  110. var graphemes = splitter.splitGraphemes(text);
  111. var textLength = graphemes.length;
  112. var glyphs = label._glyphs;
  113. var glyphsLength = glyphs.length;
  114. var glyph;
  115. var glyphIndex;
  116. var textIndex;
  117. // Compute a font size scale relative to the sdf font generated size.
  118. label._relativeSize = label._fontSize / SDFSettings.FONT_SIZE;
  119. // if we have more glyphs than needed, unbind the extras.
  120. if (textLength < glyphsLength) {
  121. for (glyphIndex = textLength; glyphIndex < glyphsLength; ++glyphIndex) {
  122. unbindGlyph(labelCollection, glyphs[glyphIndex]);
  123. }
  124. }
  125. // presize glyphs to match the new text length
  126. glyphs.length = textLength;
  127. var showBackground =
  128. label._showBackground && text.split("\n").join("").length > 0;
  129. var backgroundBillboard = label._backgroundBillboard;
  130. var backgroundBillboardCollection =
  131. labelCollection._backgroundBillboardCollection;
  132. if (!showBackground) {
  133. if (defined(backgroundBillboard)) {
  134. backgroundBillboardCollection.remove(backgroundBillboard);
  135. label._backgroundBillboard = backgroundBillboard = undefined;
  136. }
  137. } else {
  138. if (!defined(backgroundBillboard)) {
  139. backgroundBillboard = backgroundBillboardCollection.add({
  140. collection: labelCollection,
  141. image: whitePixelCanvasId,
  142. imageSubRegion: whitePixelBoundingRegion,
  143. });
  144. label._backgroundBillboard = backgroundBillboard;
  145. }
  146. backgroundBillboard.color = label._backgroundColor;
  147. backgroundBillboard.show = label._show;
  148. backgroundBillboard.position = label._position;
  149. backgroundBillboard.eyeOffset = label._eyeOffset;
  150. backgroundBillboard.pixelOffset = label._pixelOffset;
  151. backgroundBillboard.horizontalOrigin = HorizontalOrigin.LEFT;
  152. backgroundBillboard.verticalOrigin = label._verticalOrigin;
  153. backgroundBillboard.heightReference = label._heightReference;
  154. backgroundBillboard.scale = label.totalScale;
  155. backgroundBillboard.pickPrimitive = label;
  156. backgroundBillboard.id = label._id;
  157. backgroundBillboard.translucencyByDistance = label._translucencyByDistance;
  158. backgroundBillboard.pixelOffsetScaleByDistance =
  159. label._pixelOffsetScaleByDistance;
  160. backgroundBillboard.scaleByDistance = label._scaleByDistance;
  161. backgroundBillboard.distanceDisplayCondition =
  162. label._distanceDisplayCondition;
  163. backgroundBillboard.disableDepthTestDistance =
  164. label._disableDepthTestDistance;
  165. }
  166. var glyphTextureCache = labelCollection._glyphTextureCache;
  167. // walk the text looking for new characters (creating new glyphs for each)
  168. // or changed characters (rebinding existing glyphs)
  169. for (textIndex = 0; textIndex < textLength; ++textIndex) {
  170. var character = graphemes[textIndex];
  171. var verticalOrigin = label._verticalOrigin;
  172. var id = JSON.stringify([
  173. character,
  174. label._fontFamily,
  175. label._fontStyle,
  176. label._fontWeight,
  177. +verticalOrigin,
  178. ]);
  179. var glyphTextureInfo = glyphTextureCache[id];
  180. if (!defined(glyphTextureInfo)) {
  181. var glyphFont =
  182. label._fontStyle +
  183. " " +
  184. label._fontWeight +
  185. " " +
  186. SDFSettings.FONT_SIZE +
  187. "px " +
  188. label._fontFamily;
  189. var canvas = createGlyphCanvas(
  190. character,
  191. glyphFont,
  192. Color.WHITE,
  193. Color.WHITE,
  194. 0.0,
  195. LabelStyle.FILL,
  196. verticalOrigin
  197. );
  198. glyphTextureInfo = new GlyphTextureInfo(
  199. labelCollection,
  200. -1,
  201. canvas.dimensions
  202. );
  203. glyphTextureCache[id] = glyphTextureInfo;
  204. if (canvas.width > 0 && canvas.height > 0) {
  205. var sdfValues = bitmapSDF(canvas, {
  206. cutoff: SDFSettings.CUTOFF,
  207. radius: SDFSettings.RADIUS,
  208. });
  209. var ctx = canvas.getContext("2d");
  210. var canvasWidth = canvas.width;
  211. var canvasHeight = canvas.height;
  212. var imgData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
  213. for (var i = 0; i < canvasWidth; i++) {
  214. for (var j = 0; j < canvasHeight; j++) {
  215. var baseIndex = j * canvasWidth + i;
  216. var alpha = sdfValues[baseIndex] * 255;
  217. var imageIndex = baseIndex * 4;
  218. imgData.data[imageIndex + 0] = alpha;
  219. imgData.data[imageIndex + 1] = alpha;
  220. imgData.data[imageIndex + 2] = alpha;
  221. imgData.data[imageIndex + 3] = alpha;
  222. }
  223. }
  224. ctx.putImageData(imgData, 0, 0);
  225. if (character !== " ") {
  226. addGlyphToTextureAtlas(
  227. labelCollection._textureAtlas,
  228. id,
  229. canvas,
  230. glyphTextureInfo
  231. );
  232. }
  233. }
  234. }
  235. glyph = glyphs[textIndex];
  236. if (defined(glyph)) {
  237. // clean up leftover information from the previous glyph
  238. if (glyphTextureInfo.index === -1) {
  239. // no texture, and therefore no billboard, for this glyph.
  240. // so, completely unbind glyph.
  241. unbindGlyph(labelCollection, glyph);
  242. } else if (defined(glyph.textureInfo)) {
  243. // we have a texture and billboard. If we had one before, release
  244. // our reference to that texture info, but reuse the billboard.
  245. glyph.textureInfo = undefined;
  246. }
  247. } else {
  248. // create a glyph object
  249. glyph = new Glyph();
  250. glyphs[textIndex] = glyph;
  251. }
  252. glyph.textureInfo = glyphTextureInfo;
  253. glyph.dimensions = glyphTextureInfo.dimensions;
  254. // if we have a texture, configure the existing billboard, or obtain one
  255. if (glyphTextureInfo.index !== -1) {
  256. var billboard = glyph.billboard;
  257. var spareBillboards = labelCollection._spareBillboards;
  258. if (!defined(billboard)) {
  259. if (spareBillboards.length > 0) {
  260. billboard = spareBillboards.pop();
  261. } else {
  262. billboard = labelCollection._billboardCollection.add({
  263. collection: labelCollection,
  264. });
  265. billboard._labelDimensions = new Cartesian2();
  266. billboard._labelTranslate = new Cartesian2();
  267. }
  268. glyph.billboard = billboard;
  269. }
  270. billboard.show = label._show;
  271. billboard.position = label._position;
  272. billboard.eyeOffset = label._eyeOffset;
  273. billboard.pixelOffset = label._pixelOffset;
  274. billboard.horizontalOrigin = HorizontalOrigin.LEFT;
  275. billboard.verticalOrigin = label._verticalOrigin;
  276. billboard.heightReference = label._heightReference;
  277. billboard.scale = label.totalScale;
  278. billboard.pickPrimitive = label;
  279. billboard.id = label._id;
  280. billboard.image = id;
  281. billboard.translucencyByDistance = label._translucencyByDistance;
  282. billboard.pixelOffsetScaleByDistance = label._pixelOffsetScaleByDistance;
  283. billboard.scaleByDistance = label._scaleByDistance;
  284. billboard.distanceDisplayCondition = label._distanceDisplayCondition;
  285. billboard.disableDepthTestDistance = label._disableDepthTestDistance;
  286. billboard._batchIndex = label._batchIndex;
  287. billboard.outlineColor = label.outlineColor;
  288. if (label.style === LabelStyle.FILL_AND_OUTLINE) {
  289. billboard.color = label._fillColor;
  290. billboard.outlineWidth = label.outlineWidth;
  291. } else if (label.style === LabelStyle.FILL) {
  292. billboard.color = label._fillColor;
  293. billboard.outlineWidth = 0.0;
  294. } else if (label.style === LabelStyle.OUTLINE) {
  295. billboard.color = Color.TRANSPARENT;
  296. billboard.outlineWidth = label.outlineWidth;
  297. }
  298. }
  299. }
  300. // changing glyphs will cause the position of the
  301. // glyphs to change, since different characters have different widths
  302. label._repositionAllGlyphs = true;
  303. }
  304. function calculateWidthOffset(lineWidth, horizontalOrigin, backgroundPadding) {
  305. if (horizontalOrigin === HorizontalOrigin.CENTER) {
  306. return -lineWidth / 2;
  307. } else if (horizontalOrigin === HorizontalOrigin.RIGHT) {
  308. return -(lineWidth + backgroundPadding.x);
  309. }
  310. return backgroundPadding.x;
  311. }
  312. // reusable Cartesian2 instances
  313. var glyphPixelOffset = new Cartesian2();
  314. var scratchBackgroundPadding = new Cartesian2();
  315. function repositionAllGlyphs(label) {
  316. var glyphs = label._glyphs;
  317. var text = label._renderedText;
  318. var glyph;
  319. var dimensions;
  320. var lastLineWidth = 0;
  321. var maxLineWidth = 0;
  322. var lineWidths = [];
  323. var maxGlyphDescent = Number.NEGATIVE_INFINITY;
  324. var maxGlyphY = 0;
  325. var numberOfLines = 1;
  326. var glyphIndex;
  327. var glyphLength = glyphs.length;
  328. var backgroundBillboard = label._backgroundBillboard;
  329. var backgroundPadding = Cartesian2.clone(
  330. defined(backgroundBillboard) ? label._backgroundPadding : Cartesian2.ZERO,
  331. scratchBackgroundPadding
  332. );
  333. // We need to scale the background padding, which is specified in pixels by the inverse of the relative size so it is scaled properly.
  334. backgroundPadding.x /= label._relativeSize;
  335. backgroundPadding.y /= label._relativeSize;
  336. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  337. if (text.charAt(glyphIndex) === "\n") {
  338. lineWidths.push(lastLineWidth);
  339. ++numberOfLines;
  340. lastLineWidth = 0;
  341. } else {
  342. glyph = glyphs[glyphIndex];
  343. dimensions = glyph.dimensions;
  344. maxGlyphY = Math.max(maxGlyphY, dimensions.height - dimensions.descent);
  345. maxGlyphDescent = Math.max(maxGlyphDescent, dimensions.descent);
  346. //Computing the line width must also account for the kerning that occurs between letters.
  347. lastLineWidth += dimensions.width - dimensions.bounds.minx;
  348. if (glyphIndex < glyphLength - 1) {
  349. lastLineWidth += glyphs[glyphIndex + 1].dimensions.bounds.minx;
  350. }
  351. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  352. }
  353. }
  354. lineWidths.push(lastLineWidth);
  355. var maxLineHeight = maxGlyphY + maxGlyphDescent;
  356. var scale = label.totalScale;
  357. var horizontalOrigin = label._horizontalOrigin;
  358. var verticalOrigin = label._verticalOrigin;
  359. var lineIndex = 0;
  360. var lineWidth = lineWidths[lineIndex];
  361. var widthOffset = calculateWidthOffset(
  362. lineWidth,
  363. horizontalOrigin,
  364. backgroundPadding
  365. );
  366. var lineSpacing = defaultLineSpacingPercent * maxLineHeight;
  367. var otherLinesHeight = lineSpacing * (numberOfLines - 1);
  368. var totalLineWidth = maxLineWidth;
  369. var totalLineHeight = maxLineHeight + otherLinesHeight;
  370. if (defined(backgroundBillboard)) {
  371. totalLineWidth += backgroundPadding.x * 2;
  372. totalLineHeight += backgroundPadding.y * 2;
  373. backgroundBillboard._labelHorizontalOrigin = horizontalOrigin;
  374. }
  375. glyphPixelOffset.x = widthOffset * scale;
  376. glyphPixelOffset.y = 0;
  377. var firstCharOfLine = true;
  378. var lineOffsetY = 0;
  379. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  380. if (text.charAt(glyphIndex) === "\n") {
  381. ++lineIndex;
  382. lineOffsetY += lineSpacing;
  383. lineWidth = lineWidths[lineIndex];
  384. widthOffset = calculateWidthOffset(
  385. lineWidth,
  386. horizontalOrigin,
  387. backgroundPadding
  388. );
  389. glyphPixelOffset.x = widthOffset * scale;
  390. firstCharOfLine = true;
  391. } else {
  392. glyph = glyphs[glyphIndex];
  393. dimensions = glyph.dimensions;
  394. if (verticalOrigin === VerticalOrigin.TOP) {
  395. glyphPixelOffset.y =
  396. dimensions.height - maxGlyphY - backgroundPadding.y;
  397. glyphPixelOffset.y += SDFSettings.PADDING;
  398. } else if (verticalOrigin === VerticalOrigin.CENTER) {
  399. glyphPixelOffset.y =
  400. (otherLinesHeight + dimensions.height - maxGlyphY) / 2;
  401. } else if (verticalOrigin === VerticalOrigin.BASELINE) {
  402. glyphPixelOffset.y = otherLinesHeight;
  403. glyphPixelOffset.y -= SDFSettings.PADDING;
  404. } else {
  405. // VerticalOrigin.BOTTOM
  406. glyphPixelOffset.y =
  407. otherLinesHeight + maxGlyphDescent + backgroundPadding.y;
  408. glyphPixelOffset.y -= SDFSettings.PADDING;
  409. }
  410. glyphPixelOffset.y =
  411. (glyphPixelOffset.y - dimensions.descent - lineOffsetY) * scale;
  412. // Handle any offsets for the first character of the line since the bounds might not be right on the bottom left pixel.
  413. if (firstCharOfLine) {
  414. glyphPixelOffset.x -= SDFSettings.PADDING * scale;
  415. firstCharOfLine = false;
  416. }
  417. if (defined(glyph.billboard)) {
  418. glyph.billboard._setTranslate(glyphPixelOffset);
  419. glyph.billboard._labelDimensions.x = totalLineWidth;
  420. glyph.billboard._labelDimensions.y = totalLineHeight;
  421. glyph.billboard._labelHorizontalOrigin = horizontalOrigin;
  422. }
  423. //Compute the next x offset taking into account the kerning performed
  424. //on both the current letter as well as the next letter to be drawn
  425. //as well as any applied scale.
  426. if (glyphIndex < glyphLength - 1) {
  427. var nextGlyph = glyphs[glyphIndex + 1];
  428. glyphPixelOffset.x +=
  429. (dimensions.width -
  430. dimensions.bounds.minx +
  431. nextGlyph.dimensions.bounds.minx) *
  432. scale;
  433. }
  434. }
  435. }
  436. if (defined(backgroundBillboard) && text.split("\n").join("").length > 0) {
  437. if (horizontalOrigin === HorizontalOrigin.CENTER) {
  438. widthOffset = -maxLineWidth / 2 - backgroundPadding.x;
  439. } else if (horizontalOrigin === HorizontalOrigin.RIGHT) {
  440. widthOffset = -(maxLineWidth + backgroundPadding.x * 2);
  441. } else {
  442. widthOffset = 0;
  443. }
  444. glyphPixelOffset.x = widthOffset * scale;
  445. if (verticalOrigin === VerticalOrigin.TOP) {
  446. glyphPixelOffset.y = maxLineHeight - maxGlyphY - maxGlyphDescent;
  447. } else if (verticalOrigin === VerticalOrigin.CENTER) {
  448. glyphPixelOffset.y = (maxLineHeight - maxGlyphY) / 2 - maxGlyphDescent;
  449. } else if (verticalOrigin === VerticalOrigin.BASELINE) {
  450. glyphPixelOffset.y = -backgroundPadding.y - maxGlyphDescent;
  451. } else {
  452. // VerticalOrigin.BOTTOM
  453. glyphPixelOffset.y = 0;
  454. }
  455. glyphPixelOffset.y = glyphPixelOffset.y * scale;
  456. backgroundBillboard.width = totalLineWidth;
  457. backgroundBillboard.height = totalLineHeight;
  458. backgroundBillboard._setTranslate(glyphPixelOffset);
  459. backgroundBillboard._labelTranslate = Cartesian2.clone(
  460. glyphPixelOffset,
  461. backgroundBillboard._labelTranslate
  462. );
  463. }
  464. if (label.heightReference === HeightReference.CLAMP_TO_GROUND) {
  465. for (glyphIndex = 0; glyphIndex < glyphLength; ++glyphIndex) {
  466. glyph = glyphs[glyphIndex];
  467. var billboard = glyph.billboard;
  468. if (defined(billboard)) {
  469. billboard._labelTranslate = Cartesian2.clone(
  470. glyphPixelOffset,
  471. billboard._labelTranslate
  472. );
  473. }
  474. }
  475. }
  476. }
  477. function destroyLabel(labelCollection, label) {
  478. var glyphs = label._glyphs;
  479. for (var i = 0, len = glyphs.length; i < len; ++i) {
  480. unbindGlyph(labelCollection, glyphs[i]);
  481. }
  482. if (defined(label._backgroundBillboard)) {
  483. labelCollection._backgroundBillboardCollection.remove(
  484. label._backgroundBillboard
  485. );
  486. label._backgroundBillboard = undefined;
  487. }
  488. label._labelCollection = undefined;
  489. if (defined(label._removeCallbackFunc)) {
  490. label._removeCallbackFunc();
  491. }
  492. destroyObject(label);
  493. }
  494. /**
  495. * A renderable collection of labels. Labels are viewport-aligned text positioned in the 3D scene.
  496. * Each label can have a different font, color, scale, etc.
  497. * <br /><br />
  498. * <div align='center'>
  499. * <img src='Images/Label.png' width='400' height='300' /><br />
  500. * Example labels
  501. * </div>
  502. * <br /><br />
  503. * Labels are added and removed from the collection using {@link LabelCollection#add}
  504. * and {@link LabelCollection#remove}.
  505. *
  506. * @alias LabelCollection
  507. * @constructor
  508. *
  509. * @param {Object} [options] Object with the following properties:
  510. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms each label from model to world coordinates.
  511. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Determines if this primitive's commands' bounding spheres are shown.
  512. * @param {Scene} [options.scene] Must be passed in for labels that use the height reference property or will be depth tested against the globe.
  513. * @param {BlendOption} [options.blendOption=BlendOption.OPAQUE_AND_TRANSLUCENT] The label blending option. The default
  514. * is used for rendering both opaque and translucent labels. However, if either all of the labels are completely opaque or all are completely translucent,
  515. * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve performance by up to 2x.
  516. *
  517. * @performance For best performance, prefer a few collections, each with many labels, to
  518. * many collections with only a few labels each. Avoid having collections where some
  519. * labels change every frame and others do not; instead, create one or more collections
  520. * for static labels, and one or more collections for dynamic labels.
  521. *
  522. * @see LabelCollection#add
  523. * @see LabelCollection#remove
  524. * @see Label
  525. * @see BillboardCollection
  526. *
  527. * @demo {@link https://sandcastle.cesium.com/index.html?src=Labels.html|Cesium Sandcastle Labels Demo}
  528. *
  529. * @example
  530. * // Create a label collection with two labels
  531. * var labels = scene.primitives.add(new Cesium.LabelCollection());
  532. * labels.add({
  533. * position : new Cesium.Cartesian3(1.0, 2.0, 3.0),
  534. * text : 'A label'
  535. * });
  536. * labels.add({
  537. * position : new Cesium.Cartesian3(4.0, 5.0, 6.0),
  538. * text : 'Another label'
  539. * });
  540. */
  541. function LabelCollection(options) {
  542. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  543. this._scene = options.scene;
  544. this._batchTable = options.batchTable;
  545. this._textureAtlas = undefined;
  546. this._backgroundTextureAtlas = undefined;
  547. this._whitePixelIndex = undefined;
  548. this._backgroundBillboardCollection = new BillboardCollection({
  549. scene: this._scene,
  550. });
  551. this._backgroundBillboardCollection.destroyTextureAtlas = false;
  552. this._billboardCollection = new BillboardCollection({
  553. scene: this._scene,
  554. batchTable: this._batchTable,
  555. });
  556. this._billboardCollection.destroyTextureAtlas = false;
  557. this._billboardCollection._sdf = true;
  558. this._spareBillboards = [];
  559. this._glyphTextureCache = {};
  560. this._labels = [];
  561. this._labelsToUpdate = [];
  562. this._totalGlyphCount = 0;
  563. this._highlightColor = Color.clone(Color.WHITE); // Only used by Vector3DTilePoints
  564. /**
  565. * The 4x4 transformation matrix that transforms each label in this collection from model to world coordinates.
  566. * When this is the identity matrix, the labels are drawn in world coordinates, i.e., Earth's WGS84 coordinates.
  567. * Local reference frames can be used by providing a different transformation matrix, like that returned
  568. * by {@link Transforms.eastNorthUpToFixedFrame}.
  569. *
  570. * @type Matrix4
  571. * @default {@link Matrix4.IDENTITY}
  572. *
  573. * @example
  574. * var center = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883);
  575. * labels.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  576. * labels.add({
  577. * position : new Cesium.Cartesian3(0.0, 0.0, 0.0),
  578. * text : 'Center'
  579. * });
  580. * labels.add({
  581. * position : new Cesium.Cartesian3(1000000.0, 0.0, 0.0),
  582. * text : 'East'
  583. * });
  584. * labels.add({
  585. * position : new Cesium.Cartesian3(0.0, 1000000.0, 0.0),
  586. * text : 'North'
  587. * });
  588. * labels.add({
  589. * position : new Cesium.Cartesian3(0.0, 0.0, 1000000.0),
  590. * text : 'Up'
  591. * });
  592. */
  593. this.modelMatrix = Matrix4.clone(
  594. defaultValue(options.modelMatrix, Matrix4.IDENTITY)
  595. );
  596. /**
  597. * This property is for debugging only; it is not for production use nor is it optimized.
  598. * <p>
  599. * Draws the bounding sphere for each draw command in the primitive.
  600. * </p>
  601. *
  602. * @type {Boolean}
  603. *
  604. * @default false
  605. */
  606. this.debugShowBoundingVolume = defaultValue(
  607. options.debugShowBoundingVolume,
  608. false
  609. );
  610. /**
  611. * The label blending option. The default is used for rendering both opaque and translucent labels.
  612. * However, if either all of the labels are completely opaque or all are completely translucent,
  613. * setting the technique to BlendOption.OPAQUE or BlendOption.TRANSLUCENT can improve
  614. * performance by up to 2x.
  615. * @type {BlendOption}
  616. * @default BlendOption.OPAQUE_AND_TRANSLUCENT
  617. */
  618. this.blendOption = defaultValue(
  619. options.blendOption,
  620. BlendOption.OPAQUE_AND_TRANSLUCENT
  621. );
  622. }
  623. Object.defineProperties(LabelCollection.prototype, {
  624. /**
  625. * Returns the number of labels in this collection. This is commonly used with
  626. * {@link LabelCollection#get} to iterate over all the labels
  627. * in the collection.
  628. * @memberof LabelCollection.prototype
  629. * @type {Number}
  630. */
  631. length: {
  632. get: function () {
  633. return this._labels.length;
  634. },
  635. },
  636. });
  637. /**
  638. * Creates and adds a label with the specified initial properties to the collection.
  639. * The added label is returned so it can be modified or removed from the collection later.
  640. *
  641. * @param {Object} [options] A template describing the label's properties as shown in Example 1.
  642. * @returns {Label} The label that was added to the collection.
  643. *
  644. * @performance Calling <code>add</code> is expected constant time. However, the collection's vertex buffer
  645. * is rewritten; this operations is <code>O(n)</code> and also incurs
  646. * CPU to GPU overhead. For best performance, add as many billboards as possible before
  647. * calling <code>update</code>.
  648. *
  649. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  650. *
  651. *
  652. * @example
  653. * // Example 1: Add a label, specifying all the default values.
  654. * var l = labels.add({
  655. * show : true,
  656. * position : Cesium.Cartesian3.ZERO,
  657. * text : '',
  658. * font : '30px sans-serif',
  659. * fillColor : Cesium.Color.WHITE,
  660. * outlineColor : Cesium.Color.BLACK,
  661. * outlineWidth : 1.0,
  662. * showBackground : false,
  663. * backgroundColor : new Cesium.Color(0.165, 0.165, 0.165, 0.8),
  664. * backgroundPadding : new Cesium.Cartesian2(7, 5),
  665. * style : Cesium.LabelStyle.FILL,
  666. * pixelOffset : Cesium.Cartesian2.ZERO,
  667. * eyeOffset : Cesium.Cartesian3.ZERO,
  668. * horizontalOrigin : Cesium.HorizontalOrigin.LEFT,
  669. * verticalOrigin : Cesium.VerticalOrigin.BASELINE,
  670. * scale : 1.0,
  671. * translucencyByDistance : undefined,
  672. * pixelOffsetScaleByDistance : undefined,
  673. * heightReference : HeightReference.NONE,
  674. * distanceDisplayCondition : undefined
  675. * });
  676. *
  677. * @example
  678. * // Example 2: Specify only the label's cartographic position,
  679. * // text, and font.
  680. * var l = labels.add({
  681. * position : Cesium.Cartesian3.fromRadians(longitude, latitude, height),
  682. * text : 'Hello World',
  683. * font : '24px Helvetica',
  684. * });
  685. *
  686. * @see LabelCollection#remove
  687. * @see LabelCollection#removeAll
  688. */
  689. LabelCollection.prototype.add = function (options) {
  690. var label = new Label(options, this);
  691. this._labels.push(label);
  692. this._labelsToUpdate.push(label);
  693. return label;
  694. };
  695. /**
  696. * Removes a label from the collection. Once removed, a label is no longer usable.
  697. *
  698. * @param {Label} label The label to remove.
  699. * @returns {Boolean} <code>true</code> if the label was removed; <code>false</code> if the label was not found in the collection.
  700. *
  701. * @performance Calling <code>remove</code> is expected constant time. However, the collection's vertex buffer
  702. * is rewritten - an <code>O(n)</code> operation that also incurs CPU to GPU overhead. For
  703. * best performance, remove as many labels as possible before calling <code>update</code>.
  704. * If you intend to temporarily hide a label, it is usually more efficient to call
  705. * {@link Label#show} instead of removing and re-adding the label.
  706. *
  707. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  708. *
  709. *
  710. * @example
  711. * var l = labels.add(...);
  712. * labels.remove(l); // Returns true
  713. *
  714. * @see LabelCollection#add
  715. * @see LabelCollection#removeAll
  716. * @see Label#show
  717. */
  718. LabelCollection.prototype.remove = function (label) {
  719. if (defined(label) && label._labelCollection === this) {
  720. var index = this._labels.indexOf(label);
  721. if (index !== -1) {
  722. this._labels.splice(index, 1);
  723. destroyLabel(this, label);
  724. return true;
  725. }
  726. }
  727. return false;
  728. };
  729. /**
  730. * Removes all labels from the collection.
  731. *
  732. * @performance <code>O(n)</code>. It is more efficient to remove all the labels
  733. * from a collection and then add new ones than to create a new collection entirely.
  734. *
  735. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  736. *
  737. *
  738. * @example
  739. * labels.add(...);
  740. * labels.add(...);
  741. * labels.removeAll();
  742. *
  743. * @see LabelCollection#add
  744. * @see LabelCollection#remove
  745. */
  746. LabelCollection.prototype.removeAll = function () {
  747. var labels = this._labels;
  748. for (var i = 0, len = labels.length; i < len; ++i) {
  749. destroyLabel(this, labels[i]);
  750. }
  751. labels.length = 0;
  752. };
  753. /**
  754. * Check whether this collection contains a given label.
  755. *
  756. * @param {Label} label The label to check for.
  757. * @returns {Boolean} true if this collection contains the label, false otherwise.
  758. *
  759. * @see LabelCollection#get
  760. *
  761. */
  762. LabelCollection.prototype.contains = function (label) {
  763. return defined(label) && label._labelCollection === this;
  764. };
  765. /**
  766. * Returns the label in the collection at the specified index. Indices are zero-based
  767. * and increase as labels are added. Removing a label shifts all labels after
  768. * it to the left, changing their indices. This function is commonly used with
  769. * {@link LabelCollection#length} to iterate over all the labels
  770. * in the collection.
  771. *
  772. * @param {Number} index The zero-based index of the billboard.
  773. *
  774. * @returns {Label} The label at the specified index.
  775. *
  776. * @performance Expected constant time. If labels were removed from the collection and
  777. * {@link Scene#render} was not called, an implicit <code>O(n)</code>
  778. * operation is performed.
  779. *
  780. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  781. *
  782. *
  783. * @example
  784. * // Toggle the show property of every label in the collection
  785. * var len = labels.length;
  786. * for (var i = 0; i < len; ++i) {
  787. * var l = billboards.get(i);
  788. * l.show = !l.show;
  789. * }
  790. *
  791. * @see LabelCollection#length
  792. */
  793. LabelCollection.prototype.get = function (index) {
  794. //>>includeStart('debug', pragmas.debug);
  795. if (!defined(index)) {
  796. throw new DeveloperError("index is required.");
  797. }
  798. //>>includeEnd('debug');
  799. return this._labels[index];
  800. };
  801. /**
  802. * @private
  803. *
  804. */
  805. LabelCollection.prototype.update = function (frameState) {
  806. var billboardCollection = this._billboardCollection;
  807. var backgroundBillboardCollection = this._backgroundBillboardCollection;
  808. billboardCollection.modelMatrix = this.modelMatrix;
  809. billboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;
  810. backgroundBillboardCollection.modelMatrix = this.modelMatrix;
  811. backgroundBillboardCollection.debugShowBoundingVolume = this.debugShowBoundingVolume;
  812. var context = frameState.context;
  813. if (!defined(this._textureAtlas)) {
  814. this._textureAtlas = new TextureAtlas({
  815. context: context,
  816. });
  817. billboardCollection.textureAtlas = this._textureAtlas;
  818. }
  819. if (!defined(this._backgroundTextureAtlas)) {
  820. this._backgroundTextureAtlas = new TextureAtlas({
  821. context: context,
  822. initialSize: whitePixelSize,
  823. });
  824. backgroundBillboardCollection.textureAtlas = this._backgroundTextureAtlas;
  825. addWhitePixelCanvas(this._backgroundTextureAtlas, this);
  826. }
  827. var len = this._labelsToUpdate.length;
  828. for (var i = 0; i < len; ++i) {
  829. var label = this._labelsToUpdate[i];
  830. if (label.isDestroyed()) {
  831. continue;
  832. }
  833. var preUpdateGlyphCount = label._glyphs.length;
  834. if (label._rebindAllGlyphs) {
  835. rebindAllGlyphs(this, label);
  836. label._rebindAllGlyphs = false;
  837. }
  838. if (label._repositionAllGlyphs) {
  839. repositionAllGlyphs(label);
  840. label._repositionAllGlyphs = false;
  841. }
  842. var glyphCountDifference = label._glyphs.length - preUpdateGlyphCount;
  843. this._totalGlyphCount += glyphCountDifference;
  844. }
  845. var blendOption =
  846. backgroundBillboardCollection.length > 0
  847. ? BlendOption.TRANSLUCENT
  848. : this.blendOption;
  849. billboardCollection.blendOption = blendOption;
  850. backgroundBillboardCollection.blendOption = blendOption;
  851. billboardCollection._highlightColor = this._highlightColor;
  852. backgroundBillboardCollection._highlightColor = this._highlightColor;
  853. this._labelsToUpdate.length = 0;
  854. backgroundBillboardCollection.update(frameState);
  855. billboardCollection.update(frameState);
  856. };
  857. /**
  858. * Returns true if this object was destroyed; otherwise, false.
  859. * <br /><br />
  860. * If this object was destroyed, it should not be used; calling any function other than
  861. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  862. *
  863. * @returns {Boolean} True if this object was destroyed; otherwise, false.
  864. *
  865. * @see LabelCollection#destroy
  866. */
  867. LabelCollection.prototype.isDestroyed = function () {
  868. return false;
  869. };
  870. /**
  871. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  872. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  873. * <br /><br />
  874. * Once an object is destroyed, it should not be used; calling any function other than
  875. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  876. * assign the return value (<code>undefined</code>) to the object as done in the example.
  877. *
  878. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  879. *
  880. *
  881. * @example
  882. * labels = labels && labels.destroy();
  883. *
  884. * @see LabelCollection#isDestroyed
  885. */
  886. LabelCollection.prototype.destroy = function () {
  887. this.removeAll();
  888. this._billboardCollection = this._billboardCollection.destroy();
  889. this._textureAtlas = this._textureAtlas && this._textureAtlas.destroy();
  890. this._backgroundBillboardCollection = this._backgroundBillboardCollection.destroy();
  891. this._backgroundTextureAtlas =
  892. this._backgroundTextureAtlas && this._backgroundTextureAtlas.destroy();
  893. return destroyObject(this);
  894. };
  895. export default LabelCollection;