model.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. /**
  2. * Copyright (c) 2018-2023 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { parseDcd } from '../../mol-io/reader/dcd/parser';
  8. import { parseGRO } from '../../mol-io/reader/gro/parser';
  9. import { parsePDB } from '../../mol-io/reader/pdb/parser';
  10. import { Mat4, Vec3 } from '../../mol-math/linear-algebra';
  11. import { shapeFromPly } from '../../mol-model-formats/shape/ply';
  12. import { coordinatesFromDcd } from '../../mol-model-formats/structure/dcd';
  13. import { trajectoryFromGRO } from '../../mol-model-formats/structure/gro';
  14. import { trajectoryFromCCD, trajectoryFromMmCIF } from '../../mol-model-formats/structure/mmcif';
  15. import { trajectoryFromPDB } from '../../mol-model-formats/structure/pdb';
  16. import { topologyFromPsf } from '../../mol-model-formats/structure/psf';
  17. import { Coordinates, Model, Queries, QueryContext, Structure, StructureElement, StructureQuery, StructureSelection as Sel, Topology, ArrayTrajectory, Trajectory } from '../../mol-model/structure';
  18. import { PluginContext } from '../../mol-plugin/context';
  19. import { MolScriptBuilder } from '../../mol-script/language/builder';
  20. import { Expression } from '../../mol-script/language/expression';
  21. import { Script } from '../../mol-script/script';
  22. import { StateObject, StateTransformer } from '../../mol-state';
  23. import { RuntimeContext, Task } from '../../mol-task';
  24. import { deepEqual } from '../../mol-util';
  25. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  26. import { RootStructureDefinition } from '../helpers/root-structure';
  27. import { createStructureComponent, StructureComponentParams, updateStructureComponent } from '../helpers/structure-component';
  28. import { StructureQueryHelper } from '../helpers/structure-query';
  29. import { StructureSelectionQueries } from '../helpers/structure-selection-query';
  30. import { PluginStateObject as SO, PluginStateTransform } from '../objects';
  31. import { parseMol } from '../../mol-io/reader/mol/parser';
  32. import { trajectoryFromMol } from '../../mol-model-formats/structure/mol';
  33. import { trajectoryFromCifCore } from '../../mol-model-formats/structure/cif-core';
  34. import { trajectoryFromCube } from '../../mol-model-formats/structure/cube';
  35. import { parseMol2 } from '../../mol-io/reader/mol2/parser';
  36. import { trajectoryFromMol2 } from '../../mol-model-formats/structure/mol2';
  37. import { parseXtc } from '../../mol-io/reader/xtc/parser';
  38. import { coordinatesFromXtc } from '../../mol-model-formats/structure/xtc';
  39. import { parseXyz } from '../../mol-io/reader/xyz/parser';
  40. import { trajectoryFromXyz } from '../../mol-model-formats/structure/xyz';
  41. import { parseSdf } from '../../mol-io/reader/sdf/parser';
  42. import { trajectoryFromSdf } from '../../mol-model-formats/structure/sdf';
  43. import { assertUnreachable } from '../../mol-util/type-helpers';
  44. import { parseTrr } from '../../mol-io/reader/trr/parser';
  45. import { coordinatesFromTrr } from '../../mol-model-formats/structure/trr';
  46. import { parseNctraj } from '../../mol-io/reader/nctraj/parser';
  47. import { coordinatesFromNctraj } from '../../mol-model-formats/structure/nctraj';
  48. import { topologyFromPrmtop } from '../../mol-model-formats/structure/prmtop';
  49. import { topologyFromTop } from '../../mol-model-formats/structure/top';
  50. export { CoordinatesFromDcd };
  51. export { CoordinatesFromXtc };
  52. export { CoordinatesFromTrr };
  53. export { CoordinatesFromNctraj };
  54. export { TopologyFromPsf };
  55. export { TopologyFromPrmtop };
  56. export { TopologyFromTop };
  57. export { TrajectoryFromModelAndCoordinates };
  58. export { TrajectoryFromBlob };
  59. export { TrajectoryFromMmCif };
  60. export { TrajectoryFromPDB };
  61. export { TrajectoryFromGRO };
  62. export { TrajectoryFromXYZ };
  63. export { TrajectoryFromMOL };
  64. export { TrajectoryFromSDF };
  65. export { TrajectoryFromMOL2 };
  66. export { TrajectoryFromCube };
  67. export { TrajectoryFromCifCore };
  68. export { ModelFromTrajectory };
  69. export { StructureFromTrajectory };
  70. export { StructureFromModel };
  71. export { TransformStructureConformation };
  72. export { StructureSelectionFromExpression };
  73. export { MultiStructureSelectionFromExpression };
  74. export { StructureSelectionFromScript };
  75. export { StructureSelectionFromBundle };
  76. export { StructureComplexElement };
  77. export { StructureComponent };
  78. export { CustomModelProperties };
  79. export { CustomStructureProperties };
  80. export { ShapeFromPly };
  81. type CoordinatesFromDcd = typeof CoordinatesFromDcd
  82. const CoordinatesFromDcd = PluginStateTransform.BuiltIn({
  83. name: 'coordinates-from-dcd',
  84. display: { name: 'Parse DCD', description: 'Parse DCD binary data.' },
  85. from: [SO.Data.Binary],
  86. to: SO.Molecule.Coordinates
  87. })({
  88. apply({ a }) {
  89. return Task.create('Parse DCD', async ctx => {
  90. const parsed = await parseDcd(a.data).runInContext(ctx);
  91. if (parsed.isError) throw new Error(parsed.message);
  92. const coordinates = await coordinatesFromDcd(parsed.result).runInContext(ctx);
  93. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  94. });
  95. }
  96. });
  97. type CoordinatesFromXtc = typeof CoordinatesFromXtc
  98. const CoordinatesFromXtc = PluginStateTransform.BuiltIn({
  99. name: 'coordinates-from-xtc',
  100. display: { name: 'Parse XTC', description: 'Parse XTC binary data.' },
  101. from: [SO.Data.Binary],
  102. to: SO.Molecule.Coordinates
  103. })({
  104. apply({ a }) {
  105. return Task.create('Parse XTC', async ctx => {
  106. const parsed = await parseXtc(a.data).runInContext(ctx);
  107. if (parsed.isError) throw new Error(parsed.message);
  108. const coordinates = await coordinatesFromXtc(parsed.result).runInContext(ctx);
  109. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  110. });
  111. }
  112. });
  113. type CoordinatesFromTrr = typeof CoordinatesFromTrr
  114. const CoordinatesFromTrr = PluginStateTransform.BuiltIn({
  115. name: 'coordinates-from-trr',
  116. display: { name: 'Parse TRR', description: 'Parse TRR binary data.' },
  117. from: [SO.Data.Binary],
  118. to: SO.Molecule.Coordinates
  119. })({
  120. apply({ a }) {
  121. return Task.create('Parse TRR', async ctx => {
  122. const parsed = await parseTrr(a.data).runInContext(ctx);
  123. if (parsed.isError) throw new Error(parsed.message);
  124. const coordinates = await coordinatesFromTrr(parsed.result).runInContext(ctx);
  125. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  126. });
  127. }
  128. });
  129. type CoordinatesFromNctraj = typeof CoordinatesFromNctraj
  130. const CoordinatesFromNctraj = PluginStateTransform.BuiltIn({
  131. name: 'coordinates-from-nctraj',
  132. display: { name: 'Parse NCTRAJ', description: 'Parse NCTRAJ binary data.' },
  133. from: [SO.Data.Binary],
  134. to: SO.Molecule.Coordinates
  135. })({
  136. apply({ a }) {
  137. return Task.create('Parse NCTRAJ', async ctx => {
  138. const parsed = await parseNctraj(a.data).runInContext(ctx);
  139. if (parsed.isError) throw new Error(parsed.message);
  140. const coordinates = await coordinatesFromNctraj(parsed.result).runInContext(ctx);
  141. return new SO.Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' });
  142. });
  143. }
  144. });
  145. type TopologyFromPsf = typeof TopologyFromPsf
  146. const TopologyFromPsf = PluginStateTransform.BuiltIn({
  147. name: 'topology-from-psf',
  148. display: { name: 'PSF Topology', description: 'Create topology from PSF.' },
  149. from: [SO.Format.Psf],
  150. to: SO.Molecule.Topology
  151. })({
  152. apply({ a }) {
  153. return Task.create('Create Topology', async ctx => {
  154. const topology = await topologyFromPsf(a.data).runInContext(ctx);
  155. return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
  156. });
  157. }
  158. });
  159. type TopologyFromPrmtop = typeof TopologyFromPrmtop
  160. const TopologyFromPrmtop = PluginStateTransform.BuiltIn({
  161. name: 'topology-from-prmtop',
  162. display: { name: 'PRMTOP Topology', description: 'Create topology from PRMTOP.' },
  163. from: [SO.Format.Prmtop],
  164. to: SO.Molecule.Topology
  165. })({
  166. apply({ a }) {
  167. return Task.create('Create Topology', async ctx => {
  168. const topology = await topologyFromPrmtop(a.data).runInContext(ctx);
  169. return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
  170. });
  171. }
  172. });
  173. type TopologyFromTop = typeof TopologyFromTop
  174. const TopologyFromTop = PluginStateTransform.BuiltIn({
  175. name: 'topology-from-top',
  176. display: { name: 'TOP Topology', description: 'Create topology from TOP.' },
  177. from: [SO.Format.Top],
  178. to: SO.Molecule.Topology
  179. })({
  180. apply({ a }) {
  181. return Task.create('Create Topology', async ctx => {
  182. const topology = await topologyFromTop(a.data).runInContext(ctx);
  183. return new SO.Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' });
  184. });
  185. }
  186. });
  187. async function getTrajectory(ctx: RuntimeContext, obj: StateObject, coordinates: Coordinates) {
  188. if (obj.type === SO.Molecule.Topology.type) {
  189. const topology = obj.data as Topology;
  190. return await Model.trajectoryFromTopologyAndCoordinates(topology, coordinates).runInContext(ctx);
  191. } else if (obj.type === SO.Molecule.Model.type) {
  192. const model = obj.data as Model;
  193. return Model.trajectoryFromModelAndCoordinates(model, coordinates);
  194. }
  195. throw new Error('no model/topology found');
  196. }
  197. type TrajectoryFromModelAndCoordinates = typeof TrajectoryFromModelAndCoordinates
  198. const TrajectoryFromModelAndCoordinates = PluginStateTransform.BuiltIn({
  199. name: 'trajectory-from-model-and-coordinates',
  200. display: { name: 'Trajectory from Topology & Coordinates', description: 'Create a trajectory from existing model/topology and coordinates.' },
  201. from: SO.Root,
  202. to: SO.Molecule.Trajectory,
  203. params: {
  204. modelRef: PD.Text('', { isHidden: true }),
  205. coordinatesRef: PD.Text('', { isHidden: true }),
  206. }
  207. })({
  208. apply({ params, dependencies }) {
  209. return Task.create('Create trajectory from model/topology and coordinates', async ctx => {
  210. const coordinates = dependencies![params.coordinatesRef].data as Coordinates;
  211. const trajectory = await getTrajectory(ctx, dependencies![params.modelRef], coordinates);
  212. const props = { label: 'Trajectory', description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
  213. return new SO.Molecule.Trajectory(trajectory, props);
  214. });
  215. }
  216. });
  217. type TrajectoryFromBlob = typeof TrajectoryFromBlob
  218. const TrajectoryFromBlob = PluginStateTransform.BuiltIn({
  219. name: 'trajectory-from-blob',
  220. display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
  221. from: SO.Format.Blob,
  222. to: SO.Molecule.Trajectory
  223. })({
  224. apply({ a }) {
  225. return Task.create('Parse Format Blob', async ctx => {
  226. const models: Model[] = [];
  227. for (const e of a.data) {
  228. if (e.kind !== 'cif') continue;
  229. const block = e.data.blocks[0];
  230. const xs = await trajectoryFromMmCIF(block).runInContext(ctx);
  231. if (xs.frameCount === 0) throw new Error('No models found.');
  232. for (let i = 0; i < xs.frameCount; i++) {
  233. const x = await Task.resolveInContext(xs.getFrameAtIndex(i), ctx);
  234. models.push(x);
  235. }
  236. }
  237. for (let i = 0; i < models.length; i++) {
  238. Model.TrajectoryInfo.set(models[i], { index: i, size: models.length });
  239. }
  240. const props = { label: 'Trajectory', description: `${models.length} model${models.length === 1 ? '' : 's'}` };
  241. return new SO.Molecule.Trajectory(new ArrayTrajectory(models), props);
  242. });
  243. }
  244. });
  245. function trajectoryProps(trajectory: Trajectory) {
  246. const first = trajectory.representative;
  247. return { label: `${first.entry}`, description: `${trajectory.frameCount} model${trajectory.frameCount === 1 ? '' : 's'}` };
  248. }
  249. type TrajectoryFromMmCif = typeof TrajectoryFromMmCif
  250. const TrajectoryFromMmCif = PluginStateTransform.BuiltIn({
  251. name: 'trajectory-from-mmcif',
  252. display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
  253. from: SO.Format.Cif,
  254. to: SO.Molecule.Trajectory,
  255. params(a) {
  256. if (!a) {
  257. return {
  258. loadAllBlocks: PD.Optional(PD.Boolean(false, { description: 'If True, ignore Block Header parameter and parse all datablocks into a single trajectory.' })),
  259. blockHeader: PD.Optional(PD.Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.', hideIf: p => p.loadAllBlocks === true })),
  260. };
  261. }
  262. const { blocks } = a.data;
  263. return {
  264. loadAllBlocks: PD.Optional(PD.Boolean(false, { description: 'If True, ignore Block Header parameter and parse all data blocks into a single trajectory.' })),
  265. blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, blocks.map(b => [b.header, b.header] as [string, string]), { description: 'Header of the block to parse', hideIf: p => p.loadAllBlocks === true })),
  266. };
  267. }
  268. })({
  269. isApplicable: a => a.data.blocks.length > 0,
  270. apply({ a, params }) {
  271. return Task.create('Parse mmCIF', async ctx => {
  272. let trajectory: Trajectory;
  273. if (params.loadAllBlocks) {
  274. const models: Model[] = [];
  275. for (const block of a.data.blocks) {
  276. if (ctx.shouldUpdate) {
  277. await ctx.update(`Parsing ${block.header}...`);
  278. }
  279. const t = await trajectoryFromMmCIF(block).runInContext(ctx);
  280. for (let i = 0; i < t.frameCount; i++) {
  281. models.push(await Task.resolveInContext(t.getFrameAtIndex(i), ctx));
  282. }
  283. }
  284. trajectory = new ArrayTrajectory(models);
  285. } else {
  286. const header = params.blockHeader || a.data.blocks[0].header;
  287. const block = a.data.blocks.find(b => b.header === header);
  288. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  289. const isCcd = block.categoryNames.includes('chem_comp_atom') && !block.categoryNames.includes('atom_site') && !block.categoryNames.includes('ihm_sphere_obj_site') && !block.categoryNames.includes('ihm_gaussian_obj_site');
  290. trajectory = isCcd ? await trajectoryFromCCD(block).runInContext(ctx) : await trajectoryFromMmCIF(block, a.data).runInContext(ctx);
  291. }
  292. if (trajectory.frameCount === 0) throw new Error('No models found.');
  293. const props = trajectoryProps(trajectory);
  294. return new SO.Molecule.Trajectory(trajectory, props);
  295. });
  296. }
  297. });
  298. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  299. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  300. name: 'trajectory-from-pdb',
  301. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  302. from: [SO.Data.String],
  303. to: SO.Molecule.Trajectory,
  304. params: {
  305. isPdbqt: PD.Boolean(false)
  306. }
  307. })({
  308. apply({ a, params }) {
  309. return Task.create('Parse PDB', async ctx => {
  310. const parsed = await parsePDB(a.data, a.label, params.isPdbqt).runInContext(ctx);
  311. if (parsed.isError) throw new Error(parsed.message);
  312. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  313. const props = trajectoryProps(models);
  314. return new SO.Molecule.Trajectory(models, props);
  315. });
  316. }
  317. });
  318. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  319. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  320. name: 'trajectory-from-gro',
  321. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  322. from: [SO.Data.String],
  323. to: SO.Molecule.Trajectory
  324. })({
  325. apply({ a }) {
  326. return Task.create('Parse GRO', async ctx => {
  327. const parsed = await parseGRO(a.data).runInContext(ctx);
  328. if (parsed.isError) throw new Error(parsed.message);
  329. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  330. const props = trajectoryProps(models);
  331. return new SO.Molecule.Trajectory(models, props);
  332. });
  333. }
  334. });
  335. type TrajectoryFromXYZ = typeof TrajectoryFromXYZ
  336. const TrajectoryFromXYZ = PluginStateTransform.BuiltIn({
  337. name: 'trajectory-from-xyz',
  338. display: { name: 'Parse XYZ', description: 'Parse XYZ string and create trajectory.' },
  339. from: [SO.Data.String],
  340. to: SO.Molecule.Trajectory
  341. })({
  342. apply({ a }) {
  343. return Task.create('Parse XYZ', async ctx => {
  344. const parsed = await parseXyz(a.data).runInContext(ctx);
  345. if (parsed.isError) throw new Error(parsed.message);
  346. const models = await trajectoryFromXyz(parsed.result).runInContext(ctx);
  347. const props = trajectoryProps(models);
  348. return new SO.Molecule.Trajectory(models, props);
  349. });
  350. }
  351. });
  352. type TrajectoryFromMOL = typeof TrajectoryFromMOL
  353. const TrajectoryFromMOL = PluginStateTransform.BuiltIn({
  354. name: 'trajectory-from-mol',
  355. display: { name: 'Parse MOL', description: 'Parse MOL string and create trajectory.' },
  356. from: [SO.Data.String],
  357. to: SO.Molecule.Trajectory
  358. })({
  359. apply({ a }) {
  360. return Task.create('Parse MOL', async ctx => {
  361. const parsed = await parseMol(a.data).runInContext(ctx);
  362. if (parsed.isError) throw new Error(parsed.message);
  363. const models = await trajectoryFromMol(parsed.result).runInContext(ctx);
  364. const props = trajectoryProps(models);
  365. return new SO.Molecule.Trajectory(models, props);
  366. });
  367. }
  368. });
  369. type TrajectoryFromSDF = typeof TrajectoryFromSDF
  370. const TrajectoryFromSDF = PluginStateTransform.BuiltIn({
  371. name: 'trajectory-from-sdf',
  372. display: { name: 'Parse SDF', description: 'Parse SDF string and create trajectory.' },
  373. from: [SO.Data.String],
  374. to: SO.Molecule.Trajectory
  375. })({
  376. apply({ a }) {
  377. return Task.create('Parse SDF', async ctx => {
  378. const parsed = await parseSdf(a.data).runInContext(ctx);
  379. if (parsed.isError) throw new Error(parsed.message);
  380. const models: Model[] = [];
  381. for (const compound of parsed.result.compounds) {
  382. const traj = await trajectoryFromSdf(compound).runInContext(ctx);
  383. for (let i = 0; i < traj.frameCount; i++) {
  384. models.push(await Task.resolveInContext(traj.getFrameAtIndex(i), ctx));
  385. }
  386. }
  387. const traj = new ArrayTrajectory(models);
  388. const props = trajectoryProps(traj);
  389. return new SO.Molecule.Trajectory(traj, props);
  390. });
  391. }
  392. });
  393. type TrajectoryFromMOL2 = typeof TrajectoryFromMOL
  394. const TrajectoryFromMOL2 = PluginStateTransform.BuiltIn({
  395. name: 'trajectory-from-mol2',
  396. display: { name: 'Parse MOL2', description: 'Parse MOL2 string and create trajectory.' },
  397. from: [SO.Data.String],
  398. to: SO.Molecule.Trajectory
  399. })({
  400. apply({ a }) {
  401. return Task.create('Parse MOL2', async ctx => {
  402. const parsed = await parseMol2(a.data, a.label).runInContext(ctx);
  403. if (parsed.isError) throw new Error(parsed.message);
  404. const models = await trajectoryFromMol2(parsed.result).runInContext(ctx);
  405. const props = trajectoryProps(models);
  406. return new SO.Molecule.Trajectory(models, props);
  407. });
  408. }
  409. });
  410. type TrajectoryFromCube = typeof TrajectoryFromCube
  411. const TrajectoryFromCube = PluginStateTransform.BuiltIn({
  412. name: 'trajectory-from-cube',
  413. display: { name: 'Parse Cube', description: 'Parse Cube file to create a trajectory.' },
  414. from: SO.Format.Cube,
  415. to: SO.Molecule.Trajectory
  416. })({
  417. apply({ a }) {
  418. return Task.create('Parse MOL', async ctx => {
  419. const models = await trajectoryFromCube(a.data).runInContext(ctx);
  420. const props = trajectoryProps(models);
  421. return new SO.Molecule.Trajectory(models, props);
  422. });
  423. }
  424. });
  425. type TrajectoryFromCifCore = typeof TrajectoryFromCifCore
  426. const TrajectoryFromCifCore = PluginStateTransform.BuiltIn({
  427. name: 'trajectory-from-cif-core',
  428. display: { name: 'Parse CIF Core', description: 'Identify and create all separate models in the specified CIF data block' },
  429. from: SO.Format.Cif,
  430. to: SO.Molecule.Trajectory,
  431. params(a) {
  432. if (!a) {
  433. return {
  434. blockHeader: PD.Optional(PD.Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.' }))
  435. };
  436. }
  437. const { blocks } = a.data;
  438. return {
  439. blockHeader: PD.Optional(PD.Select(blocks[0] && blocks[0].header, blocks.map(b => [b.header, b.header] as [string, string]), { description: 'Header of the block to parse' }))
  440. };
  441. }
  442. })({
  443. apply({ a, params }) {
  444. return Task.create('Parse CIF Core', async ctx => {
  445. const header = params.blockHeader || a.data.blocks[0].header;
  446. const block = a.data.blocks.find(b => b.header === header);
  447. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  448. const models = await trajectoryFromCifCore(block).runInContext(ctx);
  449. if (models.frameCount === 0) throw new Error('No models found.');
  450. const props = trajectoryProps(models);
  451. return new SO.Molecule.Trajectory(models, props);
  452. });
  453. }
  454. });
  455. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  456. type ModelFromTrajectory = typeof ModelFromTrajectory
  457. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  458. name: 'model-from-trajectory',
  459. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  460. from: SO.Molecule.Trajectory,
  461. to: SO.Molecule.Model,
  462. params: a => {
  463. if (!a) {
  464. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model', immediateUpdate: true }) };
  465. }
  466. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.frameCount, step: 1 }, { description: 'Model Index', immediateUpdate: true })) };
  467. }
  468. })({
  469. isApplicable: a => a.data.frameCount > 0,
  470. apply({ a, params }) {
  471. return Task.create('Model from Trajectory', async ctx => {
  472. let modelIndex = params.modelIndex % a.data.frameCount;
  473. if (modelIndex < 0) modelIndex += a.data.frameCount;
  474. const model = await Task.resolveInContext(a.data.getFrameAtIndex(modelIndex), ctx);
  475. const label = `Model ${modelIndex + 1}`;
  476. const description = a.data.frameCount === 1 ? undefined : `of ${a.data.frameCount}`;
  477. return new SO.Molecule.Model(model, { label, description });
  478. });
  479. },
  480. interpolate(a, b, t) {
  481. const modelIndex = t >= 1 ? b.modelIndex : a.modelIndex + Math.floor((b.modelIndex - a.modelIndex + 1) * t);
  482. return { modelIndex };
  483. },
  484. dispose({ b }) {
  485. b?.data.customProperties.dispose();
  486. }
  487. });
  488. type StructureFromTrajectory = typeof StructureFromTrajectory
  489. const StructureFromTrajectory = PluginStateTransform.BuiltIn({
  490. name: 'structure-from-trajectory',
  491. display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
  492. from: SO.Molecule.Trajectory,
  493. to: SO.Molecule.Structure
  494. })({
  495. apply({ a }) {
  496. return Task.create('Build Structure', async ctx => {
  497. const s = await Structure.ofTrajectory(a.data, ctx);
  498. const props = { label: 'Ensemble', description: Structure.elementDescription(s) };
  499. return new SO.Molecule.Structure(s, props);
  500. });
  501. },
  502. dispose({ b }) {
  503. b?.data.customPropertyDescriptors.dispose();
  504. }
  505. });
  506. type StructureFromModel = typeof StructureFromModel
  507. const StructureFromModel = PluginStateTransform.BuiltIn({
  508. name: 'structure-from-model',
  509. display: { name: 'Structure', description: 'Create a molecular structure (model, assembly, or symmetry) from the specified model.' },
  510. from: SO.Molecule.Model,
  511. to: SO.Molecule.Structure,
  512. params(a) { return RootStructureDefinition.getParams(a && a.data); }
  513. })({
  514. canAutoUpdate({ oldParams, newParams }) {
  515. return RootStructureDefinition.canAutoUpdate(oldParams.type, newParams.type);
  516. },
  517. apply({ a, params }, plugin: PluginContext) {
  518. return Task.create('Build Structure', async ctx => {
  519. return RootStructureDefinition.create(plugin, ctx, a.data, params && params.type);
  520. });
  521. },
  522. update: ({ a, b, oldParams, newParams }) => {
  523. if (!deepEqual(oldParams, newParams)) return StateTransformer.UpdateResult.Recreate;
  524. if (b.data.model === a.data) return StateTransformer.UpdateResult.Unchanged;
  525. if (!Model.areHierarchiesEqual(a.data, b.data.model)) return StateTransformer.UpdateResult.Recreate;
  526. b.data = b.data.remapModel(a.data);
  527. return StateTransformer.UpdateResult.Updated;
  528. },
  529. dispose({ b }) {
  530. b?.data.customPropertyDescriptors.dispose();
  531. }
  532. });
  533. const _translation = Vec3(), _m = Mat4(), _n = Mat4();
  534. type TransformStructureConformation = typeof TransformStructureConformation
  535. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  536. name: 'transform-structure-conformation',
  537. display: { name: 'Transform Conformation' },
  538. isDecorator: true,
  539. from: SO.Molecule.Structure,
  540. to: SO.Molecule.Structure,
  541. params: {
  542. transform: PD.MappedStatic('components', {
  543. components: PD.Group({
  544. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  545. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  546. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  547. }, { isFlat: true }),
  548. matrix: PD.Group({
  549. data: PD.Mat4(Mat4.identity()),
  550. transpose: PD.Boolean(false)
  551. }, { isFlat: true })
  552. }, { label: 'Kind' })
  553. }
  554. })({
  555. canAutoUpdate({ newParams }) {
  556. return newParams.transform.name !== 'matrix';
  557. },
  558. apply({ a, params }) {
  559. // TODO: optimze
  560. // TODO: think of ways how to fast-track changes to this for animations
  561. const transform = Mat4();
  562. if (params.transform.name === 'components') {
  563. const { axis, angle, translation } = params.transform.params;
  564. const center = a.data.boundary.sphere.center;
  565. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  566. Mat4.fromTranslation(_n, Vec3.add(_translation, center, translation));
  567. const rot = Mat4.fromRotation(Mat4(), Math.PI / 180 * angle, Vec3.normalize(Vec3(), axis));
  568. Mat4.mul3(transform, _n, rot, _m);
  569. } else if (params.transform.name === 'matrix') {
  570. Mat4.copy(transform, params.transform.params.data);
  571. if (params.transform.params.transpose) Mat4.transpose(transform, transform);
  572. }
  573. const s = Structure.transform(a.data, transform);
  574. return new SO.Molecule.Structure(s, { label: a.label, description: `${a.description} [Transformed]` });
  575. },
  576. dispose({ b }) {
  577. b?.data.customPropertyDescriptors.dispose();
  578. }
  579. // interpolate(src, tar, t) {
  580. // // TODO: optimize
  581. // const u = Mat4.fromRotation(Mat4(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
  582. // Mat4.setTranslation(u, src.translation);
  583. // const v = Mat4.fromRotation(Mat4(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
  584. // Mat4.setTranslation(v, tar.translation);
  585. // const m = SymmetryOperator.slerp(Mat4(), u, v, t);
  586. // const rot = Mat4.getRotation(Quat.zero(), m);
  587. // const axis = Vec3();
  588. // const angle = Quat.getAxisAngle(axis, rot);
  589. // const translation = Mat4.getTranslation(Vec3(), m);
  590. // return { axis, angle, translation };
  591. // }
  592. });
  593. type StructureSelectionFromExpression = typeof StructureSelectionFromExpression
  594. const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  595. name: 'structure-selection-from-expression',
  596. display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
  597. from: SO.Molecule.Structure,
  598. to: SO.Molecule.Structure,
  599. params: () => ({
  600. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  601. label: PD.Optional(PD.Text('', { isHidden: true }))
  602. })
  603. })({
  604. apply({ a, params, cache }) {
  605. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.expression);
  606. (cache as any).entry = entry;
  607. if (Sel.isEmpty(selection)) return StateObject.Null;
  608. const s = Sel.unionStructure(selection);
  609. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  610. return new SO.Molecule.Structure(s, props);
  611. },
  612. update: ({ a, b, oldParams, newParams, cache }) => {
  613. if (oldParams.expression !== newParams.expression) return StateTransformer.UpdateResult.Recreate;
  614. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  615. if (entry.currentStructure === a.data) {
  616. return StateTransformer.UpdateResult.Unchanged;
  617. }
  618. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  619. if (Sel.isEmpty(selection)) return StateTransformer.UpdateResult.Null;
  620. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  621. return StateTransformer.UpdateResult.Updated;
  622. },
  623. dispose({ b }) {
  624. b?.data.customPropertyDescriptors.dispose();
  625. }
  626. });
  627. type MultiStructureSelectionFromExpression = typeof MultiStructureSelectionFromExpression
  628. const MultiStructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  629. name: 'structure-multi-selection-from-expression',
  630. display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
  631. from: SO.Root,
  632. to: SO.Molecule.Structure.Selections,
  633. params: () => ({
  634. selections: PD.ObjectList({
  635. key: PD.Text(void 0, { description: 'A unique key.' }),
  636. ref: PD.Text(),
  637. groupId: PD.Optional(PD.Text()),
  638. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.empty)
  639. }, e => e.ref, { isHidden: true }),
  640. isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
  641. label: PD.Optional(PD.Text('', { isHidden: true }))
  642. })
  643. })({
  644. apply({ params, cache, dependencies }) {
  645. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  646. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  647. let totalSize = 0;
  648. for (const sel of params.selections) {
  649. const { selection, entry } = StructureQueryHelper.createAndRun(dependencies![sel.ref].data as Structure, sel.expression);
  650. entries.set(sel.key, entry);
  651. const loci = Sel.toLociWithSourceUnits(selection);
  652. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  653. totalSize += StructureElement.Loci.size(loci);
  654. }
  655. (cache as object as any).entries = entries;
  656. const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
  657. return new SO.Molecule.Structure.Selections(selections, props);
  658. },
  659. update: ({ b, oldParams, newParams, cache, dependencies }) => {
  660. if (!!oldParams.isTransitive !== !!newParams.isTransitive) return StateTransformer.UpdateResult.Recreate;
  661. const cacheEntries = (cache as any).entries as Map<string, StructureQueryHelper.CacheEntry>;
  662. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  663. const current = new Map<string, SO.Molecule.Structure.SelectionEntry>();
  664. for (const e of b.data) current.set(e.key, e);
  665. let changed = false;
  666. let totalSize = 0;
  667. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  668. for (const sel of newParams.selections) {
  669. const structure = dependencies![sel.ref].data as Structure;
  670. let recreate = false;
  671. if (cacheEntries.has(sel.key)) {
  672. const entry = cacheEntries.get(sel.key)!;
  673. if (StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
  674. const loci = current.get(sel.key)!;
  675. if (loci.groupId !== sel.groupId) {
  676. loci.groupId = sel.groupId;
  677. changed = true;
  678. }
  679. entries.set(sel.key, entry);
  680. selections.push(loci);
  681. totalSize += StructureElement.Loci.size(loci.loci);
  682. continue;
  683. }
  684. if (entry.expression !== sel.expression) {
  685. recreate = true;
  686. } else {
  687. // TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
  688. let update = false;
  689. if (!!newParams.isTransitive) {
  690. if (Structure.areUnitIdsAndIndicesEqual(entry.originalStructure, structure)) {
  691. const selection = StructureQueryHelper.run(entry, entry.originalStructure);
  692. entry.currentStructure = structure;
  693. entries.set(sel.key, entry);
  694. const loci = StructureElement.Loci.remap(Sel.toLociWithSourceUnits(selection), structure);
  695. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  696. totalSize += StructureElement.Loci.size(loci);
  697. changed = true;
  698. } else {
  699. update = true;
  700. }
  701. } else {
  702. update = true;
  703. }
  704. if (update) {
  705. changed = true;
  706. const selection = StructureQueryHelper.updateStructure(entry, structure);
  707. entries.set(sel.key, entry);
  708. const loci = Sel.toLociWithSourceUnits(selection);
  709. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  710. totalSize += StructureElement.Loci.size(loci);
  711. }
  712. }
  713. } else {
  714. recreate = true;
  715. }
  716. if (recreate) {
  717. changed = true;
  718. // create new selection
  719. const { selection, entry } = StructureQueryHelper.createAndRun(structure, sel.expression);
  720. entries.set(sel.key, entry);
  721. const loci = Sel.toLociWithSourceUnits(selection);
  722. selections.push({ key: sel.key, loci });
  723. totalSize += StructureElement.Loci.size(loci);
  724. }
  725. }
  726. if (!changed) return StateTransformer.UpdateResult.Unchanged;
  727. (cache as object as any).entries = entries;
  728. b.data = selections;
  729. b.label = `${newParams.label || 'Multi-selection'}`;
  730. b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
  731. return StateTransformer.UpdateResult.Updated;
  732. }
  733. });
  734. type StructureSelectionFromScript = typeof StructureSelectionFromScript
  735. const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
  736. name: 'structure-selection-from-script',
  737. display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
  738. from: SO.Molecule.Structure,
  739. to: SO.Molecule.Structure,
  740. params: () => ({
  741. script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  742. label: PD.Optional(PD.Text(''))
  743. })
  744. })({
  745. apply({ a, params, cache }) {
  746. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.script);
  747. (cache as any).entry = entry;
  748. const s = Sel.unionStructure(selection);
  749. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  750. return new SO.Molecule.Structure(s, props);
  751. },
  752. update: ({ a, b, oldParams, newParams, cache }) => {
  753. if (!Script.areEqual(oldParams.script, newParams.script)) {
  754. return StateTransformer.UpdateResult.Recreate;
  755. }
  756. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  757. if (entry.currentStructure === a.data) {
  758. return StateTransformer.UpdateResult.Unchanged;
  759. }
  760. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  761. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  762. return StateTransformer.UpdateResult.Updated;
  763. },
  764. dispose({ b }) {
  765. b?.data.customPropertyDescriptors.dispose();
  766. }
  767. });
  768. type StructureSelectionFromBundle = typeof StructureSelectionFromBundle
  769. const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
  770. name: 'structure-selection-from-bundle',
  771. display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
  772. from: SO.Molecule.Structure,
  773. to: SO.Molecule.Structure,
  774. params: () => ({
  775. bundle: PD.Value<StructureElement.Bundle>(StructureElement.Bundle.Empty, { isHidden: true }),
  776. label: PD.Optional(PD.Text('', { isHidden: true }))
  777. })
  778. })({
  779. apply({ a, params, cache }) {
  780. if (params.bundle.hash !== a.data.hashCode) {
  781. return StateObject.Null;
  782. }
  783. (cache as { source: Structure }).source = a.data;
  784. const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
  785. if (s.elementCount === 0) return StateObject.Null;
  786. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  787. return new SO.Molecule.Structure(s, props);
  788. },
  789. update: ({ a, b, oldParams, newParams, cache }) => {
  790. if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
  791. return StateTransformer.UpdateResult.Recreate;
  792. }
  793. if (newParams.bundle.hash !== a.data.hashCode) {
  794. return StateTransformer.UpdateResult.Null;
  795. }
  796. if ((cache as { source: Structure }).source === a.data) {
  797. return StateTransformer.UpdateResult.Unchanged;
  798. }
  799. (cache as { source: Structure }).source = a.data;
  800. const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
  801. if (s.elementCount === 0) return StateTransformer.UpdateResult.Null;
  802. b.label = `${newParams.label || 'Selection'}`;
  803. b.description = Structure.elementDescription(s);
  804. b.data = s;
  805. return StateTransformer.UpdateResult.Updated;
  806. },
  807. dispose({ b }) {
  808. b?.data.customPropertyDescriptors.dispose();
  809. }
  810. });
  811. export const StructureComplexElementTypes = {
  812. 'polymer': 'polymer',
  813. 'protein': 'protein',
  814. 'nucleic': 'nucleic',
  815. 'water': 'water',
  816. 'branched': 'branched', // = carbs
  817. 'ligand': 'ligand',
  818. 'non-standard': 'non-standard',
  819. 'coarse': 'coarse',
  820. // Legacy
  821. 'atomic-sequence': 'atomic-sequence',
  822. 'atomic-het': 'atomic-het',
  823. 'spheres': 'spheres'
  824. } as const;
  825. export type StructureComplexElementTypes = keyof typeof StructureComplexElementTypes
  826. const StructureComplexElementTypeTuples = PD.objectToOptions(StructureComplexElementTypes);
  827. type StructureComplexElement = typeof StructureComplexElement
  828. const StructureComplexElement = PluginStateTransform.BuiltIn({
  829. name: 'structure-complex-element',
  830. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  831. from: SO.Molecule.Structure,
  832. to: SO.Molecule.Structure,
  833. params: { type: PD.Select<StructureComplexElementTypes>('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
  834. })({
  835. apply({ a, params }) {
  836. // TODO: update function.
  837. let query: StructureQuery, label: string;
  838. switch (params.type) {
  839. case 'polymer': query = StructureSelectionQueries.polymer.query; label = 'Polymer'; break;
  840. case 'protein': query = StructureSelectionQueries.protein.query; label = 'Protein'; break;
  841. case 'nucleic': query = StructureSelectionQueries.nucleic.query; label = 'Nucleic'; break;
  842. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  843. case 'branched': query = StructureSelectionQueries.branchedPlusConnected.query; label = 'Branched'; break;
  844. case 'ligand': query = StructureSelectionQueries.ligandPlusConnected.query; label = 'Ligand'; break;
  845. case 'non-standard': query = StructureSelectionQueries.nonStandardPolymer.query; label = 'Non-standard'; break;
  846. case 'coarse': query = StructureSelectionQueries.coarse.query; label = 'Coarse'; break;
  847. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  848. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  849. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  850. default: assertUnreachable(params.type);
  851. }
  852. const result = query(new QueryContext(a.data));
  853. const s = Sel.unionStructure(result);
  854. if (s.elementCount === 0) return StateObject.Null;
  855. return new SO.Molecule.Structure(s, { label, description: Structure.elementDescription(s) });
  856. },
  857. dispose({ b }) {
  858. b?.data.customPropertyDescriptors.dispose();
  859. }
  860. });
  861. type StructureComponent = typeof StructureComponent
  862. const StructureComponent = PluginStateTransform.BuiltIn({
  863. name: 'structure-component',
  864. display: { name: 'Component', description: 'A molecular structure component.' },
  865. from: SO.Molecule.Structure,
  866. to: SO.Molecule.Structure,
  867. params: StructureComponentParams
  868. })({
  869. apply({ a, params, cache }) {
  870. return createStructureComponent(a.data, params, cache as any);
  871. },
  872. update: ({ a, b, oldParams, newParams, cache }) => {
  873. return updateStructureComponent(a.data, b, oldParams, newParams, cache as any);
  874. },
  875. dispose({ b }) {
  876. b?.data.customPropertyDescriptors.dispose();
  877. }
  878. });
  879. type CustomModelProperties = typeof CustomModelProperties
  880. const CustomModelProperties = PluginStateTransform.BuiltIn({
  881. name: 'custom-model-properties',
  882. display: { name: 'Custom Model Properties' },
  883. isDecorator: true,
  884. from: SO.Molecule.Model,
  885. to: SO.Molecule.Model,
  886. params: (a, ctx: PluginContext) => {
  887. return ctx.customModelProperties.getParams(a?.data);
  888. }
  889. })({
  890. apply({ a, params }, ctx: PluginContext) {
  891. return Task.create('Custom Props', async taskCtx => {
  892. await attachModelProps(a.data, ctx, taskCtx, params);
  893. return new SO.Molecule.Model(a.data, { label: a.label, description: a.description });
  894. });
  895. },
  896. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  897. return Task.create('Custom Props', async taskCtx => {
  898. b.data = a.data;
  899. b.label = a.label;
  900. b.description = a.description;
  901. for (const name of oldParams.autoAttach) {
  902. const property = ctx.customModelProperties.get(name);
  903. if (!property) continue;
  904. a.data.customProperties.reference(property.descriptor, false);
  905. }
  906. await attachModelProps(a.data, ctx, taskCtx, newParams);
  907. return StateTransformer.UpdateResult.Updated;
  908. });
  909. },
  910. dispose({ b }) {
  911. b?.data.customProperties.dispose();
  912. }
  913. });
  914. async function attachModelProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomModelProperties['createDefaultParams']>) {
  915. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  916. const { autoAttach, properties } = params;
  917. for (const name of Object.keys(properties)) {
  918. const property = ctx.customModelProperties.get(name)!;
  919. const props = properties[name];
  920. if (autoAttach.includes(name) || property.isHidden) {
  921. try {
  922. await property.attach(propertyCtx, model, props, true);
  923. } catch (e) {
  924. ctx.log.warn(`Error attaching model prop '${name}': ${e}`);
  925. }
  926. } else {
  927. property.set(model, props);
  928. }
  929. }
  930. }
  931. type CustomStructureProperties = typeof CustomStructureProperties
  932. const CustomStructureProperties = PluginStateTransform.BuiltIn({
  933. name: 'custom-structure-properties',
  934. display: { name: 'Custom Structure Properties' },
  935. isDecorator: true,
  936. from: SO.Molecule.Structure,
  937. to: SO.Molecule.Structure,
  938. params: (a, ctx: PluginContext) => {
  939. return ctx.customStructureProperties.getParams(a?.data.root);
  940. }
  941. })({
  942. apply({ a, params }, ctx: PluginContext) {
  943. return Task.create('Custom Props', async taskCtx => {
  944. await attachStructureProps(a.data.root, ctx, taskCtx, params);
  945. return new SO.Molecule.Structure(a.data, { label: a.label, description: a.description });
  946. });
  947. },
  948. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  949. if (a.data !== b.data) return StateTransformer.UpdateResult.Recreate;
  950. return Task.create('Custom Props', async taskCtx => {
  951. b.data = a.data;
  952. b.label = a.label;
  953. b.description = a.description;
  954. for (const name of oldParams.autoAttach) {
  955. const property = ctx.customStructureProperties.get(name);
  956. if (!property) continue;
  957. a.data.customPropertyDescriptors.reference(property.descriptor, false);
  958. }
  959. await attachStructureProps(a.data.root, ctx, taskCtx, newParams);
  960. return StateTransformer.UpdateResult.Updated;
  961. });
  962. },
  963. dispose({ b }) {
  964. b?.data.customPropertyDescriptors.dispose();
  965. }
  966. });
  967. async function attachStructureProps(structure: Structure, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomStructureProperties['createDefaultParams']>) {
  968. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  969. const { autoAttach, properties } = params;
  970. for (const name of Object.keys(properties)) {
  971. const property = ctx.customStructureProperties.get(name)!;
  972. const props = properties[name];
  973. if (autoAttach.includes(name) || property.isHidden) {
  974. try {
  975. await property.attach(propertyCtx, structure, props, true);
  976. } catch (e) {
  977. ctx.log.warn(`Error attaching structure prop '${name}': ${e}`);
  978. }
  979. } else {
  980. property.set(structure, props);
  981. }
  982. }
  983. }
  984. type ShapeFromPly = typeof ShapeFromPly
  985. const ShapeFromPly = PluginStateTransform.BuiltIn({
  986. name: 'shape-from-ply',
  987. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  988. from: SO.Format.Ply,
  989. to: SO.Shape.Provider,
  990. params(a) {
  991. return { };
  992. }
  993. })({
  994. apply({ a, params }) {
  995. return Task.create('Create shape from PLY', async ctx => {
  996. const shape = await shapeFromPly(a.data, params).runInContext(ctx);
  997. const props = { label: 'Shape' };
  998. return new SO.Shape.Provider(shape, props);
  999. });
  1000. }
  1001. });