File size: 7,909 Bytes
71174bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<template>
  <PluginComponent v-model="open" :infoPayload="infoPayload" actionBtnTxt="Save" @onPopupDone="onPopupDone"
    @onUserArgChanged="onUserArgChanged" @onMolCountsChanged="onMolCountsChanged"></PluginComponent>
</template>

<script lang="ts">
import { Options } from "vue-class-component";
import * as api from "@/Api";
import {
  IContributorCredit,
  ISoftwareCredit,
} from "@/Plugins/PluginInterfaces";
import { PluginParentClass } from "@/Plugins/Parents/PluginParentClass/PluginParentClass";
import PluginComponent from "@/Plugins/Parents/PluginComponent/PluginComponent.vue";
import {
  UserArg,
  IUserArgText,
  IUserArgCheckbox,
} from "@/UI/Forms/FormFull/FormFullInterfaces";
import { ITest } from "@/Testing/TestInterfaces";
import {
  fileNameFilter,
  matchesFilename,
} from "@/FileSystem/FilenameManipulation";
import { FileInfo } from "@/FileSystem/FileInfo";
import { TestCmdList } from "@/Testing/TestCmdList";
import { dynamicImports } from "@/Core/DynamicImports";
import { Tag } from "@/Plugins/Core/ActivityFocus/ActivityFocusUtils";
import { getMoleculesFromStore } from "@/Store/StoreExternalAccess";
import { slugify } from "@/Core/Utils/StringUtils";
import { saveTxtFiles } from "@/FileSystem/LoadSaveMolModels/SaveMolModels/SaveMolModelsUtils";
import { runWorker } from "@/Core/WebWorkers/RunWorker";
import { checkAnyMolLoaded } from "@/Plugins/CheckUseAllowedUtils";

/**
 * SaveVRMLPlugin
 */
@Options({
  components: {
    PluginComponent,
  },
})
export default class SaveVRMLPlugin extends PluginParentClass {
  menuPath = "File/Graphics/3D Model...";
  title = "Save a VRML2 Model";
  softwareCredits: ISoftwareCredit[] = [dynamicImports.mol3d.credit];
  contributorCredits: IContributorCredit[] = [
    // {
    //   name: "Jacob D. Durrant",
    //   url: "http://durrantlab.com/",
    // },
  ];
  pluginId = "savevrml";

  intro = `Save the current molecular scene as a VRML2 file (3D model).`;
  details = "This plugin exports the scene geometry for use in 3D modeling software.";
  tags = [Tag.Visualization];

  userArgDefaults: UserArg[] = [
    {
      id: "filename",
      label: "",
      val: "",
      placeHolder: "Filename (e.g., my_model.wrl)...",
      description: `The name of the VRML2 file to save. The extension ".wrl" will be automatically appended.`,
      filterFunc: (filename: string): string => {
        return fileNameFilter(filename);
      },
      validateFunc: (filename: string): boolean => {
        return matchesFilename(filename);
      },
    } as IUserArgText,
    {
      id: "simplifyMesh",
      label: "Simplify the mesh",
      description: `Reduce vertex count to shrink size, with some impact on mesh quality.`,
      val: true,
    } as IUserArgCheckbox,
  ];

  /**
   * Check if this plugin can currently be used.
   *
   * @returns {string | null}  If it returns a string, show that as an error
   *     message. If null, proceed to run the plugin.
   */
  checkPluginAllowed(): string | null {
    return checkAnyMolLoaded();
  }

  /**
   * Runs when the user presses the action button and the popup closes.
   */
  onPopupDone() {
    this.submitJobs([{ filename: this.getUserArg("filename") }]);
  }

