representation.ts 16 KB

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