MaterialXMaterials 0.0.1
Utilities for retrieving materials from remote servers
Loading...
Searching...
No Matches
AmbientCGLoader Class Reference

Public Member Functions

 constructor (mxModule, mxStdlib=null)
 Class to load materials from the AmbientCG site.
 
 setDebugging (debug=true)
 
 getMaterialNames (key='assetId')
 
 writeMaterialList (materialList, filename)
 
 buildDownloadAttribute (imageFormat='PNG', imageResolution='1')
 
 getDownloadedMaterialInformation ()
 
 clearDownloadMaterial ()
 
 writeDownloadedMaterialToFile (path='')
 
async downloadMaterialAsset (assetId, imageFormat='PNG', imageResolution='1', downloadAttributeKey='downloadAttribute', downloadLinkKey='downloadLink')
 
 findMaterial (assetId, key='assetId')
 
 loadMaterialsList (fileName)
 
async downloadMaterialsList ()
 
 getDataBase ()
 
 getDataBaseMaterialList ()
 
async downloadAssetDatabase ()
 
 writeDatabaseToFile (filename)
 
 validateMaterialXDocument (doc)
 
 addComment (doc, commentString)
 
 getMaterialXString (doc)
 

Detailed Description

Definition at line 7 of file JsAmbientCGLoader.js.

Member Function Documentation

◆ addComment()

AmbientCGLoader::addComment ( doc,
commentString )

Add a comment to the MaterialX document.

Parameters
{Object}doc - The MaterialX document to add the comment to.
{string}commentString - The comment string to add.

Definition at line 311 of file JsAmbientCGLoader.js.

311 {
316
317 const comment = doc.addChildOfCategory('comment');
318 comment.setDocString(commentString);
319 }

◆ buildDownloadAttribute()

AmbientCGLoader::buildDownloadAttribute ( imageFormat = 'PNG',
imageResolution = '1' )

Build the download attribute string for a given image format and resolution.

Parameters
{string}imageFormat - The image format to download.
{string}imageResolution - The image resolution to download.
Returns
{string} The download attribute string.

Definition at line 81 of file JsAmbientCGLoader.js.

81 {
87
88 return `${imageResolution}K-${imageFormat}`;
89 }

◆ clearDownloadMaterial()

AmbientCGLoader::clearDownloadMaterial ( )

Clear any cached current material asset.

Definition at line 102 of file JsAmbientCGLoader.js.

102 {
105
106 if (this.downloadMaterial) {
107 this.downloadMaterial = null;
108 }
109 this.downloadMaterialFileName = '';
110 }

◆ constructor()

AmbientCGLoader::constructor ( mxModule,
mxStdlib = null )

Class to load materials from the AmbientCG site.

The class can convert the materials to MaterialX format for given target shading models.

Parameters
{Object}mxModule - The MaterialX module. Required.
{Object}mxStdlib - The MaterialX standard library. Optional.

Definition at line 14 of file JsAmbientCGLoader.js.

14 {
15 this.logger = console;
16 this.database = {};
17 this.assets = {};
18 this.materials = null;
19 this.materialNames = [];
20 this.csvMaterials = null;
21 this.downloadMaterial = null;
22 this.downloadMaterialFileName = '';
23 this.mx = mxModule;
24 this.stdlib = mxStdlib;
25 this.supportOpenPBR = false;
26
27 if (!mxModule) {
28 this.logger.error('MaterialX module not specified.');
29 return;
30 }
31
32 // Check for OpenPBR support (placeholder logic)
33 const version = this.mx.getVersionIntegers();
34 this.logger.info(`Using MaterialX version: ${version.join('.')}`);
35 if (version[0] >= 1 && version[1] >= 39) || version[0] > 1) {
36 this.logger.debug('OpenPBR shading model supported');
37 this.supportOpenPBR = true;
38 }
39
40 // Load the MaterialX standard library if not provided
41 if (!this.stdlib) {
42 this.stdlib = this.mx.createDocument();
43 const libFiles = this.mx.loadLibraries(this.mx.getDefaultDataLibraryFolders(), this.mx.getDefaultDataSearchPath(), this.stdlib);
44 this.logger.debug(`Loaded standard library: ${libFiles}`);
45 }
46 }

◆ downloadAssetDatabase()

async AmbientCGLoader::downloadAssetDatabase ( )

Download the asset database for materials from the ambientCG site.

Returns
{Object} The downloaded database.

Definition at line 245 of file JsAmbientCGLoader.js.

