/** Combine the shared network artwork with independently addressable planet textures. */ import fs from 'node:fs'; import path from 'node:path'; import {createHash} from 'node:crypto'; import {fileURLToPath} from 'node:url'; import {profiles,textureEntries,zip} from './build-planet-texture-packs.mjs'; const texturePrefix='assets/minecraft/textures/'; const planetNamespaces={ guild:'dr_guild',arrakis:'dr_arrakis',caladan:'dr_caladan',giedi_prime:'dr_giedi', kaitain:'dr_kaitain',sigma_draconis_iv:'dr_sigma', giedi_prime_nether:'dr_giedi',sigma_draconis_iv_the_end:'dr_sigma' }; const blocksAtlas='assets/minecraft/atlases/blocks.json'; const generatedLicenceText=new Set(['CREDITS-Sand.txt','LICENSE-Sand-Luanti.txt']); const cubeItems=fs.readFileSync(new URL('../JarvisConnector/src/main/resources/planet-cube-items.txt',import.meta.url),'utf8') .split(/\r?\n/).map(line=>line.trim()).filter(Boolean); if(new Set(cubeItems).size!==cubeItems.length||cubeItems.some(item=>!/^[a-z0-9_]+$/.test(item)))throw Error('Invalid planet cube item catalogue'); const json=value=>Buffer.from(JSON.stringify(value)); const hash=(algorithm,bytes)=>createHash(algorithm).update(bytes).digest('hex'); function addEntry(entries,name,bytes){ if(entries.has(name)&&!entries.get(name).equals(bytes))throw Error('Conflicting pack entry: '+name); entries.set(name,bytes); } export function mergePackAssets(base,sources){ const merged=new Map(base),conflicts=[]; for(const source of sources){ for(const [name,bytes] of source){ if(!/^assets\/[a-z0-9_.-]+\/[a-z0-9_./-]+$/.test(name)||name.split('/').some(part=>!part||part==='.'||part==='..')) throw Error('Invalid resource asset path: '+name); if(!merged.has(name)){ merged.set(name,bytes); continue; } const mapping=/^assets\/[^/]+\/(?:lang\/[^/]+\.json|sounds\.json)$/.test(name); const list=/^assets\/[^/]+\/font\/.+\.json$/.test(name)?'providers': /^assets\/[^/]+\/atlases\/[^/]+\.json$/.test(name)?'sources':null; if(!mapping&&!list){ conflicts.push(name); continue; } const before=JSON.parse(merged.get(name)),after=JSON.parse(bytes); if(!before||typeof before!=='object'||Array.isArray(before)||!after||typeof after!=='object'||Array.isArray(after)) throw Error('Expected a JSON object in '+name); if(mapping){ const duplicates=Object.keys(after).filter(key=>Object.hasOwn(before,key)); conflicts.push(...duplicates.map(key=>name+'#'+key)); const additions=Object.fromEntries(Object.entries(after).filter(([key])=>!Object.hasOwn(before,key))); merged.set(name,json({...before,...additions})); }else{ if(!Array.isArray(before[list])||!Array.isArray(after[list]))throw Error('Invalid '+list+' in '+name); const additionalKeys=Object.keys(after).filter(key=>key!==list); if(additionalKeys.length)throw Error('Unexpected fields in '+name+': '+additionalKeys.join(', ')); merged.set(name,json({...before,[list]:[...before[list],...after[list]]})); } } } if(conflicts.length)throw Error('Conflicting pack assets:\n'+[...new Set(conflicts)].sort().join('\n')); return merged; } function deduplicateImperialAtlas(entries){ const legacy='dunerealms:gui/imperial_menu_atlas_v2'; const canonical='dunerealms:gui/imperial-menu-atlas-v2'; const legacyFile='assets/dunerealms/textures/gui/imperial_menu_atlas_v2.png'; const canonicalFile='assets/dunerealms/textures/gui/imperial-menu-atlas-v2.png'; const oldBytes=entries.get(legacyFile),newBytes=entries.get(canonicalFile); if(!oldBytes||!newBytes||!oldBytes.equals(newBytes)||entries.has(legacyFile+'.mcmeta')||entries.has(canonicalFile+'.mcmeta'))return; for(const [name,data] of entries){ if(name.endsWith('.json')&&data.includes(Buffer.from(legacy+'.png')))return; } const aliases=new Map(); for(const path of [blocksAtlas,'assets/minecraft/atlases/items.json']){ if(!entries.has(path))return; const atlas=JSON.parse(entries.get(path)); const index=atlas.sources?.findIndex(source=> (source.type==='single'||source.type==='minecraft:single')&&source.resource===legacy&&(source.sprite??source.resource)===legacy); if(index==null||index<0)return; atlas.sources[index]={...atlas.sources[index],resource:canonical,sprite:legacy}; aliases.set(path,json(atlas)); } for(const [name,bytes] of aliases)entries.set(name,bytes); entries.delete(legacyFile); } export function centralPackEntries(base,planetEntries=textureEntries,assetSources=[]){ const merged=mergePackAssets(base,assetSources); if(!merged.has('pack.mcmeta'))throw Error('The base must be an extracted network resource pack'); const packInfo=JSON.parse(merged.get('pack.mcmeta')); if(!packInfo.pack)throw Error('The network pack metadata is invalid'); deduplicateImperialAtlas(merged); const atlas=merged.has(blocksAtlas)?JSON.parse(merged.get(blocksAtlas)):{sources:[]}; if(!Array.isArray(atlas.sources))throw Error('The network blocks atlas is invalid'); const sprites=new Map(atlas.sources.filter(source=>source.type==='single'||source.type==='minecraft:single') .map(source=>[source.sprite??source.resource,source.resource])); for(const planet of Object.keys(profiles)){ const namespace=planetNamespaces[planet]; if(!namespace)throw Error('Missing asset namespace for '+planet); const dimension=planet.endsWith('_nether')?'nether/':planet.endsWith('_the_end')?'the_end/':''; const textureDirectory='assets/'+namespace+'/textures/'+dimension; for(const [name,bytes] of planetEntries(planet)){ if(name==='pack.mcmeta')continue; const target=name.startsWith(texturePrefix) ?textureDirectory+name.slice(texturePrefix.length) :'licenses/planet-materials/'+name; // The standalone planet archives retain their existing published checksums. const content=generatedLicenceText.has(name)?Buffer.from(bytes.toString('utf8').replaceAll('\r\n','\n')):bytes; addEntry(merged,target,content); } for(const material of cubeItems){ const id=planet+'/'+material; const palette='block/'+material; const texture=merged.has(textureDirectory+palette+'.png')?namespace+':'+dimension+palette:'minecraft:block/'+material; if(texture.startsWith(namespace+':')){ if(sprites.has(texture)&&sprites.get(texture)!==texture)throw Error('Conflicting block atlas sprite: '+texture); if(!sprites.has(texture)){ atlas.sources.push({type:'single',resource:texture,sprite:texture}); sprites.set(texture,texture); } } const model=namespace+':item/'+dimension+material; const definition=json({model:{type:'minecraft:model',model}}); addEntry(merged,'assets/'+namespace+'/items/'+dimension+material+'.json',definition); addEntry(merged,'assets/'+namespace+'/models/item/'+dimension+material+'.json',json({ parent:'minecraft:block/cube_all',textures:{all:texture} })); // Previously issued item stacks retain their stored item_model component. addEntry(merged,'assets/dunerealms/items/planets/'+id+'.json',json({ model:{type:'minecraft:model',model:'dunerealms:item/planets/'+id} })); addEntry(merged,'assets/dunerealms/models/item/planets/'+id+'.json',json({parent:model})); } } merged.set(blocksAtlas,json(atlas)); return merged; } function readDirectory(root,dir=root,entries=new Map()){ for(const entry of fs.readdirSync(dir,{withFileTypes:true})){ const absolute=path.join(dir,entry.name); if(entry.isDirectory())readDirectory(root,absolute,entries); else if(entry.isFile())entries.set(path.relative(root,absolute).split(path.sep).join('/'),fs.readFileSync(absolute)); else throw Error('Unsupported pack entry: '+entry.name); } return entries; } export function buildCentralPack(baseDir,output,version,assetDirectories=[]){ if(!/^[1-9][0-9]*$/.test(version))throw Error('A positive integer release version is required'); const entries=centralPackEntries(readDirectory(baseDir),textureEntries,assetDirectories.map(dir=>readDirectory(dir))); if(entries.size>65535)throw Error('The central pack exceeds the ZIP entry limit'); const metadata=JSON.parse(entries.get('pack.mcmeta')); metadata.pack.description='DuneRealms Central Resource Pack v'+version; entries.set('pack.mcmeta',json(metadata)); const sizes=[]; const bytes=zip(entries,(name,compressedBytes)=>sizes.push({name,compressedBytes})); const filename='DuneRealms-Central-v'+version+'.zip'; const largestEntries=sizes.sort((a,b)=>b.compressedBytes-a.compressedBytes).slice(0,10); if(bytes.length>=250*1024*1024)throw Error('The central pack exceeds the Java client download limit'); const manifest={ filename,url:'https://www.dunerealms.com/downloads/'+filename, sha1:hash('sha1',bytes),sha256:hash('sha256',bytes), bytes:bytes.length,largestEntries,profiles:Object.fromEntries(Object.entries(profiles).map(([id,profile])=>[id,profile.aliases])) }; fs.mkdirSync(output,{recursive:true}); fs.writeFileSync(path.join(output,filename),bytes); fs.writeFileSync(path.join(output,'central-pack-manifest.json'),JSON.stringify(manifest,null,2)+'\n'); return manifest; } if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){ const [base,output,version,...assetDirectories]=process.argv.slice(2); if(!base||!output||!version)throw Error('Usage: node build-central-resource-pack.mjs [namespaced-asset-source ...]'); console.log(JSON.stringify(buildCentralPack(base,output,version,assetDirectories),null,2)); }