MaterialXWeb 0.0.2
Utilities for using MaterialX Packages with Web clients
Loading...
Searching...
No Matches
AmbientCGLoader Class Reference

Public Member Functions

 constructor ()
 Class to load materials from the AmbientCG site.
 
 loadMaterialsFromCache ()
 
 setDebugging (debug=true)
 
 getMaterialNames (key='assetId')
 
 writeMaterialList (materialList, filename)
 
 buildDownloadAttribute (imageFormat='PNG', imageResolution='1')
 
 splitDownloadAttribute (downloadAttribute)
 
 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 12 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 352 of file JsAmbientCGLoader.js.

352 {
357
358 const comment = doc.addChildOfCategory('comment');
359 comment.setDocString(commentString);
360 }

◆ 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 83 of file JsAmbientCGLoader.js.

83 {
89
90 return `${imageResolution}K-${imageFormat}`;
91 }

◆ clearDownloadMaterial()

AmbientCGLoader::clearDownloadMaterial ( )

Clear any cached current material asset.

Definition at line 114 of file JsAmbientCGLoader.js.

114 {
117
118 if (this.downloadMaterial) {
119 this.downloadMaterial = null;
120 }
121 this.downloadMaterialFileName = '';
122 }

◆ constructor()

AmbientCGLoader::constructor ( )

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 19 of file JsAmbientCGLoader.js.

19 {
20 if (AmbientCGLoader.instance) {
21 return AmbientCGLoader.instance;
22 }
23
24 this.logger = console;
25 this.database = {};
26 this.assets = {};
27 this.materials = null;
28 this.materialNames = [];
29 this.csvMaterials = null;
30 this.downloadMaterial = null;
31 this.downloadMaterialFileName = '';
32
33 // Cache the instance
34 AmbientCGLoader.instance = this;
35 }

◆ downloadAssetDatabase()

async AmbientCGLoader::downloadAssetDatabase ( )

Download the asset database for materials from the ambientCG site.

Returns
{Object} The downloaded database.

Definition at line 286 of file JsAmbientCGLoader.js.

286 {
290
291 this.database = {};
292 this.assets = null;
293
294 const url = 'https://ambientcg.com/api/v2/full_json';
295 const headers = { Accept: 'application/json' };
296 const params = {
297 method: 'PBRPhotogrammetry',
298 type: 'Material',
299 sort: 'Alphabet',
300 };
301
302 try {
303 const response = await axios.get(url, { headers, params });
304 if (response.status === 200) {
305 this.database = response.data;
306 this.assets = this.database.foundAssets;
307 } else {
308 this.logger.error(`Status: ${response.status}, ${response.data}`);
309 }
310 } catch (error) {
311 this.logger.error(`Error downloading asset database: ${error}`);
312 }
313
314 return this.database;
315 }

◆ 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 140 of file JsAmbientCGLoader.js.

140 {
149
151
152 const items = this.findMaterial(assetId);
153 const target = this.buildDownloadAttribute(imageFormat, imageResolution);
154 let url = '';
155 let downloadAttribute = '';
156
157 items.forEach(item => {
158 downloadAttribute = item[downloadAttributeKey];
159 if (downloadAttribute === target) {
160 url = item[downloadLinkKey];
161 this.logger.info(`Found Asset: ${assetId}. Download Attribute: ${downloadAttribute} -> ${url}`);
162 }
163 });
164
165 if (!url) {
166 this.logger.error(`No download link found for asset: ${assetId}, attribute: ${target}`);
167 return '';
168 }
169
170 this.downloadMaterialFileName = url.split('file=')[1];
171 console.log('>>>> URL:', url, 'Filename:', this.downloadMaterialFileName);
172
173 try {
174 const response = await fetch(url);
175 if (!response.ok) {
176 throw new Error(`HTTP error! Status: ${response.status}`);
177 }
178
179 // Get the response as an ArrayBuffer
180 const arrayBuffer = await response.arrayBuffer();
181
182 // Convert ArrayBuffer to Buffer
183 this.downloadMaterial = Buffer.from(arrayBuffer);
184 this.logger.info(`Material file downloaded: ${this.downloadMaterialFileName}`);
185
186 } catch (error) {
187 this.downloadMaterialFileName = '';
188 this.logger.error(`Error occurred while downloading the file: ${error}`);
189 }
190
191 return this.downloadMaterialFileName;
192 }
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 218 of file JsAmbientCGLoader.js.

218 {
222
223 const MATERIALS_CACHE_FILE = 'ambientcg_materials.json';
224 // 1. Try to load from cache file
225 if (fs.existsSync(MATERIALS_CACHE_FILE)) {
226 try {
227 const data = fs.readFileSync(MATERIALS_CACHE_FILE, 'utf8');
228 this.materials = JSON.parse(data);
229 this.logger.info(`Loaded AmbientCG materials from cache: ${MATERIALS_CACHE_FILE}`);
230 return this.materials;
231 } catch (e) {
232 this.logger.warn(`Failed to load AmbientCG materials cache: ${e.message}`);
233 }
234 }
235
236 // 2. If not in cache, fetch from network
237 const headers = { Accept: 'application/csv' };
238 const url = new URL('https://ambientCG.com/api/v2/downloads_csv');
239 url.searchParams.append('method', 'PBRPhotogrammetry');
240 url.searchParams.append('type', 'Material');
241 url.searchParams.append('sort', 'Alphabet');
242
243 this.logger.info('Downloading materials CSV list from network...');
244 try {
245 const response = await fetch(url, { headers });
246 if (response.status === 200) {
247 const csvContent = await response.text();
248 this.csvMaterials = csvContent;
249 this.materials = parse(csvContent, { columns: true });
250 this.logger.info('Downloaded CSV material list as JSON.');
251 // Save to cache file after fetching
252 try {
253 fs.writeFileSync(MATERIALS_CACHE_FILE, JSON.stringify(this.materials, null, 2));
254 this.logger.info(`Saved AmbientCG materials to cache: ${MATERIALS_CACHE_FILE}`);
255 } catch (e) {
256 this.logger.warn(`Failed to write AmbientCG materials cache: ${e.message}`);
257 }
258 } else {
259 this.materials = null;
260 this.logger.warning(`Failed to fetch the CSV material content. HTTP status code: ${response.status}`);
261 }
262 } catch (error) {
263 this.materials = null;
264 this.logger.error(`Error downloading materials list: ${error}`);
265 }
266
267 return this.materials;
268 }

