model.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  1. /**
  2. * Copyright (c) 2018-2022 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 { 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. 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.' }))
  259. };
  260. }
  261. const { blocks } = a.data;
  262. return {
  263. 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' }))
  264. };
  265. }
  266. })({
  267. isApplicable: a => a.data.blocks.length > 0,
  268. apply({ a, params }) {
  269. return Task.create('Parse mmCIF', async ctx => {
  270. const header = params.blockHeader || a.data.blocks[0].header;
  271. const block = a.data.blocks.find(b => b.header === header);
  272. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  273. const models = await trajectoryFromMmCIF(block).runInContext(ctx);
  274. if (models.frameCount === 0) throw new Error('No models found.');
  275. const props = trajectoryProps(models);
  276. return new SO.Molecule.Trajectory(models, props);
  277. });
  278. }
  279. });
  280. type TrajectoryFromPDB = typeof TrajectoryFromPDB
  281. const TrajectoryFromPDB = PluginStateTransform.BuiltIn({
  282. name: 'trajectory-from-pdb',
  283. display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
  284. from: [SO.Data.String],
  285. to: SO.Molecule.Trajectory,
  286. params: {
  287. isPdbqt: PD.Boolean(false)
  288. }
  289. })({
  290. apply({ a, params }) {
  291. return Task.create('Parse PDB', async ctx => {
  292. const parsed = await parsePDB(a.data, a.label, params.isPdbqt).runInContext(ctx);
  293. if (parsed.isError) throw new Error(parsed.message);
  294. const models = await trajectoryFromPDB(parsed.result).runInContext(ctx);
  295. const props = trajectoryProps(models);
  296. return new SO.Molecule.Trajectory(models, props);
  297. });
  298. }
  299. });
  300. type TrajectoryFromGRO = typeof TrajectoryFromGRO
  301. const TrajectoryFromGRO = PluginStateTransform.BuiltIn({
  302. name: 'trajectory-from-gro',
  303. display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
  304. from: [SO.Data.String],
  305. to: SO.Molecule.Trajectory
  306. })({
  307. apply({ a }) {
  308. return Task.create('Parse GRO', async ctx => {
  309. const parsed = await parseGRO(a.data).runInContext(ctx);
  310. if (parsed.isError) throw new Error(parsed.message);
  311. const models = await trajectoryFromGRO(parsed.result).runInContext(ctx);
  312. const props = trajectoryProps(models);
  313. return new SO.Molecule.Trajectory(models, props);
  314. });
  315. }
  316. });
  317. type TrajectoryFromXYZ = typeof TrajectoryFromXYZ
  318. const TrajectoryFromXYZ = PluginStateTransform.BuiltIn({
  319. name: 'trajectory-from-xyz',
  320. display: { name: 'Parse XYZ', description: 'Parse XYZ string and create trajectory.' },
  321. from: [SO.Data.String],
  322. to: SO.Molecule.Trajectory
  323. })({
  324. apply({ a }) {
  325. return Task.create('Parse XYZ', async ctx => {
  326. const parsed = await parseXyz(a.data).runInContext(ctx);
  327. if (parsed.isError) throw new Error(parsed.message);
  328. const models = await trajectoryFromXyz(parsed.result).runInContext(ctx);
  329. const props = trajectoryProps(models);
  330. return new SO.Molecule.Trajectory(models, props);
  331. });
  332. }
  333. });
  334. type TrajectoryFromMOL = typeof TrajectoryFromMOL
  335. const TrajectoryFromMOL = PluginStateTransform.BuiltIn({
  336. name: 'trajectory-from-mol',
  337. display: { name: 'Parse MOL', description: 'Parse MOL string and create trajectory.' },
  338. from: [SO.Data.String],
  339. to: SO.Molecule.Trajectory
  340. })({
  341. apply({ a }) {
  342. return Task.create('Parse MOL', async ctx => {
  343. const parsed = await parseMol(a.data).runInContext(ctx);
  344. if (parsed.isError) throw new Error(parsed.message);
  345. const models = await trajectoryFromMol(parsed.result).runInContext(ctx);
  346. const props = trajectoryProps(models);
  347. return new SO.Molecule.Trajectory(models, props);
  348. });
  349. }
  350. });
  351. type TrajectoryFromSDF = typeof TrajectoryFromSDF
  352. const TrajectoryFromSDF = PluginStateTransform.BuiltIn({
  353. name: 'trajectory-from-sdf',
  354. display: { name: 'Parse SDF', description: 'Parse SDF string and create trajectory.' },
  355. from: [SO.Data.String],
  356. to: SO.Molecule.Trajectory
  357. })({
  358. apply({ a }) {
  359. return Task.create('Parse SDF', async ctx => {
  360. const parsed = await parseSdf(a.data).runInContext(ctx);
  361. if (parsed.isError) throw new Error(parsed.message);
  362. const models: Model[] = [];
  363. for (const compound of parsed.result.compounds) {
  364. const traj = await trajectoryFromSdf(compound).runInContext(ctx);
  365. for (let i = 0; i < traj.frameCount; i++) {
  366. models.push(await Task.resolveInContext(traj.getFrameAtIndex(i), ctx));
  367. }
  368. }
  369. const traj = new ArrayTrajectory(models);
  370. const props = trajectoryProps(traj);
  371. return new SO.Molecule.Trajectory(traj, props);
  372. });
  373. }
  374. });
  375. type TrajectoryFromMOL2 = typeof TrajectoryFromMOL
  376. const TrajectoryFromMOL2 = PluginStateTransform.BuiltIn({
  377. name: 'trajectory-from-mol2',
  378. display: { name: 'Parse MOL2', description: 'Parse MOL2 string and create trajectory.' },
  379. from: [SO.Data.String],
  380. to: SO.Molecule.Trajectory
  381. })({
  382. apply({ a }) {
  383. return Task.create('Parse MOL2', async ctx => {
  384. const parsed = await parseMol2(a.data, a.label).runInContext(ctx);
  385. if (parsed.isError) throw new Error(parsed.message);
  386. const models = await trajectoryFromMol2(parsed.result).runInContext(ctx);
  387. const props = trajectoryProps(models);
  388. return new SO.Molecule.Trajectory(models, props);
  389. });
  390. }
  391. });
  392. type TrajectoryFromCube = typeof TrajectoryFromCube
  393. const TrajectoryFromCube = PluginStateTransform.BuiltIn({
  394. name: 'trajectory-from-cube',
  395. display: { name: 'Parse Cube', description: 'Parse Cube file to create a trajectory.' },
  396. from: SO.Format.Cube,
  397. to: SO.Molecule.Trajectory
  398. })({
  399. apply({ a }) {
  400. return Task.create('Parse MOL', async ctx => {
  401. const models = await trajectoryFromCube(a.data).runInContext(ctx);
  402. const props = trajectoryProps(models);
  403. return new SO.Molecule.Trajectory(models, props);
  404. });
  405. }
  406. });
  407. type TrajectoryFromCifCore = typeof TrajectoryFromCifCore
  408. const TrajectoryFromCifCore = PluginStateTransform.BuiltIn({
  409. name: 'trajectory-from-cif-core',
  410. display: { name: 'Parse CIF Core', description: 'Identify and create all separate models in the specified CIF data block' },
  411. from: SO.Format.Cif,
  412. to: SO.Molecule.Trajectory,
  413. params(a) {
  414. if (!a) {
  415. return {
  416. 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.' }))
  417. };
  418. }
  419. const { blocks } = a.data;
  420. return {
  421. 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' }))
  422. };
  423. }
  424. })({
  425. apply({ a, params }) {
  426. return Task.create('Parse CIF Core', async ctx => {
  427. const header = params.blockHeader || a.data.blocks[0].header;
  428. const block = a.data.blocks.find(b => b.header === header);
  429. if (!block) throw new Error(`Data block '${[header]}' not found.`);
  430. const models = await trajectoryFromCifCore(block).runInContext(ctx);
  431. if (models.frameCount === 0) throw new Error('No models found.');
  432. const props = trajectoryProps(models);
  433. return new SO.Molecule.Trajectory(models, props);
  434. });
  435. }
  436. });
  437. const plus1 = (v: number) => v + 1, minus1 = (v: number) => v - 1;
  438. type ModelFromTrajectory = typeof ModelFromTrajectory
  439. const ModelFromTrajectory = PluginStateTransform.BuiltIn({
  440. name: 'model-from-trajectory',
  441. display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
  442. from: SO.Molecule.Trajectory,
  443. to: SO.Molecule.Model,
  444. params: a => {
  445. if (!a) {
  446. return { modelIndex: PD.Numeric(0, {}, { description: 'Zero-based index of the model', immediateUpdate: true }) };
  447. }
  448. return { modelIndex: PD.Converted(plus1, minus1, PD.Numeric(1, { min: 1, max: a.data.frameCount, step: 1 }, { description: 'Model Index', immediateUpdate: true })) };
  449. }
  450. })({
  451. isApplicable: a => a.data.frameCount > 0,
  452. apply({ a, params }) {
  453. return Task.create('Model from Trajectory', async ctx => {
  454. let modelIndex = params.modelIndex % a.data.frameCount;
  455. if (modelIndex < 0) modelIndex += a.data.frameCount;
  456. const model = await Task.resolveInContext(a.data.getFrameAtIndex(modelIndex), ctx);
  457. const label = `Model ${modelIndex + 1}`;
  458. const description = a.data.frameCount === 1 ? undefined : `of ${a.data.frameCount}`;
  459. return new SO.Molecule.Model(model, { label, description });
  460. });
  461. },
  462. interpolate(a, b, t) {
  463. const modelIndex = t >= 1 ? b.modelIndex : a.modelIndex + Math.floor((b.modelIndex - a.modelIndex + 1) * t);
  464. return { modelIndex };
  465. },
  466. dispose({ b }) {
  467. b?.data.customProperties.dispose();
  468. }
  469. });
  470. type StructureFromTrajectory = typeof StructureFromTrajectory
  471. const StructureFromTrajectory = PluginStateTransform.BuiltIn({
  472. name: 'structure-from-trajectory',
  473. display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
  474. from: SO.Molecule.Trajectory,
  475. to: SO.Molecule.Structure
  476. })({
  477. apply({ a }) {
  478. return Task.create('Build Structure', async ctx => {
  479. const s = await Structure.ofTrajectory(a.data, ctx);
  480. const props = { label: 'Ensemble', description: Structure.elementDescription(s) };
  481. return new SO.Molecule.Structure(s, props);
  482. });
  483. },
  484. dispose({ b }) {
  485. b?.data.customPropertyDescriptors.dispose();
  486. }
  487. });
  488. type StructureFromModel = typeof StructureFromModel
  489. const StructureFromModel = PluginStateTransform.BuiltIn({
  490. name: 'structure-from-model',
  491. display: { name: 'Structure', description: 'Create a molecular structure (model, assembly, or symmetry) from the specified model.' },
  492. from: SO.Molecule.Model,
  493. to: SO.Molecule.Structure,
  494. params(a) { return RootStructureDefinition.getParams(a && a.data); }
  495. })({
  496. canAutoUpdate({ oldParams, newParams }) {
  497. return RootStructureDefinition.canAutoUpdate(oldParams.type, newParams.type);
  498. },
  499. apply({ a, params }, plugin: PluginContext) {
  500. return Task.create('Build Structure', async ctx => {
  501. return RootStructureDefinition.create(plugin, ctx, a.data, params && params.type);
  502. });
  503. },
  504. update: ({ a, b, oldParams, newParams }) => {
  505. if (!deepEqual(oldParams, newParams)) return StateTransformer.UpdateResult.Recreate;
  506. if (b.data.model === a.data) return StateTransformer.UpdateResult.Unchanged;
  507. if (!Model.areHierarchiesEqual(a.data, b.data.model)) return StateTransformer.UpdateResult.Recreate;
  508. b.data = b.data.remapModel(a.data);
  509. return StateTransformer.UpdateResult.Updated;
  510. },
  511. dispose({ b }) {
  512. b?.data.customPropertyDescriptors.dispose();
  513. }
  514. });
  515. const _translation = Vec3(), _m = Mat4(), _n = Mat4();
  516. type TransformStructureConformation = typeof TransformStructureConformation
  517. const TransformStructureConformation = PluginStateTransform.BuiltIn({
  518. name: 'transform-structure-conformation',
  519. display: { name: 'Transform Conformation' },
  520. isDecorator: true,
  521. from: SO.Molecule.Structure,
  522. to: SO.Molecule.Structure,
  523. params: {
  524. transform: PD.MappedStatic('components', {
  525. components: PD.Group({
  526. axis: PD.Vec3(Vec3.create(1, 0, 0)),
  527. angle: PD.Numeric(0, { min: -180, max: 180, step: 0.1 }),
  528. translation: PD.Vec3(Vec3.create(0, 0, 0)),
  529. }, { isFlat: true }),
  530. matrix: PD.Group({
  531. data: PD.Mat4(Mat4.identity()),
  532. transpose: PD.Boolean(false)
  533. }, { isFlat: true })
  534. }, { label: 'Kind' })
  535. }
  536. })({
  537. canAutoUpdate({ newParams }) {
  538. return newParams.transform.name !== 'matrix';
  539. },
  540. apply({ a, params }) {
  541. // TODO: optimze
  542. // TODO: think of ways how to fast-track changes to this for animations
  543. const transform = Mat4();
  544. if (params.transform.name === 'components') {
  545. const { axis, angle, translation } = params.transform.params;
  546. const center = a.data.boundary.sphere.center;
  547. Mat4.fromTranslation(_m, Vec3.negate(_translation, center));
  548. Mat4.fromTranslation(_n, Vec3.add(_translation, center, translation));
  549. const rot = Mat4.fromRotation(Mat4(), Math.PI / 180 * angle, Vec3.normalize(Vec3(), axis));
  550. Mat4.mul3(transform, _n, rot, _m);
  551. } else if (params.transform.name === 'matrix') {
  552. Mat4.copy(transform, params.transform.params.data);
  553. if (params.transform.params.transpose) Mat4.transpose(transform, transform);
  554. }
  555. const s = Structure.transform(a.data, transform);
  556. return new SO.Molecule.Structure(s, { label: a.label, description: `${a.description} [Transformed]` });
  557. },
  558. dispose({ b }) {
  559. b?.data.customPropertyDescriptors.dispose();
  560. }
  561. // interpolate(src, tar, t) {
  562. // // TODO: optimize
  563. // const u = Mat4.fromRotation(Mat4(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
  564. // Mat4.setTranslation(u, src.translation);
  565. // const v = Mat4.fromRotation(Mat4(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
  566. // Mat4.setTranslation(v, tar.translation);
  567. // const m = SymmetryOperator.slerp(Mat4(), u, v, t);
  568. // const rot = Mat4.getRotation(Quat.zero(), m);
  569. // const axis = Vec3();
  570. // const angle = Quat.getAxisAngle(axis, rot);
  571. // const translation = Mat4.getTranslation(Vec3(), m);
  572. // return { axis, angle, translation };
  573. // }
  574. });
  575. type StructureSelectionFromExpression = typeof StructureSelectionFromExpression
  576. const StructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  577. name: 'structure-selection-from-expression',
  578. display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
  579. from: SO.Molecule.Structure,
  580. to: SO.Molecule.Structure,
  581. params: () => ({
  582. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.all, { isHidden: true }),
  583. label: PD.Optional(PD.Text('', { isHidden: true }))
  584. })
  585. })({
  586. apply({ a, params, cache }) {
  587. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.expression);
  588. (cache as any).entry = entry;
  589. if (Sel.isEmpty(selection)) return StateObject.Null;
  590. const s = Sel.unionStructure(selection);
  591. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  592. return new SO.Molecule.Structure(s, props);
  593. },
  594. update: ({ a, b, oldParams, newParams, cache }) => {
  595. if (oldParams.expression !== newParams.expression) return StateTransformer.UpdateResult.Recreate;
  596. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  597. if (entry.currentStructure === a.data) {
  598. return StateTransformer.UpdateResult.Unchanged;
  599. }
  600. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  601. if (Sel.isEmpty(selection)) return StateTransformer.UpdateResult.Null;
  602. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  603. return StateTransformer.UpdateResult.Updated;
  604. },
  605. dispose({ b }) {
  606. b?.data.customPropertyDescriptors.dispose();
  607. }
  608. });
  609. type MultiStructureSelectionFromExpression = typeof MultiStructureSelectionFromExpression
  610. const MultiStructureSelectionFromExpression = PluginStateTransform.BuiltIn({
  611. name: 'structure-multi-selection-from-expression',
  612. display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
  613. from: SO.Root,
  614. to: SO.Molecule.Structure.Selections,
  615. params: () => ({
  616. selections: PD.ObjectList({
  617. key: PD.Text(void 0, { description: 'A unique key.' }),
  618. ref: PD.Text(),
  619. groupId: PD.Optional(PD.Text()),
  620. expression: PD.Value<Expression>(MolScriptBuilder.struct.generator.empty)
  621. }, e => e.ref, { isHidden: true }),
  622. isTransitive: PD.Optional(PD.Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
  623. label: PD.Optional(PD.Text('', { isHidden: true }))
  624. })
  625. })({
  626. apply({ params, cache, dependencies }) {
  627. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  628. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  629. let totalSize = 0;
  630. for (const sel of params.selections) {
  631. const { selection, entry } = StructureQueryHelper.createAndRun(dependencies![sel.ref].data as Structure, sel.expression);
  632. entries.set(sel.key, entry);
  633. const loci = Sel.toLociWithSourceUnits(selection);
  634. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  635. totalSize += StructureElement.Loci.size(loci);
  636. }
  637. (cache as object as any).entries = entries;
  638. const props = { label: `${params.label || 'Multi-selection'}`, description: `${params.selections.length} source(s), ${totalSize} element(s) total` };
  639. return new SO.Molecule.Structure.Selections(selections, props);
  640. },
  641. update: ({ b, oldParams, newParams, cache, dependencies }) => {
  642. if (!!oldParams.isTransitive !== !!newParams.isTransitive) return StateTransformer.UpdateResult.Recreate;
  643. const cacheEntries = (cache as any).entries as Map<string, StructureQueryHelper.CacheEntry>;
  644. const entries = new Map<string, StructureQueryHelper.CacheEntry>();
  645. const current = new Map<string, SO.Molecule.Structure.SelectionEntry>();
  646. for (const e of b.data) current.set(e.key, e);
  647. let changed = false;
  648. let totalSize = 0;
  649. const selections: SO.Molecule.Structure.SelectionEntry[] = [];
  650. for (const sel of newParams.selections) {
  651. const structure = dependencies![sel.ref].data as Structure;
  652. let recreate = false;
  653. if (cacheEntries.has(sel.key)) {
  654. const entry = cacheEntries.get(sel.key)!;
  655. if (StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
  656. const loci = current.get(sel.key)!;
  657. if (loci.groupId !== sel.groupId) {
  658. loci.groupId = sel.groupId;
  659. changed = true;
  660. }
  661. entries.set(sel.key, entry);
  662. selections.push(loci);
  663. totalSize += StructureElement.Loci.size(loci.loci);
  664. continue;
  665. }
  666. if (entry.expression !== sel.expression) {
  667. recreate = true;
  668. } else {
  669. // TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
  670. let update = false;
  671. if (!!newParams.isTransitive) {
  672. if (Structure.areUnitIdsAndIndicesEqual(entry.originalStructure, structure)) {
  673. const selection = StructureQueryHelper.run(entry, entry.originalStructure);
  674. entry.currentStructure = structure;
  675. entries.set(sel.key, entry);
  676. const loci = StructureElement.Loci.remap(Sel.toLociWithSourceUnits(selection), structure);
  677. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  678. totalSize += StructureElement.Loci.size(loci);
  679. changed = true;
  680. } else {
  681. update = true;
  682. }
  683. } else {
  684. update = true;
  685. }
  686. if (update) {
  687. changed = true;
  688. const selection = StructureQueryHelper.updateStructure(entry, structure);
  689. entries.set(sel.key, entry);
  690. const loci = Sel.toLociWithSourceUnits(selection);
  691. selections.push({ key: sel.key, loci, groupId: sel.groupId });
  692. totalSize += StructureElement.Loci.size(loci);
  693. }
  694. }
  695. } else {
  696. recreate = true;
  697. }
  698. if (recreate) {
  699. changed = true;
  700. // create new selection
  701. const { selection, entry } = StructureQueryHelper.createAndRun(structure, sel.expression);
  702. entries.set(sel.key, entry);
  703. const loci = Sel.toLociWithSourceUnits(selection);
  704. selections.push({ key: sel.key, loci });
  705. totalSize += StructureElement.Loci.size(loci);
  706. }
  707. }
  708. if (!changed) return StateTransformer.UpdateResult.Unchanged;
  709. (cache as object as any).entries = entries;
  710. b.data = selections;
  711. b.label = `${newParams.label || 'Multi-selection'}`;
  712. b.description = `${selections.length} source(s), ${totalSize} element(s) total`;
  713. return StateTransformer.UpdateResult.Updated;
  714. }
  715. });
  716. type StructureSelectionFromScript = typeof StructureSelectionFromScript
  717. const StructureSelectionFromScript = PluginStateTransform.BuiltIn({
  718. name: 'structure-selection-from-script',
  719. display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
  720. from: SO.Molecule.Structure,
  721. to: SO.Molecule.Structure,
  722. params: () => ({
  723. script: PD.Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
  724. label: PD.Optional(PD.Text(''))
  725. })
  726. })({
  727. apply({ a, params, cache }) {
  728. const { selection, entry } = StructureQueryHelper.createAndRun(a.data, params.script);
  729. (cache as any).entry = entry;
  730. const s = Sel.unionStructure(selection);
  731. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  732. return new SO.Molecule.Structure(s, props);
  733. },
  734. update: ({ a, b, oldParams, newParams, cache }) => {
  735. if (!Script.areEqual(oldParams.script, newParams.script)) {
  736. return StateTransformer.UpdateResult.Recreate;
  737. }
  738. const entry = (cache as { entry: StructureQueryHelper.CacheEntry }).entry;
  739. if (entry.currentStructure === a.data) {
  740. return StateTransformer.UpdateResult.Unchanged;
  741. }
  742. const selection = StructureQueryHelper.updateStructure(entry, a.data);
  743. StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
  744. return StateTransformer.UpdateResult.Updated;
  745. },
  746. dispose({ b }) {
  747. b?.data.customPropertyDescriptors.dispose();
  748. }
  749. });
  750. type StructureSelectionFromBundle = typeof StructureSelectionFromBundle
  751. const StructureSelectionFromBundle = PluginStateTransform.BuiltIn({
  752. name: 'structure-selection-from-bundle',
  753. display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
  754. from: SO.Molecule.Structure,
  755. to: SO.Molecule.Structure,
  756. params: () => ({
  757. bundle: PD.Value<StructureElement.Bundle>(StructureElement.Bundle.Empty, { isHidden: true }),
  758. label: PD.Optional(PD.Text('', { isHidden: true }))
  759. })
  760. })({
  761. apply({ a, params, cache }) {
  762. if (params.bundle.hash !== a.data.hashCode) {
  763. return StateObject.Null;
  764. }
  765. (cache as { source: Structure }).source = a.data;
  766. const s = StructureElement.Bundle.toStructure(params.bundle, a.data);
  767. if (s.elementCount === 0) return StateObject.Null;
  768. const props = { label: `${params.label || 'Selection'}`, description: Structure.elementDescription(s) };
  769. return new SO.Molecule.Structure(s, props);
  770. },
  771. update: ({ a, b, oldParams, newParams, cache }) => {
  772. if (!StructureElement.Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
  773. return StateTransformer.UpdateResult.Recreate;
  774. }
  775. if (newParams.bundle.hash !== a.data.hashCode) {
  776. return StateTransformer.UpdateResult.Null;
  777. }
  778. if ((cache as { source: Structure }).source === a.data) {
  779. return StateTransformer.UpdateResult.Unchanged;
  780. }
  781. (cache as { source: Structure }).source = a.data;
  782. const s = StructureElement.Bundle.toStructure(newParams.bundle, a.data);
  783. if (s.elementCount === 0) return StateTransformer.UpdateResult.Null;
  784. b.label = `${newParams.label || 'Selection'}`;
  785. b.description = Structure.elementDescription(s);
  786. b.data = s;
  787. return StateTransformer.UpdateResult.Updated;
  788. },
  789. dispose({ b }) {
  790. b?.data.customPropertyDescriptors.dispose();
  791. }
  792. });
  793. export const StructureComplexElementTypes = {
  794. 'polymer': 'polymer',
  795. 'protein': 'protein',
  796. 'nucleic': 'nucleic',
  797. 'water': 'water',
  798. 'branched': 'branched', // = carbs
  799. 'ligand': 'ligand',
  800. 'non-standard': 'non-standard',
  801. 'coarse': 'coarse',
  802. // Legacy
  803. 'atomic-sequence': 'atomic-sequence',
  804. 'atomic-het': 'atomic-het',
  805. 'spheres': 'spheres'
  806. } as const;
  807. export type StructureComplexElementTypes = keyof typeof StructureComplexElementTypes
  808. const StructureComplexElementTypeTuples = PD.objectToOptions(StructureComplexElementTypes);
  809. type StructureComplexElement = typeof StructureComplexElement
  810. const StructureComplexElement = PluginStateTransform.BuiltIn({
  811. name: 'structure-complex-element',
  812. display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
  813. from: SO.Molecule.Structure,
  814. to: SO.Molecule.Structure,
  815. params: { type: PD.Select<StructureComplexElementTypes>('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
  816. })({
  817. apply({ a, params }) {
  818. // TODO: update function.
  819. let query: StructureQuery, label: string;
  820. switch (params.type) {
  821. case 'polymer': query = StructureSelectionQueries.polymer.query; label = 'Polymer'; break;
  822. case 'protein': query = StructureSelectionQueries.protein.query; label = 'Protein'; break;
  823. case 'nucleic': query = StructureSelectionQueries.nucleic.query; label = 'Nucleic'; break;
  824. case 'water': query = Queries.internal.water(); label = 'Water'; break;
  825. case 'branched': query = StructureSelectionQueries.branchedPlusConnected.query; label = 'Branched'; break;
  826. case 'ligand': query = StructureSelectionQueries.ligandPlusConnected.query; label = 'Ligand'; break;
  827. case 'non-standard': query = StructureSelectionQueries.nonStandardPolymer.query; label = 'Non-standard'; break;
  828. case 'coarse': query = StructureSelectionQueries.coarse.query; label = 'Coarse'; break;
  829. case 'atomic-sequence': query = Queries.internal.atomicSequence(); label = 'Sequence'; break;
  830. case 'atomic-het': query = Queries.internal.atomicHet(); label = 'HET Groups/Ligands'; break;
  831. case 'spheres': query = Queries.internal.spheres(); label = 'Coarse Spheres'; break;
  832. default: assertUnreachable(params.type);
  833. }
  834. const result = query(new QueryContext(a.data));
  835. const s = Sel.unionStructure(result);
  836. if (s.elementCount === 0) return StateObject.Null;
  837. return new SO.Molecule.Structure(s, { label, description: Structure.elementDescription(s) });
  838. },
  839. dispose({ b }) {
  840. b?.data.customPropertyDescriptors.dispose();
  841. }
  842. });
  843. type StructureComponent = typeof StructureComponent
  844. const StructureComponent = PluginStateTransform.BuiltIn({
  845. name: 'structure-component',
  846. display: { name: 'Component', description: 'A molecular structure component.' },
  847. from: SO.Molecule.Structure,
  848. to: SO.Molecule.Structure,
  849. params: StructureComponentParams
  850. })({
  851. apply({ a, params, cache }) {
  852. return createStructureComponent(a.data, params, cache as any);
  853. },
  854. update: ({ a, b, oldParams, newParams, cache }) => {
  855. return updateStructureComponent(a.data, b, oldParams, newParams, cache as any);
  856. },
  857. dispose({ b }) {
  858. b?.data.customPropertyDescriptors.dispose();
  859. }
  860. });
  861. type CustomModelProperties = typeof CustomModelProperties
  862. const CustomModelProperties = PluginStateTransform.BuiltIn({
  863. name: 'custom-model-properties',
  864. display: { name: 'Custom Model Properties' },
  865. isDecorator: true,
  866. from: SO.Molecule.Model,
  867. to: SO.Molecule.Model,
  868. params: (a, ctx: PluginContext) => {
  869. return ctx.customModelProperties.getParams(a?.data);
  870. }
  871. })({
  872. apply({ a, params }, ctx: PluginContext) {
  873. return Task.create('Custom Props', async taskCtx => {
  874. await attachModelProps(a.data, ctx, taskCtx, params);
  875. return new SO.Molecule.Model(a.data, { label: a.label, description: a.description });
  876. });
  877. },
  878. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  879. return Task.create('Custom Props', async taskCtx => {
  880. b.data = a.data;
  881. b.label = a.label;
  882. b.description = a.description;
  883. for (const name of oldParams.autoAttach) {
  884. const property = ctx.customModelProperties.get(name);
  885. if (!property) continue;
  886. a.data.customProperties.reference(property.descriptor, false);
  887. }
  888. await attachModelProps(a.data, ctx, taskCtx, newParams);
  889. return StateTransformer.UpdateResult.Updated;
  890. });
  891. },
  892. dispose({ b }) {
  893. b?.data.customProperties.dispose();
  894. }
  895. });
  896. async function attachModelProps(model: Model, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomModelProperties['createDefaultParams']>) {
  897. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  898. const { autoAttach, properties } = params;
  899. for (const name of Object.keys(properties)) {
  900. const property = ctx.customModelProperties.get(name)!;
  901. const props = properties[name];
  902. if (autoAttach.includes(name) || property.isHidden) {
  903. try {
  904. await property.attach(propertyCtx, model, props, true);
  905. } catch (e) {
  906. ctx.log.warn(`Error attaching model prop '${name}': ${e}`);
  907. }
  908. } else {
  909. property.set(model, props);
  910. }
  911. }
  912. }
  913. type CustomStructureProperties = typeof CustomStructureProperties
  914. const CustomStructureProperties = PluginStateTransform.BuiltIn({
  915. name: 'custom-structure-properties',
  916. display: { name: 'Custom Structure Properties' },
  917. isDecorator: true,
  918. from: SO.Molecule.Structure,
  919. to: SO.Molecule.Structure,
  920. params: (a, ctx: PluginContext) => {
  921. return ctx.customStructureProperties.getParams(a?.data.root);
  922. }
  923. })({
  924. apply({ a, params }, ctx: PluginContext) {
  925. return Task.create('Custom Props', async taskCtx => {
  926. await attachStructureProps(a.data.root, ctx, taskCtx, params);
  927. return new SO.Molecule.Structure(a.data, { label: a.label, description: a.description });
  928. });
  929. },
  930. update({ a, b, oldParams, newParams }, ctx: PluginContext) {
  931. if (a.data !== b.data) return StateTransformer.UpdateResult.Recreate;
  932. return Task.create('Custom Props', async taskCtx => {
  933. b.data = a.data;
  934. b.label = a.label;
  935. b.description = a.description;
  936. for (const name of oldParams.autoAttach) {
  937. const property = ctx.customStructureProperties.get(name);
  938. if (!property) continue;
  939. a.data.customPropertyDescriptors.reference(property.descriptor, false);
  940. }
  941. await attachStructureProps(a.data.root, ctx, taskCtx, newParams);
  942. return StateTransformer.UpdateResult.Updated;
  943. });
  944. },
  945. dispose({ b }) {
  946. b?.data.customPropertyDescriptors.dispose();
  947. }
  948. });
  949. async function attachStructureProps(structure: Structure, ctx: PluginContext, taskCtx: RuntimeContext, params: ReturnType<CustomStructureProperties['createDefaultParams']>) {
  950. const propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
  951. const { autoAttach, properties } = params;
  952. for (const name of Object.keys(properties)) {
  953. const property = ctx.customStructureProperties.get(name)!;
  954. const props = properties[name];
  955. if (autoAttach.includes(name) || property.isHidden) {
  956. try {
  957. await property.attach(propertyCtx, structure, props, true);
  958. } catch (e) {
  959. ctx.log.warn(`Error attaching structure prop '${name}': ${e}`);
  960. }
  961. } else {
  962. property.set(structure, props);
  963. }
  964. }
  965. }
  966. type ShapeFromPly = typeof ShapeFromPly
  967. const ShapeFromPly = PluginStateTransform.BuiltIn({
  968. name: 'shape-from-ply',
  969. display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
  970. from: SO.Format.Ply,
  971. to: SO.Shape.Provider,
  972. params(a) {
  973. return { };
  974. }
  975. })({
  976. apply({ a, params }) {
  977. return Task.create('Create shape from PLY', async ctx => {
  978. const shape = await shapeFromPly(a.data, params).runInContext(ctx);
  979. const props = { label: 'Shape' };
  980. return new SO.Shape.Provider(shape, props);
  981. });
  982. }
  983. });