units-representation.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { Structure, Unit } from 'mol-model/structure';
  8. import { Task } from 'mol-task'
  9. import { RenderObject } from 'mol-gl/render-object';
  10. import { Visual, RepresentationContext, RepresentationParamsGetter, Representation } from '../representation';
  11. import { Loci, EmptyLoci, isEmptyLoci } from 'mol-model/loci';
  12. import { StructureGroup } from './units-visual';
  13. import { StructureRepresentation, StructureParams } from './representation';
  14. import { PickingId } from 'mol-geo/geometry/picking';
  15. import { MarkerAction } from 'mol-geo/geometry/marker-data';
  16. import { Theme, createEmptyTheme } from 'mol-theme/theme';
  17. import { ParamDefinition as PD } from 'mol-util/param-definition';
  18. import { UnitKind, UnitKindOptions } from './visual/util/common';
  19. import { Subject } from 'rxjs';
  20. export const UnitsParams = {
  21. ...StructureParams,
  22. unitKinds: PD.MultiSelect<UnitKind>(['atomic', 'spheres'], UnitKindOptions),
  23. }
  24. export type UnitsParams = typeof UnitsParams
  25. export interface UnitsVisual<P extends UnitsParams> extends Visual<StructureGroup, P> { }
  26. export function UnitsRepresentation<P extends UnitsParams>(label: string, ctx: RepresentationContext, getParams: RepresentationParamsGetter<Structure, P>, visualCtor: () => UnitsVisual<P>): StructureRepresentation<P> {
  27. let version = 0
  28. const updated = new Subject<number>()
  29. const _state = Representation.createState()
  30. let visuals = new Map<number, { group: Unit.SymmetryGroup, visual: UnitsVisual<P> }>()
  31. let _structure: Structure
  32. let _groups: ReadonlyArray<Unit.SymmetryGroup>
  33. let _params: P
  34. let _props: PD.Values<P>
  35. let _theme = createEmptyTheme()
  36. function createOrUpdate(props: Partial<PD.Values<P>> = {}, structure?: Structure) {
  37. if (structure && structure !== _structure) {
  38. _params = getParams(ctx, structure)
  39. if (!_props) _props = PD.getDefaultValues(_params)
  40. }
  41. _props = Object.assign({}, _props, props)
  42. return Task.create('Creating or updating UnitsRepresentation', async runtime => {
  43. if (!_structure && !structure) {
  44. throw new Error('missing structure')
  45. } else if (structure && !_structure) {
  46. // console.log(label, 'initial structure')
  47. // First call with a structure, create visuals for each group.
  48. _groups = structure.unitSymmetryGroups;
  49. for (let i = 0; i < _groups.length; i++) {
  50. const group = _groups[i];
  51. const visual = visualCtor()
  52. await visual.createOrUpdate({ webgl: ctx.webgl, runtime }, _theme, _props, { group, structure })
  53. visuals.set(group.hashCode, { visual, group })
  54. }
  55. } else if (structure && !Structure.areEquivalent(structure, _structure)) {
  56. // console.log(label, 'structure not equivalent')
  57. // Tries to re-use existing visuals for the groups of the new structure.
  58. // Creates additional visuals if needed, destroys left-over visuals.
  59. _groups = structure.unitSymmetryGroups;
  60. // const newGroups: Unit.SymmetryGroup[] = []
  61. const oldVisuals = visuals
  62. visuals = new Map()
  63. for (let i = 0; i < _groups.length; i++) {
  64. const group = _groups[i];
  65. const visualGroup = oldVisuals.get(group.hashCode)
  66. if (visualGroup) {
  67. // console.log(label, 'found visualGroup to reuse')
  68. // console.log('old', visualGroup.group)
  69. // console.log('new', group)
  70. const { visual } = visualGroup
  71. await visual.createOrUpdate({ webgl: ctx.webgl, runtime }, _theme, _props, { group, structure })
  72. visuals.set(group.hashCode, { visual, group })
  73. oldVisuals.delete(group.hashCode)
  74. } else {
  75. // console.log(label, 'not found visualGroup to reuse, creating new')
  76. // newGroups.push(group)
  77. const visual = visualCtor()
  78. await visual.createOrUpdate({ webgl: ctx.webgl, runtime }, _theme, _props, { group, structure })
  79. visuals.set(group.hashCode, { visual, group })
  80. }
  81. }
  82. oldVisuals.forEach(({ visual }) => {
  83. // console.log(label, 'removed unused visual')
  84. visual.destroy()
  85. })
  86. // TODO review logic
  87. // For new groups, re-use left-over visuals
  88. // const unusedVisuals: UnitsVisual<P>[] = []
  89. // oldVisuals.forEach(({ visual }) => unusedVisuals.push(visual))
  90. // newGroups.forEach(async group => {
  91. // const visual = unusedVisuals.pop() || visualCtor()
  92. // await visual.createOrUpdate({ ...ctx, runtime }, _props, group)
  93. // visuals.set(group.hashCode, { visual, group })
  94. // })
  95. // unusedVisuals.forEach(visual => visual.destroy())
  96. } else if (structure && structure !== _structure && Structure.areEquivalent(structure, _structure)) {
  97. // console.log(label, 'structures equivalent but not identical')
  98. // Expects that for structures with the same hashCode,
  99. // the unitSymmetryGroups are the same as well.
  100. // Re-uses existing visuals for the groups of the new structure.
  101. _groups = structure.unitSymmetryGroups;
  102. // console.log('new', structure.unitSymmetryGroups)
  103. // console.log('old', _structure.unitSymmetryGroups)
  104. for (let i = 0; i < _groups.length; i++) {
  105. const group = _groups[i];
  106. const visualGroup = visuals.get(group.hashCode)
  107. if (visualGroup) {
  108. await visualGroup.visual.createOrUpdate({ webgl: ctx.webgl, runtime }, _theme, _props, { group, structure })
  109. visualGroup.group = group
  110. } else {
  111. throw new Error(`expected to find visual for hashCode ${group.hashCode}`)
  112. }
  113. }
  114. } else {
  115. // console.log(label, 'no new structure')
  116. // No new structure given, just update all visuals with new props.
  117. const visualsList: [ UnitsVisual<P>, Unit.SymmetryGroup ][] = [] // TODO avoid allocation
  118. visuals.forEach(({ visual, group }) => visualsList.push([ visual, group ]))
  119. for (let i = 0, il = visualsList.length; i < il; ++i) {
  120. const [ visual ] = visualsList[i]
  121. await visual.createOrUpdate({ webgl: ctx.webgl, runtime }, _theme, _props)
  122. }
  123. }
  124. if (structure) _structure = structure
  125. updated.next(version++)
  126. });
  127. }
  128. function getLoci(pickingId: PickingId) {
  129. let loci: Loci = EmptyLoci
  130. visuals.forEach(({ visual }) => {
  131. const _loci = visual.getLoci(pickingId)
  132. if (!isEmptyLoci(_loci)) loci = _loci
  133. })
  134. return loci
  135. }
  136. function mark(loci: Loci, action: MarkerAction) {
  137. let changed = false
  138. visuals.forEach(({ visual }) => {
  139. changed = visual.mark(loci, action) || changed
  140. })
  141. return changed
  142. }
  143. function setState(state: Partial<Representation.State>) {
  144. if (state.visible !== undefined) visuals.forEach(({ visual }) => visual.setVisibility(state.visible!))
  145. if (state.pickable !== undefined) visuals.forEach(({ visual }) => visual.setPickable(state.pickable!))
  146. Representation.updateState(_state, state)
  147. }
  148. function setTheme(theme: Theme) {
  149. _theme = theme
  150. }
  151. function destroy() {
  152. visuals.forEach(({ visual }) => visual.destroy())
  153. visuals.clear()
  154. }
  155. return {
  156. label,
  157. get groupCount() {
  158. let groupCount = 0
  159. visuals.forEach(({ visual }) => {
  160. if (visual.renderObject) groupCount += visual.groupCount
  161. })
  162. return groupCount
  163. },
  164. get renderObjects() {
  165. const renderObjects: RenderObject[] = []
  166. visuals.forEach(({ visual }) => {
  167. if (visual.renderObject) renderObjects.push(visual.renderObject)
  168. })
  169. return renderObjects
  170. },
  171. get props() { return _props },
  172. get params() { return _params },
  173. get state() { return _state },
  174. get theme() { return _theme },
  175. updated,
  176. createOrUpdate,
  177. setState,
  178. setTheme,
  179. getLoci,
  180. mark,
  181. destroy
  182. }
  183. }