◆ 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 194 of file JsAmbientCGLoader.js.

194 {
200
201 if (this.materials) {
202 return this.materials.filter(item => item[key] === assetId);
203 }
204 return [];
205 }

◆ getDataBase()

AmbientCGLoader::getDataBase ( )

Get asset database.

Returns
{Object} Asset database.

Definition at line 270 of file JsAmbientCGLoader.js.

270 {
274
275 return this.database;
276 }

◆ getDataBaseMaterialList()

AmbientCGLoader::getDataBaseMaterialList ( )

Get asset database material list.

Returns
{Array} Material list.

Definition at line 278 of file JsAmbientCGLoader.js.

278 {
282
283 return this.assets;
284 }

◆ getDownloadedMaterialInformation()

AmbientCGLoader::getDownloadedMaterialInformation ( )

Get the current downloaded material information.

Returns
{Object} The downloaded material information.

Definition at line 103 of file JsAmbientCGLoader.js.

103 {
107
108 return {
109 filename: this.downloadMaterialFileName,
110 content: this.downloadMaterial
111 };
112 }

◆ 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 58 of file JsAmbientCGLoader.js.

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

◆ 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 362 of file JsAmbientCGLoader.js.

362 {
367
368 if (!this.mx) {
369 this.logger.error('MaterialX module is required');
370 return;
371 }
372
373 const writeOptions = this.mx.XmlWriteOptions();
374 writeOptions.writeXIncludeEnable = false;
375 writeOptions.elementPredicate = this.skipLibraryElement;
376 return this.mx.writeToXmlString(doc, writeOptions);
377 }

◆ loadMaterialsFromCache()

AmbientCGLoader::loadMaterialsFromCache ( )

Definition at line 37 of file JsAmbientCGLoader.js.

37 {
38 const MATERIALS_CACHE_FILE = 'ambientcg_materials.json';
39 if (fs.existsSync(MATERIALS_CACHE_FILE)) {
40 try {
41 const data = fs.readFileSync(MATERIALS_CACHE_FILE, 'utf8');
42 this.materials = JSON.parse(data);
43 this.logger.info(`Loaded AmbientCG materials from cache: ${MATERIALS_CACHE_FILE}`);
44 } catch (e) {
45 this.logger.warn(`Failed to load AmbientCG materials cache: ${e.message}`);
46 }
47 }
48 }

◆ 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 207 of file JsAmbientCGLoader.js.

207 {
212
213 this.materials = JSON.parse(fs.readFileSync(fileName, 'utf8'));
214 this.logger.info(`Loaded materials list from: ${fileName}`);
215 return this.materials;
216 }

◆ 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 50 of file JsAmbientCGLoader.js.

50 {
54
55 this.logger.level = debug ? 'debug' : 'info';
56 }

◆ splitDownloadAttribute()

AmbientCGLoader::splitDownloadAttribute ( downloadAttribute)

Split the download attribute into image format and resolution.

Parameters
{string}downloadAttribute - The download attribute string.
Returns
{Array} A tuple of (imageFormat, imageResolution).
Note
The download attribute is in the format: '1K-PNG'.

Definition at line 93 of file JsAmbientCGLoader.js.

93 {
99
100 const parts = downloadAttribute.split('-');
101 }

◆ 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 332 of file JsAmbientCGLoader.js.

332 {
337
338 if (!this.mx) {
339 this.logger.error('MaterialX module is required');
340 return [false, ''];
341 }
342
343 if (!doc) {
344 this.logger.warning('MaterialX document is required');
345 return [false, ''];
346 }
347
348 const valid = doc.validate();
349 return [valid, valid ? '' : 'Validation failed'];
350 }

◆ 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 317 of file JsAmbientCGLoader.js.

317 {
322
323 if (!this.database) {
324 this.logger.warning('No database to write');
325 return false;
326 }
327
328 fs.writeFileSync(filename, JSON.stringify(this.database, null, 4));
329 return true;
330 }

◆ 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 124 of file JsAmbientCGLoader.js.

124 {
128
129 const haveDownload = this.downloadMaterialFileName && this.downloadMaterial;
130 if (!haveDownload) {
131 this.logger.warning('No current material downloaded');
132 return;
133 }
134
135 const filename = `${path}/${this.downloadMaterialFileName}`;
136 fs.writeFileSync(filename, this.downloadMaterial);
137 this.logger.info(`Saved downloaded material to: ${filename}`);
138 }

◆ 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 73 of file JsAmbientCGLoader.js.

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

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