245 {
249
250 this.database = {};
251 this.assets = null;
252
253 const url = 'https://ambientcg.com/api/v2/full_json';
254 const headers = { Accept: 'application/json' };
255 const params = {
256 method: 'PBRPhotogrammetry',
257 type: 'Material',
258 sort: 'Alphabet',
259 };
260
261 try {
262 const response = await axios.get(url, { headers, params });
263 if (response.status === 200) {
264 this.database = response.data;
265 this.assets = this.database.foundAssets;
266 } else {
267 this.logger.error(`Status: ${response.status}, ${response.data}`);
268 }
269 } catch (error) {
270 this.logger.error(`Error downloading asset database: ${error}`);
271 }
272
273 return this.database;
274 }

◆ downloadMaterialAsset()

async AmbientCGLoader::downloadMaterialAsset ( assetId,
imageFormat = 'PNG',
imageResolution = '1',
downloadAttributeKey = 'downloadAttribute',
downloadLinkKey = 'downloadLink' )

Download a material with a given id and format + resolution for images.

Parameters
{string}assetId - The string id of the material.
{string}imageFormat - The image format to download. Default is PNG.
{string}imageResolution - The image resolution to download. Default is 1.
{string}downloadAttributeKey - The download attribute key. Default is 'downloadAttribute'.
{string}downloadLinkKey - The download link key. Default is 'downloadLink'.
Returns
{string} File name of downloaded content.

Definition at line 128 of file JsAmbientCGLoader.js.

128 {
137
139
140 const items = this.findMaterial(assetId);
141 const target = this.buildDownloadAttribute(imageFormat, imageResolution);
142 let url = '';
143 let downloadAttribute = '';
144
145 items.forEach(item => {
146 downloadAttribute = item[downloadAttributeKey];
147 if (downloadAttribute === target) {
148 url = item[downloadLinkKey];
149 this.logger.info(`Found Asset: ${assetId}. Download Attribute: ${downloadAttribute} -> ${url}`);
150 }
151 });
152
153 if (!url) {
154 this.logger.error(`No download link found for asset: ${assetId}, attribute: ${target}`);
155 return '';
156 }
157
158 this.downloadMaterialFileName = url.split('file=')[1];
159
160 try {
161 const response = await axios.get(url, { responseType: 'arraybuffer' });
162 this.downloadMaterial = Buffer.from(response.data, 'binary');
163 this.logger.info(`Material file downloaded: ${this.downloadMaterialFileName}`);
164 } catch (error) {
165 this.downloadMaterialFileName = '';
166 this.logger.error(`Error occurred while downloading the file: ${error}`);
167 }
168
169 return this.downloadMaterialFileName;
170 }
buildDownloadAttribute(imageFormat='PNG', imageResolution='1')
findMaterial(assetId, key='assetId')

◆ downloadMaterialsList()

async AmbientCGLoader::downloadMaterialsList ( )

Download the list of materials from the ambientCG site.

Returns
{Array} Materials list.

Definition at line 196 of file JsAmbientCGLoader.js.

196 {
200
201 const url = 'https://ambientCG.com/api/v2/downloads_csv';
202 const headers = { Accept: 'application/csv' };
203 const params = {
204 method: 'PBRPhotogrammetry',
205 type: 'Material',
206 sort: 'Alphabet',
207 };
208
209 this.logger.info('Downloading materials CSV list...');
210 try {
211 const response = await axios.get(url, { headers, params });
212 if (response.status === 200) {
213 const csvContent = response.data;
214 this.csvMaterials = csvContent;
215 //this.materials = parse(csvContent, { columns: true });
216 this.logger.info('Downloaded CSV material list as JSON.');
217 } else {
218 this.materials = null;
219 this.logger.warning(`Failed to fetch the CSV material content. HTTP status code: ${response.status}`);
220 }
221 } catch (error) {
222 this.materials = null;
223 this.logger.error(`Error downloading materials list: ${error}`);
224 }
225
226 return this.materials;
227 }

◆ findMaterial()

AmbientCGLoader::findMaterial ( assetId,
key = 'assetId' )

Get the list of materials matching a material identifier.

Parameters
{string}assetId - Material string identifier.
{string}key - The key to lookup asset identifiers. Default is 'assetId'.
Returns
{Array} List of materials, or empty array if not found.

Definition at line 172 of file JsAmbientCGLoader.js.

172 {
178
179 if (this.materials) {
180 return this.materials.filter(item => item[key] === assetId);
181 }
182 return [];
183 }

◆ getDataBase()

AmbientCGLoader::getDataBase ( )

Get asset database.

Returns
{Object} Asset database.

Definition at line 229 of file JsAmbientCGLoader.js.

229 {
233
234 return this.database;
235 }

◆ getDataBaseMaterialList()

AmbientCGLoader::getDataBaseMaterialList ( )

Get asset database material list.

Returns
{Array} Material list.

Definition at line 237 of file JsAmbientCGLoader.js.

237 {
241
242 return this.assets;
243 }

◆ getDownloadedMaterialInformation()

AmbientCGLoader::getDownloadedMaterialInformation ( )

Get the current downloaded material information.

