representation.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /**
  2. * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { ParamDefinition as PD } from '../mol-util/param-definition';
  7. import { WebGLContext } from '../mol-gl/webgl/context';
  8. import { ColorTheme } from '../mol-theme/color';
  9. import { SizeTheme } from '../mol-theme/size';
  10. import { ThemeRegistryContext, Theme } from '../mol-theme/theme';
  11. import { Subject } from 'rxjs';
  12. import { GraphicsRenderObject } from '../mol-gl/render-object';
  13. import { Task } from '../mol-task';
  14. import { PickingId } from '../mol-geo/geometry/picking';
  15. import { MarkerAction, MarkerActions } from '../mol-util/marker-action';
  16. import { Loci as ModelLoci, EmptyLoci, isEmptyLoci } from '../mol-model/loci';
  17. import { Overpaint } from '../mol-theme/overpaint';
  18. import { Transparency } from '../mol-theme/transparency';
  19. import { Mat4 } from '../mol-math/linear-algebra';
  20. import { getQualityProps } from './util';
  21. import { BaseGeometry } from '../mol-geo/geometry/base';
  22. import { Visual } from './visual';
  23. import { CustomProperty } from '../mol-model-props/common/custom-property';
  24. // export interface RepresentationProps {
  25. // visuals?: string[]
  26. // }
  27. export type RepresentationProps = { [k: string]: any }
  28. export interface RepresentationContext {
  29. readonly webgl?: WebGLContext
  30. readonly colorThemeRegistry: ColorTheme.Registry
  31. readonly sizeThemeRegistry: SizeTheme.Registry
  32. }
  33. export type RepresentationParamsGetter<D, P extends PD.Params> = (ctx: ThemeRegistryContext, data: D) => P
  34. export type RepresentationFactory<D, P extends PD.Params, S extends Representation.State> = (ctx: RepresentationContext, getParams: RepresentationParamsGetter<D, P>) => Representation<D, P, S>
  35. //
  36. export interface RepresentationProvider<D = any, P extends PD.Params = any, S extends Representation.State = any, Id extends string = string> {
  37. readonly name: Id,
  38. readonly label: string
  39. readonly description: string
  40. readonly factory: RepresentationFactory<D, P, S>
  41. readonly getParams: RepresentationParamsGetter<D, P>
  42. readonly defaultValues: PD.Values<P>
  43. readonly defaultColorTheme: { name: string, props?: {} }
  44. readonly defaultSizeTheme: { name: string, props?: {} }
  45. readonly isApplicable: (data: D) => boolean
  46. readonly ensureCustomProperties?: {
  47. attach: (ctx: CustomProperty.Context, data: D) => Promise<void>,
  48. detach: (ctx: CustomProperty.Context, data: D) => void
  49. }
  50. }
  51. export namespace RepresentationProvider {
  52. export type ParamValues<R extends RepresentationProvider<any, any, any>> = R extends RepresentationProvider<any, infer P, any> ? PD.Values<P> : never;
  53. export function getDetaultParams<R extends RepresentationProvider<D, any, any>, D>(r: R, ctx: ThemeRegistryContext, data: D) {
  54. return PD.getDefaultValues(r.getParams(ctx, data));
  55. }
  56. }
  57. export type AnyRepresentationProvider = RepresentationProvider<any, {}, Representation.State>
  58. export const EmptyRepresentationProvider = {
  59. label: '',
  60. description: '',
  61. factory: () => Representation.Empty,
  62. getParams: () => ({}),
  63. defaultValues: {}
  64. }
  65. function getTypes(list: { name: string, provider: RepresentationProvider<any, any, any> }[]) {
  66. return list.map(e => [e.name, e.provider.label] as [string, string]);
  67. }
  68. export class RepresentationRegistry<D, S extends Representation.State> {
  69. private _list: { name: string, provider: RepresentationProvider<D, any, any> }[] = []
  70. private _map = new Map<string, RepresentationProvider<D, any, any>>()
  71. private _name = new Map<RepresentationProvider<D, any, any>, string>()
  72. get default() { return this._list[0]; }
  73. get types(): [string, string][] { return getTypes(this._list) }
  74. constructor() {};
  75. add<P extends PD.Params>(provider: RepresentationProvider<D, P, S>) {
  76. if (this._map.has(provider.name)) {
  77. throw new Error(`${provider.name} already registered.`);
  78. }
  79. this._list.push({ name: provider.name, provider })
  80. this._map.set(provider.name, provider)
  81. this._name.set(provider, provider.name)
  82. }
  83. getName(provider: RepresentationProvider<D, any, any>): string {
  84. if (!this._name.has(provider)) throw new Error(`'${provider.label}' is not a registered represenatation provider.`);
  85. return this._name.get(provider)!;
  86. }
  87. remove(provider: RepresentationProvider<D, any, any>) {
  88. const name = provider.name;
  89. this._list.splice(this._list.findIndex(e => e.name === name), 1)
  90. const p = this._map.get(name);
  91. if (p) {
  92. this._map.delete(name);
  93. this._name.delete(p);
  94. }
  95. }
  96. get<P extends PD.Params>(name: string): RepresentationProvider<D, P, S> {
  97. return this._map.get(name) || EmptyRepresentationProvider as unknown as RepresentationProvider<D, P, S>
  98. }
  99. get list() {
  100. return this._list
  101. }
  102. getApplicableList(data: D) {
  103. return this._list.filter(e => e.provider.isApplicable(data));
  104. }
  105. getApplicableTypes(data: D) {
  106. return getTypes(this.getApplicableList(data))
  107. }
  108. }
  109. //
  110. export { Representation }
  111. interface Representation<D, P extends PD.Params = {}, S extends Representation.State = Representation.State> {
  112. readonly label: string
  113. readonly updated: Subject<number>
  114. /** Number of addressable groups in all visuals of the representation */
  115. readonly groupCount: number
  116. readonly renderObjects: ReadonlyArray<GraphicsRenderObject>
  117. readonly props: Readonly<PD.Values<P>>
  118. readonly params: Readonly<P>
  119. readonly state: Readonly<S>
  120. readonly theme: Readonly<Theme>
  121. createOrUpdate: (props?: Partial<PD.Values<P>>, data?: D) => Task<void>
  122. setState: (state: Partial<S>) => void
  123. setTheme: (theme: Theme) => void
  124. /** If no pickingId is given, returns a Loci for the whole representation */
  125. getLoci: (pickingId?: PickingId) => ModelLoci
  126. mark: (loci: ModelLoci, action: MarkerAction) => boolean
  127. destroy: () => void
  128. }
  129. namespace Representation {
  130. export interface Loci<T extends ModelLoci = ModelLoci> { loci: T, repr?: Representation.Any }
  131. export namespace Loci {
  132. export function areEqual(a: Loci, b: Loci) {
  133. return a.repr === b.repr && ModelLoci.areEqual(a.loci, b.loci);
  134. }
  135. export const Empty: Loci = { loci: EmptyLoci };
  136. }
  137. export interface State {
  138. /** Controls if the representation's renderobjects are rendered or not */
  139. visible: boolean
  140. /** A factor applied to alpha value of the representation's renderobjects */
  141. alphaFactor: number
  142. /** Controls if the representation's renderobjects are pickable or not */
  143. pickable: boolean
  144. /** Overpaint applied to the representation's renderobjects */
  145. overpaint: Overpaint
  146. /** Per group transparency applied to the representation's renderobjects */
  147. transparency: Transparency
  148. /** Controls if the representation's renderobjects are synced automatically with GPU or not */
  149. syncManually: boolean
  150. /** A transformation applied to the representation's renderobjects */
  151. transform: Mat4
  152. /** Bit mask of allowed marker actions */
  153. markerActions: MarkerActions
  154. }
  155. export function createState(): State {
  156. return { visible: true, alphaFactor: 1, pickable: true, syncManually: false, transform: Mat4.identity(), overpaint: Overpaint.Empty, transparency: Transparency.Empty, markerActions: MarkerActions.All }
  157. }
  158. export function updateState(state: State, update: Partial<State>) {
  159. if (update.visible !== undefined) state.visible = update.visible
  160. if (update.alphaFactor !== undefined) state.alphaFactor = update.alphaFactor
  161. if (update.pickable !== undefined) state.pickable = update.pickable
  162. if (update.overpaint !== undefined) state.overpaint = update.overpaint
  163. if (update.transparency !== undefined) state.transparency = update.transparency
  164. if (update.syncManually !== undefined) state.syncManually = update.syncManually
  165. if (update.transform !== undefined) Mat4.copy(state.transform, update.transform)
  166. if (update.markerActions !== undefined) state.markerActions = update.markerActions
  167. }
  168. export interface StateBuilder<S extends State> {
  169. create(): S
  170. update(state: S, update: Partial<S>): void
  171. }
  172. export const StateBuilder: StateBuilder<State> = { create: createState, update: updateState }
  173. export type Any = Representation<any, any, any>
  174. export const Empty: Any = {
  175. label: '', groupCount: 0, renderObjects: [], props: {}, params: {}, updated: new Subject(), state: createState(), theme: Theme.createEmpty(),
  176. createOrUpdate: () => Task.constant('', undefined),
  177. setState: () => {},
  178. setTheme: () => {},
  179. getLoci: () => EmptyLoci,
  180. mark: () => false,
  181. destroy: () => {}
  182. }
  183. export type Def<D, P extends PD.Params = {}, S extends State = State> = { [k: string]: RepresentationFactory<D, P, S> }
  184. export function createMulti<D, P extends PD.Params = {}, S extends State = State>(label: string, ctx: RepresentationContext, getParams: RepresentationParamsGetter<D, P>, stateBuilder: StateBuilder<S>, reprDefs: Def<D, P>): Representation<D, P, S> {
  185. let version = 0
  186. const updated = new Subject<number>()
  187. const currentState = stateBuilder.create()
  188. let currentTheme = Theme.createEmpty()
  189. let currentParams: P
  190. let currentProps: PD.Values<P>
  191. let currentData: D
  192. const reprMap: { [k: number]: string } = {}
  193. const reprList: Representation<D, P>[] = Object.keys(reprDefs).map((name, i) => {
  194. reprMap[i] = name
  195. const repr = reprDefs[name](ctx, getParams)
  196. repr.setState(currentState)
  197. return repr
  198. })
  199. return {
  200. label,
  201. updated,
  202. get groupCount() {
  203. let groupCount = 0
  204. if (currentProps) {
  205. const { visuals } = currentProps
  206. for (let i = 0, il = reprList.length; i < il; ++i) {
  207. if (!visuals || visuals.includes(reprMap[i])) {
  208. groupCount += reprList[i].groupCount
  209. }
  210. }
  211. }
  212. return groupCount
  213. },
  214. get renderObjects() {
  215. const renderObjects: GraphicsRenderObject[] = []
  216. if (currentProps) {
  217. const { visuals } = currentProps
  218. for (let i = 0, il = reprList.length; i < il; ++i) {
  219. if (!visuals || visuals.includes(reprMap[i])) {
  220. renderObjects.push(...reprList[i].renderObjects)
  221. }
  222. }
  223. }
  224. return renderObjects
  225. },
  226. get props() { return currentProps },
  227. get params() { return currentParams },
  228. createOrUpdate: (props: Partial<P> = {}, data?: D) => {
  229. if (data && data !== currentData) {
  230. currentParams = getParams(ctx, data)
  231. currentData = data
  232. if (!currentProps) currentProps = PD.getDefaultValues(currentParams) as P
  233. }
  234. const qualityProps = getQualityProps(Object.assign({}, currentProps, props), currentData)
  235. Object.assign(currentProps, props, qualityProps)
  236. const { visuals } = currentProps
  237. return Task.create(`Creating or updating '${label}' representation`, async runtime => {
  238. for (let i = 0, il = reprList.length; i < il; ++i) {
  239. if (!visuals || visuals.includes(reprMap[i])) {
  240. await reprList[i].createOrUpdate(currentProps, currentData).runInContext(runtime)
  241. }
  242. }
  243. updated.next(version++)
  244. })
  245. },
  246. get state() { return currentState },
  247. get theme() { return currentTheme },
  248. getLoci: (pickingId?: PickingId) => {
  249. if (pickingId === undefined) {
  250. return reprList.length > 0 ? reprList[0].getLoci() : EmptyLoci
  251. }
  252. for (let i = 0, il = reprList.length; i < il; ++i) {
  253. const loci = reprList[i].getLoci(pickingId)
  254. if (!isEmptyLoci(loci)) return loci
  255. }
  256. return EmptyLoci
  257. },
  258. mark: (loci: ModelLoci, action: MarkerAction) => {
  259. let marked = false
  260. for (let i = 0, il = reprList.length; i < il; ++i) {
  261. marked = reprList[i].mark(loci, action) || marked
  262. }
  263. return marked
  264. },
  265. setState: (state: Partial<S>) => {
  266. stateBuilder.update(currentState, state)
  267. for (let i = 0, il = reprList.length; i < il; ++i) {
  268. reprList[i].setState(currentState)
  269. }
  270. },
  271. setTheme: (theme: Theme) => {
  272. for (let i = 0, il = reprList.length; i < il; ++i) {
  273. reprList[i].setTheme(theme)
  274. }
  275. },
  276. destroy() {
  277. for (let i = 0, il = reprList.length; i < il; ++i) {
  278. reprList[i].destroy()
  279. }
  280. }
  281. }
  282. }
  283. export function fromRenderObject(label: string, renderObject: GraphicsRenderObject): Representation<GraphicsRenderObject, BaseGeometry.Params> {
  284. let version = 0
  285. const updated = new Subject<number>()
  286. const currentState = Representation.createState()
  287. const currentTheme = Theme.createEmpty()
  288. const currentParams = PD.clone(BaseGeometry.Params)
  289. const currentProps = PD.getDefaultValues(BaseGeometry.Params)
  290. return {
  291. label,
  292. updated,
  293. get groupCount() { return renderObject.values.uGroupCount.ref.value },
  294. get renderObjects() { return [renderObject] },
  295. get props() { return currentProps },
  296. get params() { return currentParams },
  297. createOrUpdate: (props: Partial<PD.Values<BaseGeometry.Params>> = {}) => {
  298. const qualityProps = getQualityProps(Object.assign({}, currentProps, props))
  299. Object.assign(currentProps, props, qualityProps)
  300. return Task.create(`Updating '${label}' representation`, async runtime => {
  301. // TODO
  302. updated.next(version++)
  303. })
  304. },
  305. get state() { return currentState },
  306. get theme() { return currentTheme },
  307. getLoci: () => {
  308. // TODO
  309. return EmptyLoci
  310. },
  311. mark: (loci: ModelLoci, action: MarkerAction) => {
  312. // TODO
  313. return false
  314. },
  315. setState: (state: Partial<State>) => {
  316. if (state.visible !== undefined) Visual.setVisibility(renderObject, state.visible)
  317. if (state.alphaFactor !== undefined) Visual.setAlphaFactor(renderObject, state.alphaFactor)
  318. if (state.pickable !== undefined) Visual.setPickable(renderObject, state.pickable)
  319. if (state.overpaint !== undefined) {
  320. // TODO
  321. }
  322. if (state.transparency !== undefined) {
  323. // TODO
  324. }
  325. if (state.transform !== undefined) Visual.setTransform(renderObject, state.transform)
  326. Representation.updateState(currentState, state)
  327. },
  328. setTheme: () => { },
  329. destroy() { }
  330. }
  331. }
  332. }