  /**
   * Simplify the mesh.
   *
   * @param {string[][]} vrmlData  The VRML data to simplify.
   * @param {any}        mols      The molecules to simplify.
   * @returns {Promise<string[][]>}  The simplified VRML data.
   */
  private async _simplifyMesh(vrmlData: [string, string][], mols: any) {
    const simplifiedVrmlPromises = [];

    const newVrmlData: [string, string][] = [];

    for (const payload of vrmlData) {
      const [id, vrml] = payload;

      const mol = mols.filters.onlyId(id);
      if (!mol) {
        continue;
      }

      if (this.getUserArg("simplifyMesh") === true) {
        const worker = new Worker(
          new URL(
            "../../../Meshes/SimplifyVRML/SimplifyVRML.worker.ts",
            import.meta.url
          )
        );

        let reductionFraction = 0.5;
        let mergeCutoff = 0.15;
        const stylesJSONStr = JSON.stringify(mol.styles);
        if (stylesJSONStr.includes('"stick"')) {
          // This is a good one. Still some duplicate vertices, but not too bad.
          reductionFraction = 0.001;
          mergeCutoff = 0.15;
        } else if (stylesJSONStr.includes('"sphere"')) {
          // This one good
          reductionFraction = 1;
          mergeCutoff = 0.15;
        } else if (stylesJSONStr.includes('"surface"')) {
          // This one is good
          reductionFraction = 1;

          // You could put this to 0.75 or 1, but with small artifacts. Mesh with
          // this if you need even fewer verts.
          mergeCutoff = 0.5;
        } else if (stylesJSONStr.includes('"cartoon"')) {
          // This one is good
          reductionFraction = 0.4;
          mergeCutoff = 0.15;
        }

        simplifiedVrmlPromises.push(
          runWorker(worker, {
            vrmlContent: vrml,
            mergeCutoff,
            reductionFraction,
            id,
          })
        );
      }

      const resps = await Promise.all(simplifiedVrmlPromises);
      resps.forEach((resp) => {
        newVrmlData.push([resp.id, resp.optimizedVRML]);
        // vrmlData[resp.id] = resp.optimizedVRML;
      });
    }
    return newVrmlData;
  }

  /**
   * Every plugin runs some job. This is the function that does the job running.
   *
   * @param {any} parameters  Information about the VRML file to save.
   */
  async runJobInBrowser(parameters: any): Promise<any> {
    let filename = parameters.filename;
    const viewer = await api.visualization.viewer;

    // TODO: This is set to simplify (true).
    const vrmlData = await viewer.exportVRMLPerModel(true);
    debugger
    viewer.renderAll();

    const mols = getMoleculesFromStore();

    let newVrmlData: [string, string][] = [];
    if (this.getUserArg("simplifyMesh") === true) {
      // Simplify meshes
      newVrmlData = await this._simplifyMesh(vrmlData, mols);
    } else {
      newVrmlData = vrmlData;
    }


    const files: FileInfo[] = [];
    for (const payload of newVrmlData) {
      const [id, vrml] = payload;

      const mol = mols.filters.onlyId(id);
      if (!mol) {
        continue;
      }
      const innerFilename = slugify(mol.descriptions.pathName("_", 0));
      if (vrml !== "") {
        const fileInfo = new FileInfo({
          name: innerFilename + ".wrl",
          contents: vrml,
        });

        files.push(fileInfo);
      }
    }
    if (files.length === 1) {
      // If there's only one file, its name should be the one provided by the user.
      if (!filename.toLowerCase().endsWith(".wrl")) {
        filename += ".wrl";
      }
      files[0].name = filename;
    }
    // saveTxtFiles handles single vs multiple files and zip extension for multiple.
    return saveTxtFiles(files, filename);
  }

  /**
   * Gets the test commands for the plugin. For advanced use.
   *
   * @gooddefault
   * @document
   * @returns {ITest}  The selenium test commands.
   */
  async getTests(): Promise<ITest[]> {
    return [
      {
        beforePluginOpens: () => new TestCmdList().loadExampleMolecule(),
        pluginOpen: () => new TestCmdList().setUserArg(
          "filename",
          "test",
          this.pluginId
        ),
        afterPluginCloses: () => new TestCmdList().waitUntilRegex(
          "#log",
          "Job savevrml.*? ended"
        ),
      },
      {
        beforePluginOpens: () => new TestCmdList().loadExampleMolecule(),
        pluginOpen: () => new TestCmdList().setUserArg(
          "filename",
          "test.with.dots",
          this.pluginId
        ),
        afterPluginCloses: () => new TestCmdList().waitUntilRegex(
          "#log",
          "Job savevrml.*? ended"
        ),
      },
    ];
  }
}
</script>

<style scoped lang="scss"></style>