Returns
{Object} The downloaded material information.

Definition at line 91 of file JsAmbientCGLoader.js.

91 {
95
96 return {
97 filename: this.downloadMaterialFileName,
98 content: this.downloadMaterial
99 };
100 }

◆ getMaterialNames()

AmbientCGLoader::getMaterialNames ( key = 'assetId')

Get the list of material names.

Parameters
{string}key - The key to use for the material name. Default is 'assetId'.
Returns
{Array} The list of material names.

Definition at line 56 of file JsAmbientCGLoader.js.

56 {
61
62 this.materialNames = [];
63 const uniqueNames = new Set();
64 if (this.materials) {
65 this.materials.forEach(item => uniqueNames.add(item[key]));
66 }
67 this.materialNames = Array.from(uniqueNames).sort();
68 return this.materialNames;
69 }

◆ getMaterialXString()

AmbientCGLoader::getMaterialXString ( doc)

Convert the MaterialX document to a string.

Parameters
{Object}doc - The MaterialX document to convert.
Returns
{string} The MaterialX document as a string.

Definition at line 321 of file JsAmbientCGLoader.js.

321 {
326
327 if (!this.mx) {
328 this.logger.error('MaterialX module is required');
329 return;
330 }
331
332 const writeOptions = this.mx.XmlWriteOptions();
333 writeOptions.writeXIncludeEnable = false;
334 writeOptions.elementPredicate = this.skipLibraryElement;
335 return this.mx.writeToXmlString(doc, writeOptions);
336 }

◆ loadMaterialsList()

AmbientCGLoader::loadMaterialsList ( fileName)

Load in the list of downloadable materials from file.

Parameters
{string}fileName - Name of JSON containing list.
Returns
{Array} Materials list.

Definition at line 185 of file JsAmbientCGLoader.js.

185 {
190
191 this.materials = JSON.parse(fs.readFileSync(fileName, 'utf8'));
192 this.logger.info(`Loaded materials list from: ${fileName}`);
193 return this.materials;
194 }

◆ setDebugging()

AmbientCGLoader::setDebugging ( debug = true)

Set the debugging level for the logger.

Parameters
{boolean}debug - True to set the logger to debug level, otherwise False.

Definition at line 48 of file JsAmbientCGLoader.js.

48 {
52
53 this.logger.level = debug ? 'debug' : 'info';
54 }

◆ validateMaterialXDocument()

AmbientCGLoader::validateMaterialXDocument ( doc)

Validate the MaterialX document.

Parameters
{Object}doc - The MaterialX document to validate.
Returns
{Array} A tuple of (valid, errors) where valid is True if the document is valid, and errors is a list of errors if the document is invalid.

Definition at line 291 of file JsAmbientCGLoader.js.

291 {
296
297 if (!this.mx) {
298 this.logger.error('MaterialX module is required');
299 return [false, ''];
300 }
301
302 if (!doc) {
303 this.logger.warning('MaterialX document is required');
304 return [false, ''];
305 }
306
307 const valid = doc.validate();
308 return [valid, valid ? '' : 'Validation failed'];
309 }

◆ writeDatabaseToFile()

AmbientCGLoader::writeDatabaseToFile ( filename)

Write the database file.

Parameters
{string}filename - The filename to write the JSON file to.
Returns
{boolean} True if the file was written successfully, otherwise False.

Definition at line 276 of file JsAmbientCGLoader.js.

276 {
281
282 if (!this.database) {
283 this.logger.warning('No database to write');
284 return false;
285 }
286
287 fs.writeFileSync(filename, JSON.stringify(this.database, null, 4));
288 return true;
289 }

◆ writeDownloadedMaterialToFile()

AmbientCGLoader::writeDownloadedMaterialToFile ( path = '')

Write the currently downloaded file to file.

Parameters
{string}path - The output path for the material. Default is empty.

Definition at line 112 of file JsAmbientCGLoader.js.

112 {
116
117 const haveDownload = this.downloadMaterialFileName && this.downloadMaterial;
118 if (!haveDownload) {
119 this.logger.warning('No current material downloaded');
120 return;
121 }
122
123 const filename = `${path}/${this.downloadMaterialFileName}`;
124 fs.writeFileSync(filename, this.downloadMaterial);
125 this.logger.info(`Saved downloaded material to: ${filename}`);
126 }

◆ writeMaterialList()

AmbientCGLoader::writeMaterialList ( materialList,
filename )

Write the material list in JSON format to a file.

Parameters
{Array}materialList - The list of materials to write.
{string}filename - The file path to write the list to.

Definition at line 71 of file JsAmbientCGLoader.js.

71 {
76
77 this.logger.info(`Writing material list to file: ${filename}`);
78 fs.writeFileSync(filename, JSON.stringify(materialList, null, 4));
79 }

The documentation for this class was generated from the following file: