element-index.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { ColorScale, Color } from 'mol-util/color';
  7. import { Location } from 'mol-model/location';
  8. import { StructureElement, Link } from 'mol-model/structure';
  9. import { OrderedSet } from 'mol-data/int';
  10. import { ColorThemeProps, ColorTheme, LocationColor } from '../color';
  11. const DefaultColor = Color(0xCCCCCC)
  12. const Description = 'Gives every element (atom or coarse sphere/gaussian) a unique color based on the position (index) of the element in the list of elements in the structure.'
  13. export function ElementIndexColorTheme(props: ColorThemeProps): ColorTheme {
  14. let color: LocationColor
  15. let scale = ColorScale.create({ list: props.list, minLabel: 'Start', maxLabel: 'End' })
  16. if (props.structure) {
  17. const { units } = props.structure
  18. const unitCount = units.length
  19. const cummulativeElementCount = new Map<number, number>()
  20. const unitIdIndex = new Map<number, number>()
  21. let elementCount = 0
  22. for (let i = 0; i < unitCount; ++i) {
  23. cummulativeElementCount.set(i, elementCount)
  24. elementCount += units[i].elements.length
  25. unitIdIndex.set(units[i].id, i)
  26. }
  27. scale.setDomain(0, elementCount - 1)
  28. const scaleColor = scale.color
  29. color = (location: Location): Color => {
  30. if (StructureElement.isLocation(location)) {
  31. const unitIndex = unitIdIndex.get(location.unit.id)!
  32. const unitElementIndex = OrderedSet.findPredecessorIndex(location.unit.elements, location.element)
  33. return scaleColor(cummulativeElementCount.get(unitIndex)! + unitElementIndex)
  34. } else if (Link.isLocation(location)) {
  35. const unitIndex = unitIdIndex.get(location.aUnit.id)!
  36. return scaleColor(cummulativeElementCount.get(unitIndex)! + location.aIndex)
  37. }
  38. return DefaultColor
  39. }
  40. } else {
  41. color = () => DefaultColor
  42. }
  43. return {
  44. features: { structure: true, list: true },
  45. granularity: 'groupInstance',
  46. color,
  47. description: Description,
  48. legend: scale ? scale.legend : undefined
  49. }
  50. }