file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
js/meshopt_encoder.js
JavaScript
// This file is part of meshoptimizer library and is distributed under the terms of MIT License. // Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) var MeshoptEncoder = (function () { // Built with clang version 19.1.5-wasi-sdk // Built from meshoptimizer 1.0 var wasm = 'b9H79Tebbbe9ok9Geueu9Geub9Gbb9Gruuuuuuueu9Gvuuuuueu9Gduueu9Gluuuueu9Gvuuuuub9Gouuuuuub9Gluuuub9GiuuueuiE8AdilveoveovrrwrrrDDoDrbqqbelve9Weiiviebeoweuec;G:Qdkr:PlCo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bb8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9mW4W2be8A9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWVbd8F9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949c919M9MWV9c9V919U9KbiE9TW79O9V9Wt9FW9U9J9V9KW9wWVtW949wWV79P9V9UblY9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWVbv8E9TW79O9V9Wt9FW9U9J9V9KW69U9KW949c919M9MWV9c9V919U9Kbo8A9TW79O9V9Wt9FW9U9J9V9KW69U9KW949wWV79P9V9UbrE9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JWbwa9TW79O9V9Wt9FW9U9J9V9KW69U9KW949tWG91W9U9JW9c9V919U9KbDL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9p9JtbqK9TW79O9V9Wt9FW9U9J9V9KWS9P2tWV9r919HtbkL9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVT949WbxY9TW79O9V9Wt9FW9U9J9V9KWS9P2tWVJ9V29VVbmE9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OWbza9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94J9H9J9OW9ttV9P9WbHa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9WbOK9TW79O9V9Wt9F79W9Ht9P9H29t9VVt9sW9T9H9WbAl79IV9RbXDwebcekdKYq:p28Adbk:Bhdhud9:8Jjjjjbc;qw9Rgr8KjjjjbcbhwdnaeTmbabcbyd;m:kjjbaoaocb9iEgDc:GeV86bbarc;adfcbcjdz:xjjjb8AdnaiTmbarc;adfadalz:wjjjb8Akarc;abfalfcbcbcjdal9RalcFe0Ez:xjjjb8Aarc;abfarc;adfalz:wjjjb8AarcUf9cb83ibarc8Wf9cb83ibarcyf9cb83ibarcaf9cb83ibarcKf9cb83ibarczf9cb83ibar9cb83iwar9cb83ibcj;abal9Uc;WFbGcjdalca0Ehqdnaicd6mbavcd9imbaDTmbadcefhkaqci2gxal2hmarc;alfclfhParc;qlfceVhsarc;qofclVhzarc;qofcKfhHarc;qofczfhOcbhAincdhCcbhodnavci6mbaH9cb83ibaO9cb83ibar9cb83i;yoar9cb83i;qoadaAfgoybbhXcbhQincbhwcbhLdninaoalfhKaoybbgYaX7aLVhLawcP0meaKhoaYhXawcefgwaQfai6mbkkcbhXarc;qofhwincwh8AcwhEdnaLaX93gocFeGg3cs0mbclhEa3ci0mba3cb9hcethEkdnaocw4cFeGg3cs0mbclh8Aa3ci0mba3cb9hceth8Aka8AaEfh3awydbh5cwh8AcwhEdnaocz4cFeGg8Ecs0mbclhEa8Eci0mba8Ecb9hcethEka3a5fh3dnaocFFFFb0mbclh8AaocFFF8F0mbaocFFFr0ceth8Akawa3aEfa8AfBdbawclfhwaXcefgXcw9hmbkaKhoaYhXaQczfgQai6mbkcbhocehwazhLinawaoaLydbarc;qofaocdtfydb6EhoaLclfhLawcefgwcw9hmbkcihCkcbh3arc;qlfcbcjdz:xjjjb8Aarc;alfcwfcbBdbar9cb83i;alaoclth8Fadhaaqhhakh5inarc;qlfadcba3cufgoaoa30Eal2falz:wjjjb8Aaiahaiah6Ehgdnaqaia39Ra3aqfai6EgYcsfc9WGgoaY9nmbarc;qofaYfcbaoaY9Rz:xjjjb8Akada3al2fh8Jcbh8Kina8Ka8FVcl4hQarc;alfa8Kcdtfh8LaAh8Mcbh8Nina8NaAfhwdndndndndndna8KPldebidkasa8Mc98GgLfhoa5aLfh8Aarc;qlfawc98GgLfRbbhXcwhwinaoRbbawtaXVhXaocefhoawcwfgwca9hmbkaYTmla8Ncith8Ea8JaLfhEcbhKinaERbbhLcwhoa8AhwinawRbbaotaLVhLawcefhwaocwfgoca9hmbkarc;qofaKfaLaX7aQ93a8E486bba8Aalfh8AaEalfhEaLhXaKcefgKaY9hmbxlkkaYTmia8Mc9:Ghoa8NcitcwGhEarc;qlfawceVfRbbcwtarc;qlfawc9:GfRbbVhLarc;qofhwaghXinawa5aofRbbcwtaaaofRbbVg8AaL9RgLcetaLcztcz91cs47cFFiGaE486bbaoalfhoawcefhwa8AhLa3aXcufgX9hmbxikkaYTmda8Jawfhoarc;qlfawfRbbhLarc;qofhwaghXinawaoRbbg8AaL9RgLcetaLcKtcK91cr4786bbawcefhwaoalfhoa8AhLa3aXcufgX9hmbxdkkaYTmeka8LydbhEcbhKarc;qofhoincdhLcbhwinaLaoawfRbbcb9hfhLawcefgwcz9hmbkclhXcbhwinaXaoawfRbbcd0fhXawcefgwcz9hmbkcwh8Acbhwina8AaoawfRbbcP0fh8Aawcefgwcz9hmbkaLaXaLaX6Egwa8Aawa8A6Egwczawcz6EaEfhEaoczfhoaKczfgKaY6mbka8LaEBdbka8Mcefh8Ma8Ncefg8Ncl9hmbka8Kcefg8KaC9hmbkaaamfhaahaxfhha5amfh5a3axfg3ai6mbkcbhocehwaPhLinawaoaLydbarc;alfaocdtfydb6EhoaLclfhLawcefgXhwaCaX9hmbkaraAcd4fa8FcdVaoaocdSE86bbaAclfgAal6mbkkabaefh8Kabcefhoalcd4gecbaDEhkadcefhOarc;abfceVhHcbhmdndninaiam9nmearc;qofcbcjdz:xjjjb8Aa8Kao9Rak6mdadamal2gwfhxcbh8JaOawfhzaocbakz:xjjjbghakfh5aqaiam9Ramaqfai6Egscsfgocl4cifcd4hCaoc9WGg8LThPindndndndndndndndndndnaDTmbara8Jcd4fRbbgLciGPlbedlbkasTmdaxa8Jfhoarc;abfa8JfRbbhLarc;qofhwashXinawaoRbbg8AaL9RgLcetaLcKtcK91cr4786bbawcefhwaoalfhoa8AhLaXcufgXmbxikkasTmia8JcitcwGhEarc;abfa8JceVfRbbcwtarc;abfa8Jc9:GgofRbbVhLaxaofhoarc;qofhwashXinawao8Vbbg8AaL9RgLcetaLcztcz91cs47cFFiGaE486bbawcefhwaoalfhoa8AhLaXcufgXmbxdkkaHa8Jc98GgEfhoazaEfh8Aarc;abfaEfRbbhXcwhwinaoRbbawtaXVhXaocefhoawcwfgwca9hmbkasTmbaLcl4hYa8JcitcKGh3axaEfhEcbhKinaERbbhLcwhoa8AhwinawRbbaotaLVhLawcefhwaocwfgoca9hmbkarc;qofaKfaLaX7aY93a3486bba8Aalfh8AaEalfhEaLhXaKcefgKas9hmbkkaDmbcbhoxlka8LTmbcbhodninarc;qofaofgwcwf8Pibaw8Pib:e9qTmeaoczfgoa8L9pmdxbkkdnavmbcehoxikcbhEaChKaChYinarc;qofaEfgocwf8Pibhyao8Pibh8PcdhLcbhwinaLaoawfRbbcb9hfhLawcefgwcz9hmbkclhXcbhwinaXaoawfRbbcd0fhXawcefgwcz9hmbkcwh8Acbhwina8AaoawfRbbcP0fh8Aawcefgwcz9hmbkaLaXaLaX6Egoa8Aaoa8A6Egoczaocz6EaYfhYaocucbaya8P:e9cb9sEgwaoaw6EaKfhKaEczfgEa8L9pmdxbkkaha8Jcd4fgoaoRbbcda8JcetcoGtV86bbxikdnaKas6mbaYas6mbaha8Jcd4fgoaoRbbcia8JcetcoGtV86bba8Ka59Ras6mra5arc;qofasz:wjjjbasfh5xikaKaY9phokaha8Jcd4fgwawRbbaoa8JcetcoGtV86bbka8Ka59RaC6mla5cbaCz:xjjjbgAaCfhYdndna8LmbaPhoxekdna8KaY9RcK9pmbaPhoxekaocdtc:q1jjbfcj1jjbaDEg5ydxggcetc;:FFFeGh8Fcuh3cuagtcu7cFeGhacbh8Marc;qofhLinarc;qofa8MfhQczhEdndndnagPDbeeeeeeedekcucbaQcwf8PibaQ8Pib:e9cb9sEhExekcbhoa8FhEinaEaaaLaofRbb9nfhEaocefgocz9hmbkkcih8Ecbh8Ainczhwdndndna5a8AcdtfydbgKPDbeeeeeeedekcucbaQcwf8PibaQ8Pib:e9cb9sEhwxekaKcetc;:FFFeGhwcuaKtcu7cFeGhXcbhoinawaXaLaofRbb9nfhwaocefgocz9hmbkkdndnawaE6mbaKa39hmeawaE9hmea5a8EcdtfydbcwSmeka8Ah8EawhEka8Acefg8Aci9hmbkaAa8Mco4fgoaoRbba8Ea8Mci4coGtV86bbdndndna5a8Ecdtfydbg3PDdbbbbbbbebkdncwa39Tg8ETmbcua3tcu7hwdndna3ceSmbcbh8NaLhQinaQhoa8Eh8AcbhXinaoRbbgEawcFeGgKaEaK6EaXa3tVhXaocefhoa8Acufg8AmbkaYaX86bbaQa8EfhQaYcefhYa8Na8Efg8Ncz6mbxdkkcbh8NaLhQinaQhoa8Eh8AcbhXinaoRbbgEawcFeGgKaEaK6EaXcetVhXaocefhoa8Acufg8AmbkaYaX:T9cFe:d9c:c:qj:bw9:9c:q;c1:I1e:d9c:b:c:e1z9:9ca188bbaQa8EfhQaYcefhYa8Na8Efg8Ncz6mbkkcbhoinaYaLaofRbbgX86bbaYaXawcFeG9pfhYaocefgocz9hmbxikkdna3ceSmbinaYcb86bbaYcefhYxbkkinaYcb86bbaYcefhYxbkkaYaQ8Pbb83bbaYcwfaQcwf8Pbb83bbaYczfhYka8Mczfg8Ma8L9pgomeaLczfhLa8KaY9RcK9pmbkkaoTmlaYh5aYTmlka8Jcefg8Jal9hmbkarc;abfaxascufal2falz:wjjjb8Aasamfhma5hoa5mbkcbhwxdkdna8Kao9RakalfgwcKcaaDEgLawaL0EgX9pmbcbhwxdkdnawaL9pmbaocbaXaw9Rgwz:xjjjbawfhokaoarc;adfalz:wjjjbalfhodnaDTmbaoaraez:wjjjbaefhokaoab9Rhwxekcbhwkarc;qwf8Kjjjjbawk5babaeadaialcdcbyd;m:kjjbz:bjjjbk9reduaecd4gdaefgicaaica0Eabcj;abae9Uc;WFbGcjdaeca0Egifcufai9Uae2aiadfaicl4cifcd4f2fcefkmbcbabBd;m:kjjbk:Ese5u8Jjjjjbc;ae9Rgl8Kjjjjbcbhvdnaici9UgocHfae0mbabcbyd;q:kjjbgrc;GeV86bbalc;abfcFecjez:xjjjb8AalcUfgw9cu83ibalc8WfgD9cu83ibalcyfgq9cu83ibalcafgk9cu83ibalcKfgx9cu83ibalczfgm9cu83ibal9cu83iwal9cu83ibabaefc9WfhPabcefgsaofhednaiTmbcmcsarcb9kgzEhHcbhOcbhAcbhCcbhXcbhQindnaeaP9nmbcbhvxikaQcufhvadaCcdtfgLydbhKaLcwfydbhYaLclfydbh8AcbhEdndndninalc;abfavcsGcitfgoydlh3dndndnaoydbgoaK9hmba3a8ASmekdnaoa8A9hmba3aY9hmbaEcefhExekaoaY9hmea3aK9hmeaEcdfhEkaEc870mdaXcufhvaLaEciGcx2goc;i1jjbfydbcdtfydbh3aLaoc;e1jjbfydbcdtfydbh8AaLaoc;a1jjbfydbcdtfydbhKcbhodnindnalavcsGcdtfydba39hmbaohYxdkcuhYavcufhvaocefgocz9hmbkkaOa3aOSgvaYce9iaYaH9oVgoGfhOdndndncbcsavEaYaoEgvcs9hmbarce9imba3a3aAa3cefaASgvEgAcefSmecmcsavEhvkasavaEcdtc;WeGV86bbavcs9hmea3aA9Rgvcetavc8F917hvinaeavcFb0crtavcFbGV86bbaecefheavcje6hoavcr4hvaoTmbka3hAxvkcPhvasaEcdtcPV86bba3hAkavTmiavaH9omicdhocehEaQhYxlkavcufhvaEclfgEc;ab9hmbkkdnaLceaYaOSceta8AaOSEcx2gvc;a1jjbfydbcdtfydbgKTaLavc;e1jjbfydbcdtfydbg8AceSGaLavc;i1jjbfydbcdtfydbg3cdSGaOcb9hGazGg5ce9hmbaw9cu83ibaD9cu83ibaq9cu83ibak9cu83ibax9cu83ibam9cu83ibal9cu83iwal9cu83ibcbhOkcbhEaXcufgvhodnindnalaocsGcdtfydba8A9hmbaEhYxdkcuhYaocufhoaEcefgEcz9hmbkkcbhodnindnalavcsGcdtfydba39hmbaohExdkcuhEavcufhvaocefgocz9hmbkkaOaKaOSg8EfhLdndnaYcm0mbaYcefhYxekcbcsa8AaLSgvEhYaLavfhLkdndnaEcm0mbaEcefhExekcbcsa3aLSgvEhEaLavfhLkc9:cua8EEh8FcbhvaEaYcltVgacFeGhodndndninavc:W1jjbfRbbaoSmeavcefgvcz9hmbxdkka5aKaO9havcm0VVmbasavc;WeV86bbxekasa8F86bbaeaa86bbaecefhekdna8EmbaKaA9Rgvcetavc8F917hvinaeavcFb0gocrtavcFbGV86bbavcr4hvaecefheaombkaKhAkdnaYcs9hmba8AaA9Rgvcetavc8F917hvinaeavcFb0gocrtavcFbGV86bbavcr4hvaecefheaombka8AhAkdnaEcs9hmba3aA9Rgvcetavc8F917hvinaeavcFb0gocrtavcFbGV86bbavcr4hvaecefheaombka3hAkalaXcdtfaKBdbaXcefcsGhvdndnaYPzbeeeeeeeeeeeeeebekalavcdtfa8ABdbaXcdfcsGhvkdndnaEPzbeeeeeeeeeeeeeebekalavcdtfa3BdbavcefcsGhvkcihoalc;abfaQcitfgEaKBdlaEa8ABdbaQcefcsGhYcdhEavhXaLhOxekcdhoalaXcdtfa3BdbcehEaXcefcsGhXaQhYkalc;abfaYcitfgva8ABdlava3Bdbalc;abfaQaEfcsGcitfgva3BdlavaKBdbascefhsaQaofcsGhQaCcifgCai6mbkkdnaeaP9nmbcbhvxekcbhvinaeavfavc:W1jjbfRbb86bbavcefgvcz9hmbkaeab9Ravfhvkalc;aef8KjjjjbavkZeeucbhddninadcefgdc8F0meceadtae6mbkkadcrfcFeGcr9Uci2cdfabci9U2cHfkmbcbabBd;q:kjjbk:Adewu8Jjjjjbcz9Rhlcbhvdnaicvfae0mbcbhvabcbRb;q:kjjbc;qeV86bbal9cb83iwabcefhoabaefc98fhrdnaiTmbcbhwcbhDindnaoar6mbcbskadaDcdtfydbgqalcwfawaqav9Rgvavc8F91gv7av9Rc507gwcdtfgkydb9Rgvc8E91c9:Gavcdt7awVhvinaoavcFb0gecrtavcFbGV86bbavcr4hvaocefhoaembkakaqBdbaqhvaDcefgDai9hmbkkdnaoar9nmbcbskaocbBbbaoab9RclfhvkavkBeeucbhddninadcefgdc8F0meceadtae6mbkkadcwfcFeGcr9Uab2cvfk:bvli99dui99ludnaeTmbcuadcetcuftcu7:Zhvdndncuaicuftcu7:ZgoJbbbZMgr:lJbbb9p9DTmbar:Ohwxekcjjjj94hwkcbhicbhDinalclfIdbgrJbbbbJbbjZalIdbgq:lar:lMalcwfIdbgk:lMgr:varJbbbb9BEgrNhxaqarNhrdndnakJbbbb9GTmbaxhqxekJbbjZar:l:tgqaq:maxJbbbb9GEhqJbbjZax:l:tgxax:marJbbbb9GEhrkdndnalcxfIdbgxJbbj:;axJbbj:;9GEgkJbbjZakJbbjZ9FEavNJbbbZJbbb:;axJbbbb9GEMgx:lJbbb9p9DTmbax:Ohmxekcjjjj94hmkdndnaqJbbj:;aqJbbj:;9GEgxJbbjZaxJbbjZ9FEaoNJbbbZJbbb:;aqJbbbb9GEMgq:lJbbb9p9DTmbaq:OhPxekcjjjj94hPkdndnarJbbj:;arJbbj:;9GEgqJbbjZaqJbbjZ9FEaoNJbbbZJbbb:;arJbbbb9GEMgr:lJbbb9p9DTmbar:Ohsxekcjjjj94hskdndnadcl9hmbabaifgzas86bbazcifam86bbazcdfaw86bbazcefaP86bbxekabaDfgzas87ebazcofam87ebazclfaw87ebazcdfaP87ebkalczfhlaiclfhiaDcwfhDaecufgembkkk;hlld99eud99eudnaeTmbdndncuaicuftcu7:ZgvJbbbZMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikaic;8FiGhrinabcofcicdalclfIdb:lalIdb:l9EgialcwfIdb:lalaicdtfIdb:l9EEgialcxfIdb:lalaicdtfIdb:l9EEgiarV87ebdndnJbbj:;JbbjZalaicdtfIdbJbbbb9DEgoalaicd7cdtfIdbJ;Zl:1ZNNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabcdfaq87ebdndnalaicefciGcdtfIdbJ;Zl:1ZNaoNgwJbbj:;awJbbj:;9GEgDJbbjZaDJbbjZ9FEavNJbbbZJbbb:;awJbbbb9GEMgw:lJbbb9p9DTmbaw:Ohqxekcjjjj94hqkabaq87ebdndnaoalaicufciGcdtfIdbJ;Zl:1ZNNgoJbbj:;aoJbbj:;9GEgwJbbjZawJbbjZ9FEavNJbbbZJbbb:;aoJbbbb9GEMgo:lJbbb9p9DTmbao:Ohixekcjjjj94hikabclfai87ebabcwfhbalczfhlaecufgembkkk;3viDue99eu8Jjjjjbcjd9Rgo8Kjjjjbadcd4hrdndndndnavcd9hmbadcl6meaohwarhDinawc:CuBdbawclfhwaDcufgDmbkaeTmiadcl6mdarcdthqalhkcbhxinaohwakhDarhminawawydbgPcbaDIdbgs:8cL4cFeGc:cufasJbbbb9BEgzaPaz9kEBdbaDclfhDawclfhwamcufgmmbkakaqfhkaxcefgxaeSmixbkkaeTmdxekaeTmekarcdthkavce9hhqadcl6hdcbhxindndndnaqmbadmdc:CuhDalhwarhminaDcbawIdbgs:8cL4cFeGc:cufasJbbbb9BEgPaDaP9kEhDawclfhwamcufgmmbxdkkc:CuhDdndnavPleddbdkadmdaohwalhmarhPinawcbamIdbgs:8cL4cFeGgzc;:bazc;:b0Ec:cufasJbbbb9BEBdbamclfhmawclfhwaPcufgPmbxdkkadmecbhwarhminaoawfcbalawfIdbgs:8cL4cFeGgPc8AaPc8A0Ec:cufasJbbbb9BEBdbawclfhwamcufgmmbkkadmbcbhwarhPinaDhmdnavceSmbaoawfydbhmkdndnalawfIdbgscjjj;8iamai9RcefgmcLt9R::NJbbbZJbbb:;asJbbbb9GEMgs:lJbbb9p9DTmbas:Ohzxekcjjjj94hzkabawfazcFFFrGamcKtVBdbawclfhwaPcufgPmbkkabakfhbalakfhlaxcefgxae9hmbkkaocjdf8Kjjjjbk:Ylvdud99due99iudnaeTmbceaicufgvthocuaitcu7:Zhrcuavtcu7:Zhwcbhvadcl9hhDcbhqindndnalcwfIdbgkJbbbbakJbbbb9GEgkJbbjZakJbbjZ9FEarNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikdndnalIdbgkJbbbbakJbbbb9GEgkJbbjZakJbbjZ9FEarNJbbbZMgk:lJbbb9p9DTmbak:Ohdxekcjjjj94hdkadai9Rcd9TgxaifhidndnalclfIdbgkJbbbbakJbbbb9GEgkJbbjZakJbbjZ9FEarNJbbbZMgk:lJbbb9p9DTmbak:Ohdxekcjjjj94hdkadai9Rcd9ThddndnalcxfIdbgkJbbbbakJbbbb9GEgkJbbjZakJbbjZ9FEawNJbbbZMgk:lJbbb9p9DTmbak:Ohmxekcjjjj94hmkadaifhiaoamVhmdndnaDmbabavfgPai86bbaPcifam86bbaPcdfad86bbaPcefax86bbxekabaqfgPai87ebaPcofam87ebaPclfad87ebaPcdfax87ebkalczfhlavclfhvaqcwfhqaecufgembkkk;YqdXui998Jjjjjbc:qd9Rgv8Kjjjjbavc:Sefcbc;Kbz:xjjjb8AcbhodnadTmbcbhoaiTmbdndnabaeSmbaehrxekavcuadcdtgwadcFFFFi0Ecbyd;u:kjjbHjjjjbbgrBd:SeavceBd:mdaraeawz:wjjjb8Akavc:GefcwfcbBdbav9cb83i:Geavc:Gefaradaiavc:Sefz:pjjjbavyd:GehDadci9Ugqcbyd;u:kjjbHjjjjbbheavc:Sefavyd:mdgkcdtfaeBdbavakcefgwBd:mdaecbaqz:xjjjbhxavc:SefawcdtfcuaicdtaicFFFFi0Ecbyd;u:kjjbHjjjjbbgmBdbavakcdfgPBd:mdalc;ebfhsaDheamhwinawalIdbasaeydbgzcwazcw6EcdtfIdbMUdbaeclfheawclfhwaicufgimbkavc:SefaPcdtfcuaqcdtadcFFFF970Ecbyd;u:kjjbHjjjjbbgPBdbdnadci6mbarheaPhwaqhiinawamaeydbcdtfIdbamaeclfydbcdtfIdbMamaecwfydbcdtfIdbMUdbaecxfheawclfhwaicufgimbkkakcifhoalc;ebfhHavc;qbfhOavheavyd:KehAavyd:OehCcbhzcbhwcbhXcehQinaehLcihkarawci2gKcdtfgeydbhsaeclfydbhdabaXcx2fgicwfaecwfydbgYBdbaiclfadBdbaiasBdbaxawfce86bbaOaYBdwaOadBdlaOasBdbaPawcdtfcbBdbdnazTmbcihkaLhiinaOakcdtfaiydbgeBdbakaeaY9haeas9haead9hGGfhkaiclfhiazcufgzmbkkaXcefhXcbhzinaCaAarazaKfcdtfydbcdtgifydbcdtfgYheaDaifgdydbgshidnasTmbdninaeydbawSmeaeclfheaicufgiTmdxbkkaeaYascdtfc98fydbBdbadadydbcufBdbkazcefgzci9hmbkdndnakTmbcuhwJbbbbh8Acbhdavyd:KehYavyd:OehKindndnaDaOadcdtfydbcdtgzfydbgembadcefhdxekadcs0hiamazfgsIdbhEasalcbadcefgdaiEcdtfIdbaHaecwaecw6EcdtfIdbMg3Udba3aE:th3aecdthiaKaYazfydbcdtfheinaPaeydbgzcdtfgsa3asIdbMgEUdbaEa8Aa8AaE9DgsEh8AazawasEhwaeclfheaic98fgimbkkadak9hmbkawcu9hmekaQaq9pmdindnaxaQfRbbmbaQhwxdkaqaQcefgQ9hmbxikkakczakcz6EhzaOheaLhOawcu9hmbkkaocdtavc:Seffc98fhedninaoTmeaeydbcbyd;y:kjjbH:bjjjbbaec98fheaocufhoxbkkavc:qdf8Kjjjjbk;IlevucuaicdtgvaicFFFFi0Egocbyd;u:kjjbHjjjjbbhralalyd9GgwcdtfarBdbalawcefBd9GabarBdbaocbyd;u:kjjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdlcuadcdtadcFFFFi0Ecbyd;u:kjjbHjjjjbbhralalyd9GgocdtfarBdbalaocefBd9GabarBdwabydbcbavz:xjjjb8Aadci9UhDdnadTmbabydbhoaehladhrinaoalydbcdtfgvavydbcefBdbalclfhlarcufgrmbkkdnaiTmbabydbhlabydlhrcbhvaihoinaravBdbarclfhralydbavfhvalclfhlaocufgombkkdnadci6mbabydlhrabydwhvcbhlinaecwfydbhoaeclfydbhdaraeydbcdtfgwawydbgwcefBdbavawcdtfalBdbaradcdtfgdadydbgdcefBdbavadcdtfalBdbaraocdtfgoaoydbgocefBdbavaocdtfalBdbaecxfheaDalcefgl9hmbkkdnaiTmbabydlheabydbhlinaeaeydbalydb9RBdbalclfhlaeclfheaicufgimbkkkQbabaeadaic;K1jjbz:ojjjbkQbabaeadaic;m:jjjbz:ojjjbk9DeeuabcFeaicdtz:xjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk:Vvioud9:du8Jjjjjbc;Wa9Rgl8Kjjjjbcbhvalcxfcbc;Kbz:xjjjb8AalcuadcitgoadcFFFFe0Ecbyd;u:kjjbHjjjjbbgrBdxalceBd2araeadaicezNjjjbalcuaoadcjjjjoGEcbyd;u:kjjbHjjjjbbgwBdzadcdthednadTmbabhiinaiavBdbaiclfhiadavcefgv9hmbkkawaefhDalabBdwalawBdl9cbhqindnadTmbaq9cq9:hkarhvaDhiadheinaiav8Pibak1:NcFrG87ebavcwfhvaicdfhiaecufgembkkalclfaq:NceGcdtfydbhxalclfaq9ce98gq:NceGcdtfydbhmalc;Wbfcbcjaz:xjjjb8AaDhvadhidnadTmbinalc;Wbfav8VebcdtfgeaeydbcefBdbavcdfhvaicufgimbkkcbhvcbhiinalc;WbfavfgeydbhoaeaiBdbaoaifhiavclfgvcja9hmbkadhvdndnadTmbinalc;WbfaDamydbgicetf8VebcdtfgeaeydbgecefBdbaxaecdtfaiBdbamclfhmavcufgvmbkaq9cv9smdcbhvinabawydbcdtfavBdbawclfhwadavcefgv9hmbxdkkaq9cv9smekkclhvdninavc98Smealcxfavfydbcbyd;y:kjjbH:bjjjbbavc98fhvxbkkalc;Waf8Kjjjjbk:Jwliuo99iud9:cbhv8Jjjjjbca9Rgoczfcwfcbyd:8:kjjbBdbaocb8Pd:0:kjjb83izaocwfcbyd;i:kjjbBdbaocb8Pd;a:kjjb83ibaicd4hrdndnadmbJFFuFhwJFFuuhDJFFuuhqJFFuFhkJFFuuhxJFFuFhmxekarcdthPaehsincbhiinaoczfaifgzasaifIdbgwazIdbgDaDaw9EEUdbaoaifgzawazIdbgDaDaw9DEUdbaiclfgicx9hmbkasaPfhsavcefgvad9hmbkaoIdKhDaoIdwhwaoIdChqaoIdlhkaoIdzhxaoIdbhmkdnadTmbJbbbbJbFu9hJbbbbamax:tgmamJbbbb9DEgmakaq:tgkakam9DEgkawaD:tgwawak9DEgw:vawJbbbb9BEhwdnalmbarcdthoindndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:S9cC:ghHdndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikaHai:S:ehHdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaHai:T9cy:g:e83ibaeaofheabcwfhbadcufgdmbxdkkarcdthoindndnaeIdbax:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cv9:9c;j:KM;j:KM;j:Kd:dhOdndnaeclfIdbaq:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cq9:9cM;j:KM;j:KM;jl:daO:ehOdndnaecwfIdbaD:tawNJbbbZMgk:lJbbb9p9DTmbak:Ohixekcjjjj94hikabaOai:SgH9ca:gaH9cz:g9cjjj;4s:d:eaH9cFe:d:e9cF:bj;4:pj;ar:d9c:bd9:9c:p;G:d;4j:E;ar:d9cH9:9c;d;H:W:y:m:g;d;Hb:d9cC9:9c:KM;j:KM;j:KMD:d:e83ibaeaofheabcwfhbadcufgdmbkkk9teiucbcbyd;C:kjjbgeabcifc98GfgbBd;C:kjjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd;C:kjjbgeabcrfc94GfgbBd;C:kjjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd;C:kjjbge9Rcifc98GaefgbBd;C:kjjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk;Uddbcjwk;mdbbbbdbbblbbbwbbbbbbbebbbdbbblbbbwbbbbbbbbbbbbbbbb4:h9w9N94:P:gW:j9O:ye9Pbbbbbbebbbdbbbebbbdbbbbbbbdbbbbbbbebbbbbbb:l29hZ;69:9kZ;N;76Z;rg97Z;z;o9xZ8J;B85Z;:;u9yZ;b;k9HZ:2;Z9DZ9e:l9mZ59A8KZ:r;T3Z:A:zYZ79OHZ;j4::8::Y:D9V8:bbbb9s:49:Z8R:hBZ9M9M;M8:L;z;o8:;8:PG89q;x:J878R:hQ8::M:B;e87bbbbbbjZbbjZbbjZ:E;V;N8::Y:DsZ9i;H;68:xd;R8:;h0838:;W:NoZbbbb:WV9O8:uf888:9i;H;68:9c9G;L89;n;m9m89;D8Ko8:bbbbf:8tZ9m836ZS:2AZL;zPZZ818EZ9e:lxZ;U98F8:819E;68:FFuuFFuuFFuuFFuFFFuFFFuFbc;mqkCebbbebbbebbbdbbb9G:vbb'; // embed! wasm var wasmpack = new Uint8Array([ 32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115, ]); if (typeof WebAssembly !== 'object') { return { supported: false, }; } var instance; var ready = WebAssembly.instantiate(unpack(wasm), {}).then(function (result) { instance = result.instance; instance.exports.__wasm_call_ctors(); instance.exports.meshopt_encodeVertexVersion(1); instance.exports.meshopt_encodeIndexVersion(1); }); function unpack(data) { var result = new Uint8Array(data.length); for (var i = 0; i < data.length; ++i) { var ch = data.charCodeAt(i); result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4; } var write = 0; for (var i = 0; i < data.length; ++i) { result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i]; } return result.buffer.slice(0, write); } function assert(cond) { if (!cond) { throw new Error('Assertion failed'); } } function bytes(view) { return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); } function reorder(fun, indices, vertices, optf) { var sbrk = instance.exports.sbrk; var ip = sbrk(indices.length * 4); var rp = sbrk(vertices * 4); var heap = new Uint8Array(instance.exports.memory.buffer); var indices8 = bytes(indices); heap.set(indices8, ip); if (optf) { optf(ip, ip, indices.length, vertices); } var unique = fun(rp, ip, indices.length, vertices); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var remap = new Uint32Array(vertices); new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4)); indices8.set(heap.subarray(ip, ip + indices.length * 4)); sbrk(ip - sbrk(0)); for (var i = 0; i < indices.length; ++i) indices[i] = remap[indices[i]]; return [remap, unique]; } function spatialsort(fun, positions, count, stride) { var sbrk = instance.exports.sbrk; var ip = sbrk(count * 4); var sp = sbrk(count * stride); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(positions), sp); fun(ip, sp, count, stride); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var remap = new Uint32Array(count); new Uint8Array(remap.buffer).set(heap.subarray(ip, ip + count * 4)); sbrk(ip - sbrk(0)); return remap; } function encode(fun, bound, source, count, size, level, version) { var sbrk = instance.exports.sbrk; var tp = sbrk(bound); var sp = sbrk(count * size); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(source), sp); var res = fun(tp, bound, sp, count, size, level, version); var target = new Uint8Array(res); target.set(heap.subarray(tp, tp + res)); sbrk(tp - sbrk(0)); return target; } function maxindex(source) { var result = 0; for (var i = 0; i < source.length; ++i) { var index = source[i]; result = result < index ? index : result; } return result; } function index32(source, size) { assert(size == 2 || size == 4); if (size == 4) { return new Uint32Array(source.buffer, source.byteOffset, source.byteLength / 4); } else { var view = new Uint16Array(source.buffer, source.byteOffset, source.byteLength / 2); return new Uint32Array(view); // copies each element } } function filter(fun, source, count, stride, bits, insize, mode) { var sbrk = instance.exports.sbrk; var tp = sbrk(count * stride); var sp = sbrk(count * insize); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(source), sp); fun(tp, count, stride, bits, sp, mode); var target = new Uint8Array(count * stride); target.set(heap.subarray(tp, tp + count * stride)); sbrk(tp - sbrk(0)); return target; } return { ready: ready, supported: true, reorderMesh: function (indices, triangles, optsize) { var optf = triangles ? optsize ? instance.exports.meshopt_optimizeVertexCacheStrip : instance.exports.meshopt_optimizeVertexCache : undefined; return reorder(instance.exports.meshopt_optimizeVertexFetchRemap, indices, maxindex(indices) + 1, optf); }, reorderPoints: function (positions, positions_stride) { assert(positions instanceof Float32Array); assert(positions.length % positions_stride == 0); assert(positions_stride >= 3); return spatialsort(instance.exports.meshopt_spatialSortRemap, positions, positions.length / positions_stride, positions_stride * 4); }, encodeVertexBuffer: function (source, count, size) { assert(size > 0 && size <= 256); assert(size % 4 == 0); var bound = instance.exports.meshopt_encodeVertexBufferBound(count, size); return encode(instance.exports.meshopt_encodeVertexBuffer, bound, source, count, size); }, encodeVertexBufferLevel: function (source, count, size, level, version) { assert(size > 0 && size <= 256); assert(size % 4 == 0); assert(level >= 0 && level <= 3); assert(version === undefined || version == 0 || version == 1); var bound = instance.exports.meshopt_encodeVertexBufferBound(count, size); return encode(instance.exports.meshopt_encodeVertexBufferLevel, bound, source, count, size, level, version === undefined ? -1 : version); }, encodeIndexBuffer: function (source, count, size) { assert(size == 2 || size == 4); assert(count % 3 == 0); var indices = index32(source, size); var bound = instance.exports.meshopt_encodeIndexBufferBound(count, maxindex(indices) + 1); return encode(instance.exports.meshopt_encodeIndexBuffer, bound, indices, count, 4); }, encodeIndexSequence: function (source, count, size) { assert(size == 2 || size == 4); var indices = index32(source, size); var bound = instance.exports.meshopt_encodeIndexSequenceBound(count, maxindex(indices) + 1); return encode(instance.exports.meshopt_encodeIndexSequence, bound, indices, count, 4); }, encodeGltfBuffer: function (source, count, size, mode, version) { var table = { ATTRIBUTES: this.encodeVertexBufferLevel, TRIANGLES: this.encodeIndexBuffer, INDICES: this.encodeIndexSequence, }; assert(table[mode]); return table[mode](source, count, size, /* level= */ 2, version === undefined ? 0 : version); }, encodeFilterOct: function (source, count, stride, bits) { assert(stride == 4 || stride == 8); assert(bits >= 2 && bits <= 16); return filter(instance.exports.meshopt_encodeFilterOct, source, count, stride, bits, 16); }, encodeFilterQuat: function (source, count, stride, bits) { assert(stride == 8); assert(bits >= 4 && bits <= 16); return filter(instance.exports.meshopt_encodeFilterQuat, source, count, stride, bits, 16); }, encodeFilterExp: function (source, count, stride, bits, mode) { assert(stride > 0 && stride % 4 == 0); assert(bits >= 1 && bits <= 24); var table = { Separate: 0, SharedVector: 1, SharedComponent: 2, Clamped: 3, }; return filter(instance.exports.meshopt_encodeFilterExp, source, count, stride, bits, stride, mode ? table[mode] : 1); }, encodeFilterColor: function (source, count, stride, bits) { assert(stride == 4 || stride == 8); assert(bits >= 2 && bits <= 16); return filter(instance.exports.meshopt_encodeFilterColor, source, count, stride, bits, 16); }, }; })(); export { MeshoptEncoder };
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
js/meshopt_encoder.test.js
JavaScript
import assert from 'assert/strict'; import { MeshoptEncoder as encoder } from './meshopt_encoder.js'; import { MeshoptDecoder as decoder } from './meshopt_decoder.mjs'; process.on('unhandledRejection', (error) => { console.log('unhandledRejection', error); process.exit(1); }); function bytes(view) { return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); } var tests = { reorderMesh: function () { var indices = new Uint32Array([4, 2, 5, 3, 1, 4, 0, 1, 3, 1, 2, 4]); var expected = new Uint32Array([0, 1, 2, 3, 1, 0, 4, 3, 0, 5, 3, 4]); var remap = new Uint32Array([5, 3, 1, 4, 0, 2]); var res = encoder.reorderMesh(indices, /* triangles= */ true, /* optsize= */ true); assert.deepEqual(indices, expected); assert.deepEqual(res[0], remap); assert.equal(res[1], 6); // unique }, reorderPoints: function () { var points = new Float32Array([1, 1, 1, 11, 11, 11, 2, 2, 2, 12, 12, 12]); var expected = new Uint32Array([0, 2, 1, 3]); var remap = encoder.reorderPoints(points, 3); assert.deepEqual(remap, expected); }, roundtripVertexBuffer: function () { var data = new Uint8Array(16 * 4); // this tests 0/2/4/8 bit groups in one stream for (var i = 0; i < 16; ++i) { data[i * 4 + 0] = 0; data[i * 4 + 1] = i * 1; data[i * 4 + 2] = i * 2; data[i * 4 + 3] = i * 8; } var encoded = encoder.encodeVertexBuffer(data, 16, 4); assert.equal(encoded[0], 0xa1); var decoded = new Uint8Array(16 * 4); decoder.decodeVertexBuffer(decoded, 16, 4, encoded); assert.deepEqual(decoded, data); }, roundtripVertexBufferV1: function () { var data = new Uint8Array(16 * 4); // this tests 0/2/4/8 bit groups in one stream for (var i = 0; i < 16; ++i) { data[i * 4 + 0] = 0; data[i * 4 + 1] = i * 1; data[i * 4 + 2] = i * 2; data[i * 4 + 3] = i * 8; } var encoded = encoder.encodeVertexBufferLevel(data, 16, 4, 3, /* version= */ 1); assert.equal(encoded[0], 0xa1); var decoded = new Uint8Array(16 * 4); decoder.decodeVertexBuffer(decoded, 16, 4, encoded); assert.deepEqual(decoded, data); }, roundtripIndexBuffer: function () { var data = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]); var encoded = encoder.encodeIndexBuffer(bytes(data), data.length, 4); var decoded = new Uint32Array(data.length); decoder.decodeIndexBuffer(bytes(decoded), data.length, 4, encoded); assert.deepEqual(decoded, data); }, roundtripIndexBuffer16: function () { var data = new Uint16Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]); var encoded = encoder.encodeIndexBuffer(bytes(data), data.length, 2); var decoded = new Uint16Array(data.length); decoder.decodeIndexBuffer(bytes(decoded), data.length, 2, encoded); assert.deepEqual(decoded, data); }, roundtripIndexSequence: function () { var data = new Uint32Array([0, 1, 51, 2, 49, 1000]); var encoded = encoder.encodeIndexSequence(bytes(data), data.length, 4); var decoded = new Uint32Array(data.length); decoder.decodeIndexSequence(bytes(decoded), data.length, 4, encoded); assert.deepEqual(decoded, data); }, roundtripIndexSequence16: function () { var data = new Uint16Array([0, 1, 51, 2, 49, 1000]); var encoded = encoder.encodeIndexSequence(bytes(data), data.length, 2); var decoded = new Uint16Array(data.length); decoder.decodeIndexSequence(bytes(decoded), data.length, 2, encoded); assert.deepEqual(decoded, data); }, encodeFilterOct8: function () { var data = new Float32Array([1, 0, 0, 0, 0, -1, 0, 0, 0.7071068, 0, 0.707168, 1, -0.7071068, 0, -0.707168, 1]); var expected = new Uint8Array([0x7f, 0, 0x7f, 0, 0, 0x81, 0x7f, 0, 0x3f, 0, 0x7f, 0x7f, 0x81, 0x40, 0x7f, 0x7f]); // 4 vectors, encode each vector into 4 bytes with 8 bits of precision/component var encoded = encoder.encodeFilterOct(data, 4, 4, 8); assert.deepEqual(encoded, expected); }, encodeFilterOct12: function () { var data = new Float32Array([1, 0, 0, 0, 0, -1, 0, 0, 0.7071068, 0, 0.707168, 1, -0.7071068, 0, -0.707168, 1]); var expected = new Uint16Array([0x7ff, 0, 0x7ff, 0, 0x0, 0xf801, 0x7ff, 0, 0x3ff, 0, 0x7ff, 0x7fff, 0xf801, 0x400, 0x7ff, 0x7fff]); // 4 vectors, encode each vector into 8 bytes with 12 bits of precision/component var encoded = encoder.encodeFilterOct(data, 4, 8, 12); assert.deepEqual(encoded, bytes(expected)); }, encodeFilterQuat12: function () { var data = new Float32Array([1, 0, 0, 0, 0, -1, 0, 0, 0.7071068, 0, 0, 0.707168, -0.7071068, 0, 0, -0.707168]); var expected = new Uint16Array([0, 0, 0, 0x7fc, 0, 0, 0, 0x7fd, 0x7ff, 0, 0, 0x7ff, 0x7ff, 0, 0, 0x7ff]); // 4 quaternions, encode each quaternion into 8 bytes with 12 bits of precision/component var encoded = encoder.encodeFilterQuat(data, 4, 8, 12); assert.deepEqual(encoded, bytes(expected)); }, encodeFilterExp: function () { var data = new Float32Array([1, -23.4, -0.1]); var expected = new Uint32Array([0xf7000200, 0xf7ffd133, 0xf7ffffcd]); // 1 vector with 3 components (12 bytes), encode each vector into 12 bytes with 15 bits of precision/component var encoded = encoder.encodeFilterExp(data, 1, 12, 15); assert.deepEqual(encoded, bytes(expected)); }, encodeFilterExpMode: function () { var data = new Float32Array([1, -23.4, -0.1, 11.0]); var expected = new Uint32Array([0xf3002000, 0xf7ffd133, 0xf3fffccd, 0xf7001600]); // 2 vectors with 2 components (8 bytes), encode each vector into 8 bytes with 15 bits of precision/component var encoded = encoder.encodeFilterExp(data, 2, 8, 15, 'SharedComponent'); assert.deepEqual(encoded, bytes(expected)); }, encodeFilterExpClamp: function () { var data = new Float32Array([1, -23.4, -0.1]); var expected = new Uint32Array([0xf3002000, 0xf7ffd133, 0xf2fff99a]); // 1 vector with 3 components (12 bytes), encode each vector into 12 bytes with 15 bits of precision/component // exponents are separate but clamped to 0 var encoded = encoder.encodeFilterExp(data, 1, 12, 15, 'Clamped'); assert.deepEqual(encoded, bytes(expected)); }, encodeFilterColor8: function () { var data = new Float32Array([1, 0, 0, 1, 0, 1, 0, 0.5, 0, 0, 1, 0.25, 0.4, 0.4, 0.4, 0.75]); var expected = new Uint8Array([0x40, 0x7f, 0xc1, 0xff, 0x7f, 0x00, 0x7f, 0xc0, 0x40, 0x81, 0xc0, 0xa0, 0x66, 0x00, 0x00, 0xdf]); // 4 vectors, encode each vector into 4 bytes with 8 bits of precision/component var encoded = encoder.encodeFilterColor(data, 4, 4, 8); assert.deepEqual(encoded, expected); }, encodeFilterColor12: function () { var data = new Float32Array([1, 0, 0, 1, 0, 1, 0, 0.5, 0, 0, 1, 0.25, 0.4, 0.4, 0.4, 0.75]); var expected = new Uint16Array([ 0x0400, 0x07ff, 0xfc01, 0x0fff, 0x07ff, 0x0000, 0x07ff, 0x0c00, 0x0400, 0xf801, 0xfc00, 0x0a00, 0x0666, 0x0000, 0x0000, 0x0dff, ]); // 4 vectors, encode each vector into 8 bytes with 12 bits of precision/component var encoded = encoder.encodeFilterColor(data, 4, 8, 12); assert.deepEqual(encoded, bytes(expected)); }, encodeGltfBuffer: function () { var data = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]); var encoded = encoder.encodeGltfBuffer(bytes(data), data.length, 4, 'TRIANGLES'); var decoded = new Uint32Array(data.length); decoder.decodeGltfBuffer(bytes(decoded), data.length, 4, encoded, 'TRIANGLES'); assert.equal(encoded[0], 0xe1); assert.deepEqual(decoded, data); }, encodeGltfBufferAttribute: function () { var data = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]); var encoded = encoder.encodeGltfBuffer(bytes(data), data.length, 4, 'ATTRIBUTES'); var decoded = new Uint32Array(data.length); decoder.decodeGltfBuffer(bytes(decoded), data.length, 4, encoded, 'ATTRIBUTES'); assert.equal(encoded[0], 0xa0); assert.deepEqual(decoded, data); }, encodeGltfBufferAttributeV1: function () { var data = new Uint32Array([0, 1, 2, 2, 1, 3, 4, 6, 5, 7, 8, 9]); var encoded = encoder.encodeGltfBuffer(bytes(data), data.length, 4, 'ATTRIBUTES', 1); var decoded = new Uint32Array(data.length); decoder.decodeGltfBuffer(bytes(decoded), data.length, 4, encoded, 'ATTRIBUTES'); assert.equal(encoded[0], 0xa1); assert.deepEqual(decoded, data); }, }; Promise.all([encoder.ready, decoder.ready]).then(() => { var count = 0; for (var key in tests) { tests[key](); count++; } console.log(count, 'tests passed'); });
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
js/meshopt_simplifier.d.ts
TypeScript
// This file is part of meshoptimizer library and is distributed under the terms of MIT License. // Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) export type Flags = 'LockBorder' | 'Sparse' | 'ErrorAbsolute' | 'Prune' | 'Regularize' | 'Permissive'; export const MeshoptSimplifier: { supported: boolean; ready: Promise<void>; compactMesh: (indices: Uint32Array) => [Uint32Array, number]; simplify: ( indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number, target_index_count: number, target_error: number, flags?: Flags[] ) => [Uint32Array, number]; simplifyWithAttributes: ( indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number, vertex_attributes: Float32Array, vertex_attributes_stride: number, attribute_weights: number[], vertex_lock: Uint8Array | null, target_index_count: number, target_error: number, flags?: Flags[] ) => [Uint32Array, number]; simplifyWithUpdate: ( indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number, vertex_attributes: Float32Array, vertex_attributes_stride: number, attribute_weights: number[], vertex_lock: Uint8Array | null, target_index_count: number, target_error: number, flags?: Flags[] ) => [number, number]; simplifySloppy: ( indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number, vertex_lock: Uint8Array | null, target_index_count: number, target_error: number ) => [Uint32Array, number]; getScale: (vertex_positions: Float32Array, vertex_positions_stride: number) => number; simplifyPoints: ( vertex_positions: Float32Array, vertex_positions_stride: number, target_vertex_count: number, vertex_colors?: Float32Array, vertex_colors_stride?: number, color_weight?: number ) => Uint32Array; simplifyPrune: (indices: Uint32Array, vertex_positions: Float32Array, vertex_positions_stride: number, target_error: number) => Uint32Array; };
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
js/meshopt_simplifier.js
JavaScript
// This file is part of meshoptimizer library and is distributed under the terms of MIT License. // Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) var MeshoptSimplifier = (function () { // Built with clang version 19.1.5-wasi-sdk // Built from meshoptimizer 1.0 var wasm = 'b9H79Tebbbe:6eO9Geueu9Geub9Gbb9Gsuuuuuuuuuuuu99uueu9Gvuuuuub9Gruuuuuuub9Gouuuuuue999Gvuuuuueu9Gzuuuuuuuuuuu99uuuub9Gquuuuuuu99uueu9GPuuuuuuuuuuu99uueu9Gquuuuuuuu99ueu9Gruuuuuu99eu9Gwuuuuuu99ueu9Giuuue999Gluuuueu9Gluuuub9GiuuueuiLQdilvorlwDiqkxmPszbHHbelve9Weiiviebeoweuec:G:Pdkr:Bdxo9TW9T9VV95dbH9F9F939H79T9F9J9H229F9Jt9VV7bbz9TW79O9V9Wt9F79P9T9W29P9M95bw8E9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9OcttV9P9I91tW7bD8A9TW79O9V9Wt9F79P9T9W29P9M959x9Pt9O9v9W9K9HtWbqQ9TW79O9V9Wt9F79P9T9W29P9M959t29V9W9W95bkX9TW79O9V9Wt9F79P9T9W29P9M959qV919UWbxQ9TW79O9V9Wt9F79P9T9W29P9M959q9V9P9Ut7bmX9TW79O9V9Wt9F79P9T9W29P9M959t9J9H2WbPa9TW79O9V9Wt9F9V9Wt9P9T9P96W9wWVtW94SWt9J9O9sW9T9H9Wbs59TW79O9V9Wt9F9NW9UWV9HtW9q9V79Pt9P9V9U9sW9T9H9Wbzl79IV9RbHDwebcekdCXqM;YeQdbk;A1er3ue99euE99Que9:r998Jjjjjbcj;sb9Rgs8Kjjjjbcbhzasc:Cefcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkdnamcdGTmbalcrfci4cbyd1:jjjbHjjjjbbhHasc:Cefasyd;8egecdtfaHBdbasaecefBd;8ecbhlcbhednadTmbabheadhOinaHaeydbci4fcb86bbaeclfheaOcufgOmbkcbhlabheadhOinaHaeydbgAci4fgCaCRbbgCceaAcrGgAtV86bbaCcu7aA4ceGalfhlaeclfheaOcufgOmbkcualcdtalcFFFFi0Ehekaecbyd1:jjjbHjjjjbbhzasc:Cefasyd;8egecdtfazBdbasaecefBd;8ealcd4alfhOcehHinaHgecethHaeaO6mbkcbhXcuaecdtgOaecFFFFi0Ecbyd1:jjjbHjjjjbbhHasc:Cefasyd;8egAcdtfaHBdbasaAcefBd;8eaHcFeaOz:tjjjbhQdnadTmbaecufhLcbhKindndnaQabaXcdtfgYydbgAc:v;t;h;Ev2aLGgOcdtfgCydbgHcuSmbceheinazaHcdtfydbaASmdaOaefhHaecefheaQaHaLGgOcdtfgCydbgHcu9hmbkkazaKcdtfaABdbaCaKBdbaKhHaKcefhKkaYaHBdbaXcefgXad9hmbkkaQcbyd:m:jjjbH:bjjjbbasasyd;8ecufBd;8ekcbh8AcualcefgecdtaecFFFFi0Ecbyd1:jjjbHjjjjbbhXasc:Cefasyd;8egecdtfaXBdbasaXBdNeasaecefBd;8ecuadcitadcFFFFe0Ecbyd1:jjjbHjjjjbbhEasc:Cefasyd;8egecdtfaEBdbasaEBd:yeasaecefBd;8eascNefabadalcbz:cjjjbcualcdtgealcFFFFi0Eg3cbyd1:jjjbHjjjjbbhAasc:Cefasyd;8egHcdtfaABdbasaHcefBd;8ea3cbyd1:jjjbHjjjjbbhKasc:Cefasyd;8egHcdtfaKBdbasaHcefBd;8eaAaKaialavazasc:Cefz:djjjbalcbyd1:jjjbHjjjjbbh5asc:Cefasyd;8egHcdtfa5BdbasaHcefBd;8ea3cbyd1:jjjbHjjjjbbhHasc:Cefasyd;8egOcdtfaHBdbasaOcefBd;8ea3cbyd1:jjjbHjjjjbbhOasc:Cefasyd;8egCcdtfaOBdbasaCcefBd;8eaHcFeaez:tjjjbh8EaOcFeaez:tjjjbh8FdnalTmbaEcwfhaindnaXa8AgOcefg8AcdtfydbgCaXaOcdtgefydbgHSmbaCaH9RhhaEaHcitfhga8Faefh8Ja8Eaefh8KcbhQindndnagaQcitfydbgLaO9hmba8KaOBdba8JaOBdbxekdnaXaLcdtg8LfgeclfydbgHaeydbgeSmbaEaecitgCfydbaOSmeaHae9Rh8Maecu7aHfhYaaaCfhHcbheinaYaeSmeaecefheaHydbhCaHcwfhHaCaO9hmbkaea8M6meka8Fa8LfgeaOaLaeydbcuSEBdba8KaLaOa8KydbcuSEBdbkaQcefgQah9hmbkka8Aal9hmbkaAhHaKhOa8FhCa8EhQcbheindndnaeaHydbgL9hmbdnaeaOydbgL9hmbaQydbhLdnaCydbgYcu9hmbaLcu9hmba5aefcb86bbxikdnaYcuSmbaLcuSmbaeaYSmbaAaYcdtfydbaAaLcdtfydb9hmba5aefcd86bbxika5aefh8KdnaeaYSmbaeaLSmba8Kce86bbxika8Kcl86bbxdkdnaeaKaLcdtgYfydb9hmbdnaCydbg8KcuSmbaea8KSmbaQydbghcuSmbaeahSmba8FaYfydbggcuSmbagaLSmba8EaYfydbgYcuSmbaYaLSmbdnaAa8KcdtfydbgLaAaYcdtfydb9hmbaLaAahcdtfydbgYSmbaYaAagcdtfydb9hmba5aefcd86bbxlka5aefcl86bbxika5aefcl86bbxdka5aefcl86bbxeka5aefa5aLfRbb86bbkaHclfhHaOclfhOaCclfhCaQclfhQalaecefge9hmbkdnamcaGTmbaEcwfh8Jcbh8Nindndna5a8NfgyRbbg8Pc9:fPibebekdndndnaAa8Ncdtfydbgea8N9hmbdnaqmbcbhgxdkdnazTmbcbhga8NheinagaqazaecdtgefydbfRbbcdGce4VhgaKaefydbgea8N9hmbxikkcbhga8NheinagaqaefRbbcdGce4VhgaKaecdtfydbgea8N9hmbxdkka5aefRbbhexeka8NheindnaXaecdtgafgeclfydbgHaeydbgeSmbaHae9Rh8AaEaecitfh8MaAaafh8Lcbh8Kina8Ma8KcitfydbgYhednindnaXaecdtgLfgeclfydbgHaeydbgeSmbdnaAaEaecitgOfydbcdtfydba8LydbgQ9hmbcehexikaHae9Rhhaecu7aHfhCa8JaOfhHcbheinaCaeSmeaecefheaHydbhOaHcwfhHaAaOcdtfydbaQ9hmbkaeah6hexdkaKaLfydbgeaY9hmbkcbhekagaece7Vhga8Kcefg8Ka8A9hmbkkaKaafydbgea8N9hmbka8PciagceGEhekayae86bbka8Ncefg8Nal9hmbkkdnaqTmbdndnazTmbazheaAhHalhOindnaqaeydbfRbbceGTmba5aHydbfcl86bbkaeclfheaHclfhHaOcufgOmbxdkkaqheaAhHalhOindnaeRbbceGTmba5aHydbfcl86bbkaecefheaHclfhHaOcufgOmbkkaAhealhOa5hHindna5aeydbfRbbcl9hmbaHcl86bbkaeclfheaHcefhHaOcufgOmbkkamceGTmba5healhHindnaeRbbce9hmbaecl86bbkaecefheaHcufgHmbkkcbhIcualcx2alc;v:Q;v:Qe0Ecbyd1:jjjbHjjjjbbhaasc:Cefasyd;8egecdtfaaBdbasaecefBd;8easc:qefcbBdbas9cb83i1eaaaialavazasc1efz:ejjjbh8RdndnaDmbcbhycbhCxekcbhCawhecbhHindnaeIdbJbbbb9ETmbasaCcdtfaHBdbaCcefhCkaeclfheaDaHcefgH9hmbkcuaCal2gecdtaecFFFFi0Ecbyd1:jjjbHjjjjbbhyasc:Cefasyd;8egecdtfayBdbasaecefBd;8ealTmbdnaCmbcbhCxekarcd4h8KdnazTmbaCcdthhcbhXayhYinaoazaXcdtfydba8K2cdtfhLasheaYhHaChOinaHaLaeydbcdtgQfIdbawaQfIdbNUdbaeclfheaHclfhHaOcufgOmbkaYahfhYaXcefgXal9hmbxdkkaCcdthhcbhXayhYinaoaXa8K2cdtfhLasheaYhHaChOinaHaLaeydbcdtgQfIdbawaQfIdbNUdbaeclfheaHclfhHaOcufgOmbkaYahfhYaXcefgXal9hmbkkcualc8S2gHalc;D;O;f8U0EgQcbyd1:jjjbHjjjjbbheasc:Cefasyd;8egOcdtfaeBdbasaOcefBd;8eaecbaHz:tjjjbh8ScbhDcbh8KdnaCTmbcbhIaQcbyd1:jjjbHjjjjbbh8Kasc:Cefasyd;8egecdtfa8KBdbasaecefBd;8ea8KcbaHz:tjjjb8AcuaCal2gecltgHaecFFFFb0Ecbyd1:jjjbHjjjjbbhDasc:Cefasyd;8egecdtfaDBdbasaecefBd;8eaDcbaHz:tjjjb8AamcjjjjdGTmbcualcltgealcFFFFb0Ecbyd1:jjjbHjjjjbbhIasc:Cefasyd;8egHcdtfaIBdbasaHcefBd;8eaIcbaez:tjjjb8AkdnadTmbcbhLabhHinaaaHclfydbgXcx2fgeIdbaaaHydbgYcx2fgOIdbgR:tg8UaaaHcwfydbghcx2fgQIdlaOIdlg8V:tg8WNaQIdbaR:tg8XaeIdla8V:tg8YN:tg8Zh80aeIdwaOIdwg81:tgBa8XNaQIdwa81:tg83a8UN:tgUh8Xa8Ya83Na8WaBN:tg8Yh8Udna8Za8ZNa8Ya8YNaUaUNMM:rgBJbbbb9EgOTmba8ZaB:vh80aUaB:vh8Xa8YaB:vh8Uka8SaAaYcdtfydbgQc8S2fgea8UaB:rg8Wa8UNNg85aeIdbMUdbaea8Xa8Wa8XNg86Ng87aeIdlMUdlaea80a8Wa80Ng83Ng88aeIdwMUdwaea86a8UNg86aeIdxMUdxaea83a8UNg89aeIdzMUdzaea83a8XNg8:aeIdCMUdCaea8Ua8Wa80a81Na8UaRNa8Va8XNMM:mgZNg83Ng8UaeIdKMUdKaea8Xa83Ng8XaeId3MUd3aea80a83Ng80aeIdaMUdaaea83aZNg83aeId8KMUd8Kaea8WaeIdyMUdya8SaAaXcdtfydbgXc8S2fgea85aeIdbMUdbaea87aeIdlMUdlaea88aeIdwMUdwaea86aeIdxMUdxaea89aeIdzMUdzaea8:aeIdCMUdCaea8UaeIdKMUdKaea8XaeId3MUd3aea80aeIdaMUdaaea83aeId8KMUd8Kaea8WaeIdyMUdya8SaAahcdtfydbgYc8S2fgea85aeIdbMUdbaea87aeIdlMUdlaea88aeIdwMUdwaea86aeIdxMUdxaea89aeIdzMUdzaea8:aeIdCMUdCaea8UaeIdKMUdKaea8XaeId3MUd3aea80aeIdaMUdaaea83aeId8KMUd8Kaea8WaeIdyMUdydnaITmbdnaOTmba8ZaB:vh8ZaUaB:vhUa8YaB:vh8YkaIaQcltfgeaBJbbbZNg8UaUNg8WaeIdlMUdlaea8Ua8ZNg8XaeIdwMUdwaea8Ua8YNg80aeIdbMUdbaea8UaR:ma8YNaUa8VN:ta81a8ZN:tNg8UaeIdxMUdxaIaXcltfgea8WaeIdlMUdlaea8XaeIdwMUdwaea80aeIdbMUdbaea8UaeIdxMUdxaIaYcltfgea8WaeIdlMUdlaea8XaeIdwMUdwaea80aeIdbMUdbaea8UaeIdxMUdxkaHcxfhHaLcifgLad6mbkkdnalTmbJ;n;m;m89J:v:;;w8ZamczGEh8YcbhOaAhQaahHa8SheindnaOaQydb9hmbaecxfgLaLIdbJbbbbMUdbaeczfgLaLIdbJbbbbMUdbaecCfgLaLIdbJbbbbMUdbaea8YaecyfgLIdbg8ZNg8UaeIdbMUdbaeclfgXa8UaXIdbMUdbaecwfgXa8UaXIdbMUdbaecKfgXaXIdbaHIdbg8Xa8UN:tUdbaHcwfIdbh8Waec3fgXaXIdba8UaHclfIdbg80N:tUdbaecafgXaXIdba8Ua8WN:tUdbaec8KfgXIdbhUaLa8Za8UMUdbaXaUa8Ua8Wa8WNa8Xa8XNa80a80NMMNMUdbkaQclfhQaHcxfhHaec8SfhealaOcefgO9hmbkkdnadTmbcbhhabhYinabahcdtfhXcbhHina5aXaHc:G1jjbfydbcdtfydbgOfRbbhedndna5aYaHfydbgQfRbbgLc99fcFeGcpe0mbaec99fcFeGc;:e6mekdnaLcufcFeGce0mba8EaQcdtfydbaO9hmekdnaecufcFeGce0mba8FaOcdtfydbaQ9hmekJbbacJbbacJbbbZaecFeGceSEaLcFeGceSEh88aaaOcx2fgeIdwaaaQcx2fgLIdwgB:tg80:mh86aeIdlaLIdlg83:tg8Z:mh89aeIdbaLIdbgR:tgU:mh8:dnaaaXaHc:K1jjbfydbcdtfydbcx2fgeIdwaB:tg8Va80a80NaUaUNa8Za8ZNMMg8YNa8Va80NaeIdbaR:tg81aUNa8ZaeIdla83:tg85NMMg8Wa80N:tg8Xa8XNa81a8YNa8WaUN:tg8Ua8UNa85a8YNa8Wa8ZN:tg8Wa8WNMM:rg87Jbbbb9ETmba8Xa87:vh8Xa8Wa87:vh8Wa8Ua87:vh8Uka88a8Y:rNg8Ya8XaBNa8UaRNa83a8WNMM:mgZNg87aZNhZa8Xa87Nhna8Wa87Nhca8Ua87Nh9ca8Ya8XNg87a8WNhJa87a8UNh9ea8Ya8WNgTa8UNhSa8Xa87Nh87a8WaTNhTa8Ua8Ya8UNNh9hdnaUa85Na81a89NMg8Xa8XNa8Za8VNa85a86NMg8Ua8UNa80a81Na8Va8:NMg8Wa8WNMM:rg80Jbbbb9ETmba8Xa80:vh8Xa8Wa80:vh8Wa8Ua80:vh8Uka8SaAaQcdtfydbc8S2fgeaeIdba9ha8Ua88a80:rNg80a8UNNMgUMUdbaeaTa8Wa80a8WNg8VNMg81aeIdlMUdlaea87a8Xa80a8XNg8ZNMg85aeIdwMUdwaeaSa8Va8UNMg8VaeIdxMUdxaea9ea8Za8UNMg87aeIdzMUdzaeaJa8Za8WNMg8ZaeIdCMUdCaea9ca8Ua80a8XaBNa8UaRNa83a8WNMMgB:mNg80NMg8UaeIdKMUdKaeaca8Wa80NMg8WaeId3MUd3aeana8Xa80NMg8XaeIdaMUdaaeaZaBa80N:tg80aeId8KMUd8Kaea8YJbbbbMg8YaeIdyMUdya8SaAaOcdtfydbc8S2fgeaUaeIdbMUdbaea81aeIdlMUdlaea85aeIdwMUdwaea8VaeIdxMUdxaea87aeIdzMUdzaea8ZaeIdCMUdCaea8UaeIdKMUdKaea8WaeId3MUd3aea8XaeIdaMUdaaea80aeId8KMUd8Kaea8YaeIdyMUdykaHclfgHcx9hmbkaYcxfhYahcifghad6mbkaCTmbcbhYinJbbbbh8YaaabaYcdtfgeclfydbghcx2fgHIdwaaaeydbggcx2fgOIdwg81:tg8Wa8WNaHIdbaOIdbg85:tg8Xa8XNaHIdlaOIdlg87:tg80a80NMMgRaaaecwfydbgEcx2fgeIdwa81:tg8ZNa8Wa8Wa8ZNa8XaeIdba85:tgUNa80aeIdla87:tgBNMMg8UN:tJbbbbJbbjZaRa8Za8ZNaUaUNaBaBNMMg8VNa8Ua8UN:tg83:va83Jbbbb9BEg83Nh89a8Va8WNa8Za8UN:ta83Nh8:aRaBNa80a8UN:ta83NhZa8Va80NaBa8UN:ta83NhnaRaUNa8Xa8UN:ta83Nhca8Va8XNaUa8UN:ta83Nh9ca8XaBNaUa80N:tg8Ua8UNa80a8ZNaBa8WN:tg8Ua8UNa8WaUNa8Za8XN:tg8Ua8UNMM:rJbbbZNh8UayagaC2g8LcdtfhHayaEaC2g8JcdtfhOayahaC2g8AcdtfhQa81:mhJa87:mh9ea85:mhTcbhLaChXJbbbbhBJbbbbh83JbbbbhRJbbbbh8VJbbbbh81Jbbbbh85Jbbbbh87Jbbbbh88Jbbbbh86inascjdfaLfgecwfa8Ua8:aQIdbaHIdbg8Z:tg80Na89aOIdba8Z:tgUNMg8WNUdbaeclfa8Uana80NaZaUNMg8XNUdbaea8Ua9ca80NacaUNMg80NUdbaecxfa8UaJa8WNa9ea8XNa8ZaTa80NMMMg8ZNUdba8Ua8Wa8XNNa8VMh8Va8Ua8Wa80NNa81Mh81a8Ua8Xa80NNa85Mh85a8Ua8Za8ZNNa8YMh8Ya8Ua8Wa8ZNNaBMhBa8Ua8Xa8ZNNa83Mh83a8Ua80a8ZNNaRMhRa8Ua8Wa8WNNa87Mh87a8Ua8Xa8XNNa88Mh88a8Ua80a80NNa86Mh86aHclfhHaQclfhQaOclfhOaLczfhLaXcufgXmbka8Kagc8S2fgea86aeIdbMUdbaea88aeIdlMUdlaea87aeIdwMUdwaea85aeIdxMUdxaea81aeIdzMUdzaea8VaeIdCMUdCaeaRaeIdKMUdKaea83aeId3MUd3aeaBaeIdaMUdaaea8YaeId8KMUd8Kaea8UaeIdyMUdya8Kahc8S2fgea86aeIdbMUdbaea88aeIdlMUdlaea87aeIdwMUdwaea85aeIdxMUdxaea81aeIdzMUdzaea8VaeIdCMUdCaeaRaeIdKMUdKaea83aeId3MUd3aeaBaeIdaMUdaaea8YaeId8KMUd8Kaea8UaeIdyMUdya8KaEc8S2fgea86aeIdbMUdbaea88aeIdlMUdlaea87aeIdwMUdwaea85aeIdxMUdxaea81aeIdzMUdzaea8VaeIdCMUdCaeaRaeIdKMUdKaea83aeId3MUd3aeaBaeIdaMUdaaea8YaeId8KMUd8Kaea8UaeIdyMUdyaDa8LcltfhXcbhHaChQinaXaHfgeascjdfaHfgOIdbaeIdbMUdbaeclfgLaOclfIdbaLIdbMUdbaecwfgLaOcwfIdbaLIdbMUdbaecxfgeaOcxfIdbaeIdbMUdbaHczfhHaQcufgQmbkaDa8AcltfhXcbhHaChQinaXaHfgeascjdfaHfgOIdbaeIdbMUdbaeclfgLaOclfIdbaLIdbMUdbaecwfgLaOcwfIdbaLIdbMUdbaecxfgeaOcxfIdbaeIdbMUdbaHczfhHaQcufgQmbkaDa8JcltfhXcbhHaChQinaXaHfgeascjdfaHfgOIdbaeIdbMUdbaeclfgLaOclfIdbaLIdbMUdbaecwfgLaOcwfIdbaLIdbMUdbaecxfgeaOcxfIdbaeIdbMUdbaHczfhHaQcufgQmbkaYcifgYad6mbkkcbhOdndnamcwGg9imbJbbbbhRcbh6cbh9kcbh0xekcbh6a3cbyd1:jjjbHjjjjbbh0asc:Cefasyd;8egecdtfa0BdbasaecefBd;8ecua0alabadaAz:fjjjbgQcltaQcjjjjiGEcbyd1:jjjbHjjjjbbh9kasc:Cefasyd;8egecdtfa9kBdbasaecefBd;8ea9kaQa0aaalz:gjjjbJFFuuhRaQTmba9kheaQhHinaeIdbg8UaRaRa8U9EEhRaeclfheaHcufgHmbkaQh6kasydNeh9mdnalTmba9mclfhea9mydbhQa5hHalhLcbhOincbaeydbgXaQ9RaHRbbcpeGEaOfhOaHcefhHaeclfheaXhQaLcufgLmbkaOce4hOkcuadaO9Rcifg9ncx2a9nc;v:Q;v:Qe0Ecbyd1:jjjbHjjjjbbh9oasc:Cefasyd;8egecdtfa9oBdbasaecefBd;8ecua9ncdta9ncFFFFi0Ecbyd1:jjjbHjjjjbbh9pasc:Cefasyd;8egecdtfa9pBdbasaecefBd;8ea3cbyd1:jjjbHjjjjbbh8Pasc:Cefasyd;8egecdtfa8PBdbasaecefBd;8ealcbyd1:jjjbHjjjjbbh9qasc:Cefasyd;8egecdtfa9qBdbasaecefBd;8eaxaxNa8RJbbjZamclGEgnanN:vh88Jbbbbh86dnadak9nmbdna9nci6mbasyd:yeh9raCclth9sa9ocwfh9tJbbbbh87Jbbbbh86inascNefabadalaAz:cjjjbabhgcbh8Ncbh3inaba3cdtfh8LcbheindnaAagaefydbgOcdtghfydbgQaAa8Laec:W1jjbfydbcdtfydbgHcdtgEfydbgLSmba5aHfRbbgYcv2a5aOfRbbgXfc;a1jjbfRbbg8AaXcv2aYfg8Jc;a1jjbfRbbg8MVcFeGTmbdnaLaQ9nmba8Jc;G1jjbfRbbcFeGmekdnaXcufcFeGce0mbaYTmba8EahfydbaH9hmekdnaXTmbaYcufcFeGce0mba8FaEfydbaO9hmeka9oa8Ncx2fgQaHaOa8McFeGgLEBdlaQaOaHaLEBdbaQaLa8AGcb9hBdwa8Ncefh8Nkaeclfgecx9hmbkdna3cifg3ad9pmbagcxfhga8Ncifa9n9nmekka8NTmdcbh8Jina8SaAa9oa8Jcx2fghydbgLcdtgQfydbggc8S2fgeIdwaaahydlgXcx2fgHIdwg8XNaeIdzaHIdbg80NaeIdaMg8Ua8UMMa8XNaeIdlaHIdlg8ZNaeIdCa8XNaeId3Mg8Ua8UMMa8ZNaeIdba80NaeIdxa8ZNaeIdKMg8Ua8UMMa80NaeId8KMMM:lh8UJbbbbJbbjZaeIdyg8W:va8WJbbbb9BEh8Wdndnahydwg8LmbJFFuuh83xekJbbbbJbbjZa8SaAaXcdtfydbc8S2fgeIdygU:vaUJbbbb9BEaeIdwaaaLcx2fgHIdwgUNaeIdzaHIdbg8YNaeIdaMgBaBMMaUNaeIdlaHIdlgBNaeIdCaUNaeId3MgUaUMMaBNaeIdba8YNaeIdxaBNaeIdKMgUaUMMa8YNaeId8KMMM:lNh83ka8Wa8UNhBdnaCTmba8KaLc8S2fgOIdwa8XNaOIdza80NaOIdaMg8Ua8UMMa8XNaOIdla8ZNaOIdCa8XNaOId3Mg8Ua8UMMa8ZNaOIdba80NaOIdxa8ZNaOIdKMg8Ua8UMMa80NaOId8KMMMh8UayaXaC2gYcdtfhHaDaLaC2gEcltfheaOIdyhUaChOinaHIdbg8Wa8WaUNaecxfIdba8XaecwfIdbNa80aeIdbNa8ZaeclfIdbNMMMg8Wa8WM:tNa8UMh8UaHclfhHaeczfheaOcufgOmbkdndna8LmbJbbbbh8Wxeka8KaXc8S2fgOIdwaaaLcx2fgeIdwg80NaOIdzaeIdbg8ZNaOIdaMg8Wa8WMMa80NaOIdlaeIdlgUNaOIdCa80NaOId3Mg8Wa8WMMaUNaOIdba8ZNaOIdxaUNaOIdKMg8Wa8WMMa8ZNaOId8KMMMh8WayaEcdtfhHaDaYcltfheaOIdyh8YaChOinaHIdbg8Xa8Xa8YNaecxfIdba80aecwfIdbNa8ZaeIdbNaUaeclfIdbNMMMg8Xa8XM:tNa8WMh8WaHclfhHaeczfheaOcufgOmbka8W:lh8WkaBa8U:lMhBa83a8WMh83dndndna5aLfRbbc9:fPddbekaKaQfydbgQaLSmbaAaXcdtfydbhEindndna8EaQcdtgYfydbgecuSmbaAaecdtfydbaESmekdna8FaYfydbgecuSmbaAaecdtfydbaESmekaXheka8KaQc8S2fgOIdwaaaecx2fgHIdwg8XNaOIdzaHIdbg80NaOIdaMg8Ua8UMMa8XNaOIdlaHIdlg8ZNaOIdCa8XNaOId3Mg8Ua8UMMa8ZNaOIdba80NaOIdxa8ZNaOIdKMg8Ua8UMMa80NaOId8KMMMh8UayaeaC2cdtfhHaDaQaC2cltfheaOIdyhUaChOinaHIdbg8Wa8WaUNaecxfIdba8XaecwfIdbNa80aeIdbNa8ZaeclfIdbNMMMg8Wa8WM:tNa8UMh8UaHclfhHaeczfheaOcufgOmbkaBa8U:lMhBaKaYfydbgQaL9hmbkka5aXfRbbci9hmea8LTmeaKaXcdtfydbgQaXSmeindndna8EaQcdtgYfydbgecuSmbaAaecdtfydbagSmekdna8FaYfydbgecuSmbaAaecdtfydbagSmekaLheka8KaQc8S2fgOIdwaaaecx2fgHIdwg8XNaOIdzaHIdbg80NaOIdaMg8Ua8UMMa8XNaOIdlaHIdlg8ZNaOIdCa8XNaOId3Mg8Ua8UMMa8ZNaOIdba80NaOIdxa8ZNaOIdKMg8Ua8UMMa80NaOId8KMMMh8UayaeaC2cdtfhHaDaQaC2cltfheaOIdyhUaChOinaHIdbg8Wa8WaUNaecxfIdba8XaecwfIdbNa80aeIdbNa8ZaeclfIdbNMMMg8Wa8WM:tNa8UMh8UaHclfhHaeczfheaOcufgOmbka83a8U:lMh83aKaYfydbgQaX9hmbxdkkdna8Fa8Ea8EaQfydbaXSEaKaQfydbgYcdtfydbgQcu9hmbaKaXcdtfydbhQka8KaYc8S2fgOIdwaaaQcx2fgeIdwg8XNaOIdzaeIdbg80NaOIdaMg8Ua8UMMa8XNaOIdlaeIdlg8ZNaOIdCa8XNaOId3Mg8Ua8UMMa8ZNaOIdba80NaOIdxa8ZNaOIdKMg8Ua8UMMa80NaOId8KMMMh8UayaQaC2ggcdtfhHaDaYaC2gEcltfheaOIdyhUaChOinaHIdbg8Wa8WaUNaecxfIdba8XaecwfIdbNa80aeIdbNa8ZaeclfIdbNMMMg8Wa8WM:tNa8UMh8UaHclfhHaeczfheaOcufgOmbkdndna8LmbJbbbbh8Wxeka8KaQc8S2fgOIdwaaaYcx2fgeIdwg80NaOIdzaeIdbg8ZNaOIdaMg8Wa8WMMa80NaOIdlaeIdlgUNaOIdCa80NaOId3Mg8Wa8WMMaUNaOIdba8ZNaOIdxaUNaOIdKMg8Wa8WMMa8ZNaOId8KMMMh8WayaEcdtfhHaDagcltfheaOIdyh8YaChOinaHIdbg8Xa8Xa8YNaecxfIdba80aecwfIdbNa8ZaeIdbNaUaeclfIdbNMMMg8Xa8XM:tNa8WMh8WaHclfhHaeczfheaOcufgOmbka8W:lh8WkaBa8U:lMhBa83a8WMh83kaha83aBa83aB9DgeEUdwahaLaXaea8Lcb9hGgeEBdlahaXaLaeEBdba8Jcefg8Ja8N9hmbkascjdfcbcj;qbz:tjjjb8Aa9thea8NhHinascjdfaeydbcA4cF8FGgOcFAaOcFA6EcdtfgOaOydbcefBdbaecxfheaHcufgHmbkcbhecbhHinascjdfaefgOydbhQaOaHBdbaQaHfhHaeclfgecj;qb9hmbkcbhea9thHinascjdfaHydbcA4cF8FGgOcFAaOcFA6EcdtfgOaOydbgOcefBdba9paOcdtfaeBdbaHcxfhHa8Naecefge9hmbkadak9RgOci9Uh9udnalTmbcbhea8PhHinaHaeBdbaHclfhHalaecefge9hmbkkcbh9va9qcbalz:tjjjbh9waOcO9Uh9xa9uce4h9ycbh3cbh8Adnina9oa9pa8Acdtfydbcx2fg8JIdwg8Ua889Emea3a9u9pmeJFFuuh8Wdna9ya8N9pmba9oa9pa9ycdtfydbcx2fIdwJbb;aZNh8Wkdna8Ua8W9ETmba8Ua869ETmba3a9x0mdkdna9waAa8Jydlg8Mcdtg9zfgEydbgQfg9ARbba9waAa8Jydbggcdtg9Bfydbgefg9CRbbVmba5agfRbbh9Ddna9maecdtfgHclfydbgOaHydbgHSmbaOaH9RhLaaaQcx2fhYaaaecx2fhha9raHcitfhecbhHceh8Ldnindna8PaeydbcdtfydbgOaQSmba8PaeclfydbcdtfydbgXaQSmbaOaXSmbaaaXcx2fgXIdbaaaOcx2fgOIdbg8X:tg8UahIdlaOIdlg80:tg8YNahIdba8X:tgBaXIdla80:tg8WN:tg8Za8UaYIdla80:tg83NaYIdba8X:tg8Va8WN:tg80Na8WahIdwaOIdwgU:tg81Na8YaXIdwaU:tg8XN:tg8Ya8WaYIdwaU:tg85Na83a8XN:tg8WNa8XaBNa81a8UN:tgUa8Xa8VNa85a8UN:tg8UNMMa8Za8ZNa8Ya8YNaUaUNMMa80a80Na8Wa8WNa8Ua8UNMMN:rJbbj8:N9FmdkaecwfheaHcefgHaL6h8LaLaH9hmbkka8LceGTmba9ycefh9yxekdndndndna9Dc9:fPdebdkagheinaEydbhOdndna8EaecdtgHfydbgecuSmbaAaecdtfydbaOSmekdna8FaHfydbgecuSmbaAaecdtfydbaOSmeka8Mheka8PaHfaeBdbaKaHfydbgeag9hmbxikkdna8Fa8Ea8Ea9Bfydba8MSEaKa9Bfydbggcdtfydbgecu9hmbaKa9zfydbheka8Pa9Bfa8MBdbaeh8Mka8Pagcdtfa8MBdbka9Cce86bba9Ace86bba8JIdwg8Ua86a86a8U9DEh86a9vcefh9vcecda9DceSEa3fh3ka8Acefg8Aa8N9hmbkka9vTmddnalTmbcbhXcbhhindna8PahcdtgefydbgOahSmbaAaOcdtfydbhgdnahaAaefydb9hgEmba8Sagc8S2fgea8Sahc8S2fgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdyaITmbaIagcltfgeaIahcltfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxkaCTmba8KaOc8S2fgea8Kahc8S2g8LfgHIdbaeIdbMUdbaeaHIdlaeIdlMUdlaeaHIdwaeIdwMUdwaeaHIdxaeIdxMUdxaeaHIdzaeIdzMUdzaeaHIdCaeIdCMUdCaeaHIdKaeIdKMUdKaeaHId3aeId3MUd3aeaHIdaaeIdaMUdaaeaHId8KaeId8KMUd8KaeaHIdyaeIdyMUdya9saO2hYaDhHaChQinaHaYfgeaHaXfgOIdbaeIdbMUdbaeclfgLaOclfIdbaLIdbMUdbaecwfgLaOcwfIdbaLIdbMUdbaecxfgeaOcxfIdbaeIdbMUdbaHczfhHaQcufgQmbkaEmbJbbbbJbbjZa8Sa8LfgeIdyg8U:va8UJbbbb9BEaeIdwaaagcx2fgHIdwg8UNaeIdzaHIdbg8WNaeIdaMg8Xa8XMMa8UNaeIdlaHIdlg8XNaeIdCa8UNaeId3Mg8Ua8UMMa8XNaeIdba8WNaeIdxa8XNaeIdKMg8Ua8UMMa8WNaeId8KMMM:lNg8Ua87a87a8U9DEh87kaXa9sfhXahcefghal9hmbkcbhHa8EheindnaeydbgOcuSmbdnaHa8PaOcdtgQfydbgO9hmbcuhOa8EaQfydbgQcuSmba8PaQcdtfydbhOkaeaOBdbkaeclfhealaHcefgH9hmbkcbhHa8FheindnaeydbgOcuSmbdnaHa8PaOcdtgQfydbgO9hmbcuhOa8FaQfydbgQcuSmba8PaQcdtfydbhOkaeaOBdbkaeclfhealaHcefgH9hmbkka87a86aCEh87cbhHabhecbhOindnaAa8PaeydbcdtfydbgXcdtfydbgQaAa8PaeclfydbcdtfydbgYcdtfydbgLSmbaQaAa8PaecwfydbcdtfydbggcdtfydbghSmbaLahSmbabaHcdtfgQaXBdbaQcwfagBdbaQclfaYBdbaHcifhHkaecxfheaOcifgOad6mbkdndna9imbaHhdxekdnaHak0mbaHhdxekdnaRa879FmbaHhdxekJFFuuhRcbhdabhecbhOindna9ka0aeydbgQcdtfydbcdtfIdbg8Ua879ETmbaeclf8Pdbh9EabadcdtfgLaQBdbaLclfa9E83dba8UaRaRa8U9EEhRadcifhdkaecxfheaOcifgOaH6mbkkadak0mbxdkkascNefabadalaAz:cjjjbkdndnadak0mbadhhxekdna9imbadhhxekdnaRa889FmbadhhxekcehLinaRJbb;aZNg8Ua88a8Ua889DEh8XJbbbbh8Udna6Tmba9khea6hHinaeIdbg8Wa8Ua8Wa8X9FEa8Ua8Wa8U9EEh8UaeclfheaHcufgHmbkkJFFuuhRcbhhabhecbhHindna9ka0aeydbgOcdtfydbcdtfIdbg8Wa8X9ETmbaeclf8Pdbh9EabahcdtfgQaOBdbaQclfa9E83dba8WaRaRa8W9EEhRahcifhhkaecxfheaHcifgHad6mbkdnaLahad9hVceGmbadhhxdka8Ua86a86a8U9DEh86ahak9nmecbhLahhdaRa889FmbkkdnamcjjjjdGTmba9qcbalz:tjjjbh8LdnahTmbabheahhHina8LaeydbgOfce86bba8LaAaOcdtfydbfce86bbaeclfheaHcufgHmbkkascNefabahalaAz:cjjjbdndndnalTmbcbhQasyd:yehEindna8LaQfRbbTmbdna5aQfRbbgecl0mbceaetcQGmekdnaAaQcdtgXfydbgeaQSmbaaaQcx2fgHaaaecx2fge8Pdb83dbaHcwfaecwfydbBdbxeka8SaQc8S2fgLIdyg9ca9cJL:3;rUNg8UMh88aLIdwg9ha8UMhRaLIdlgxa8UMh8VaLIdbg9Fa8UMhUaLIdag9Ga8UaaaQcx2fggIdwg89N:th81aLId3g9Ha8UagIdlg8:N:th85aLIdKg9IagIdbgZa8UN:th8YJbbbbhcaLIdCg9JJbbbbMh87aLIdzg9KJbbbbMhBaLIdxgWJbbbbMh83dndnaCTmbaQhOinJbbbba88a8KaOc8S2fgHIdyg8U:va8UJbbbb9BEh8UaDaOaC2cltfheaHIdaa88Na81Mh81aHId3a88Na85Mh85aHIdKa88Na8YMh8YaHIdCa88Na87Mh87aHIdza88NaBMhBaHIdxa88Na83Mh83aHIdwa88NaRMhRaHIdla88Na8VMh8VaHIdba88NaUMhUaChHina81aecxfIdbg8ZaecwfIdbg8WNa8UN:th81a85a8ZaeclfIdbg8XNa8UN:th85a87a8Wa8XNa8UN:th87aUaeIdbg80a80Na8UN:thUa8Ya8Za80Na8UN:th8YaBa8Wa80Na8UN:thBa83a8Xa80Na8UN:th83aRa8Wa8WNa8UN:thRa8Va8Xa8XNa8UN:th8VaeczfheaHcufgHmbkaKaOcdtfydbgOaQ9hmbkaITmbaIaQcltfgeIdxhSaeIdwhJaeIdlh9eaeIdbh8UxekJbbbbhSJbbbbhJJbbbbh9eJbbbbh8UkaBaU:vg8Xa8YNa81:ta87aBa83aU:vg8WN:tg81a8Va83a8WN:tg8Z:vg80a8Wa8YNa85:tg8VN:th85aJa8Ua8XN:ta9ea8Ua8WN:tg83a80N:tg87aRaBa8XN:ta81a80N:tgB:vgR:mh81a83a8Z:vgJ:mh9ednJbbbba8Ua8UaU:vgTN:ta83aJN:ta87aRN:tg83:la88J:983:g81Ng8U9ETmba81a85Na9ea8VNaTa8YNaS:tMMa83:vhckaU:la8U9ETmba8Z:la8U9ETmbaB:la8U9ETmbaT:macNa8X:ma81acNa85aB:vMgBNa8W:ma9eacNa80:maBNa8Va8Z:vMMg87Na8Y:maU:vMMMh88a9maXfgeclfydbgHaeydbge9RhYaEaecitfhXJbbbbh8UdnaHaeSg8JmbJbbbbh8UaXheaYhOinaaaeclfydbcx2fgHIdwa89:tg8Wa8WNaHIdbaZ:tg8Wa8WNaHIdla8::tg8Wa8WNMMg8Waaaeydbcx2fgHIdwa89:tg8Xa8XNaHIdbaZ:tg8Xa8XNaHIdla8::tg8Xa8XNMMg8Xa8Ua8Ua8X9DEg8Ua8Ua8W9DEh8UaecwfheaOcufgOmbkkaBa89:tg8Wa8WNa88aZ:tg8Wa8WNa87a8::tg8Wa8WNMMa8U:rg8Ua8UN9EmbaLId8Khcdna8JmbcbhOcehLdninaaaXclfydbcx2fgeIdbaaaXydbcx2fgHIdbg8X:tg8Ua8:aHIdlg80:tg8YNaZa8X:tg83aeIdla80:tg8WN:tg8Za8Ua87a80:tgRNa88a8X:tg8Va8WN:tg80Na8Wa89aHIdwgU:tg81Na8YaeIdwaU:tg8XN:tg8Ya8WaBaU:tg85NaRa8XN:tg8WNa8Xa83Na81a8UN:tgUa8Xa8VNa85a8UN:tg8UNMMa8Za8ZNa8Ya8YNaUaUNMMa80a80Na8Wa8WNa8Ua8UNMMN:rJbbj8:N9FmeaXcwfhXaOcefgOaY6hLaYaO9hmbkkaLceGmekJbbbbJbbjZa9c:va9cJbbbb9BEg8Ua9haBNa9Ka88Na9GMg8Wa8WMMaBNaxa87Na9JaBNa9HMg8Wa8WMMa87Na9Fa88NaWa87Na9IMg8Wa8WMMa88NacMMM:lNa8Ua9ha89Na9KaZNa9GMg8Wa8WMMa89Naxa8:Na9Ja89Na9HMg8Wa8WMMa8:Na9FaZNaWa8:Na9IMg8Wa8WMMaZNacMMM:lNJbb;aZNJ:983:g81M9EmbagaBUdwaga87Udlaga88UdbkaQcefgQal9hmbkaCTmecbhLindna8LaLfRbbTmbaAaLcdtgefydbaL9hmba5aLfhEaaaLcx2fhOaKaefh8JayaLaC2cdtfh8AcbhgincuhQdnaERbbci9hmbaLhQa8JydbgeaLSmbayagcdtgHfhXa8AaHfIdbh8UaLhQinaQhHcuhQdnaXaeaC2cdtfIdba8U9CmbaHcuSmbaHhQa8Kaec8S2fIdya8KaHc8S2fIdy9ETmbaehQkaKaecdtfydbgeaL9hmbkkayagcdtfhXaDagcltfhYaLheinaXaeaC2cdtfJbbbbJbbjZa8KaeaQaQcuSEgHc8S2fIdyg8U:va8UJbbbb9BEaYaHaC2cltfgHIdwaOIdwNaHIdbaOIdbNaHIdlaOIdlNMMaHIdxMNUdbaKaecdtfydbgeaL9hmbkagcefggaC9hmbkkaLcefgLalSmixbkkaCmekcbhCkaiavaoarawaCalaaayazasa8Rasc1efa5a8Laqz:hjjjbkdnamcjjjjlGTmbazmbahTmbcbhQabheina5aeydbgAfRbbc3thLaecwfgKydbhHdndna8EaAcdtgYfydbaeclfgXydbgOSmbcbhCa8FaOcdtfydbaA9hmekcjjjj94hCkaeaLaCVaAVBdba5aOfRbbc3thLdndna8EaOcdtfydbaHSmbcbhCa8FaHcdtfydbaO9hmekcjjjj94hCkaXaLaCVaOVBdba5aHfRbbc3thCdndna8EaHcdtfydbaASmbcbhOa8FaYfydbaH9hmekcjjjj94hOkaKaCaOVaHVBdbaecxfheaQcifgQah6mbkkdnazTmbahTmbahheinabazabydbcdtfydbBdbabclfhbaecufgembkkdnaPTmbaPana86:rNUdbkasyd;8egecdtasc:Ceffc98fhHdninaeTmeaHydbcbyd:m:jjjbH:bjjjbbaHc98fhHaecufhexbkkascj;sbf8Kjjjjbahk;Yieouabydlhvabydbclfcbaicdtz:tjjjbhoadci9UhrdnadTmbdnalTmbaehwadhDinaoalawydbcdtfydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbxdkkaehwadhDinaoawydbcdtfgqaqydbcefBdbawclfhwaDcufgDmbkkdnaiTmbcbhDaohwinawydbhqawaDBdbawclfhwaqaDfhDaicufgimbkkdnadci6mbinaecwfydbhwaeclfydbhDaeydbhidnalTmbalawcdtfydbhwalaDcdtfydbhDalaicdtfydbhikavaoaicdtfgqydbcitfaDBdbavaqydbcitfawBdlaqaqydbcefBdbavaoaDcdtfgqydbcitfawBdbavaqydbcitfaiBdlaqaqydbcefBdbavaoawcdtfgwydbcitfaiBdbavawydbcitfaDBdlawawydbcefBdbaecxfhearcufgrmbkkabydbcbBdbk:todDue99aicd4aifhrcehwinawgDcethwaDar6mbkcuaDcdtgraDcFFFFi0Ecbyd1:jjjbHjjjjbbhwaoaoyd9GgqcefBd9GaoaqcdtfawBdbawcFearz:tjjjbhkdnaiTmbalcd4hlaDcufhxcbhminamhDdnavTmbavamcdtfydbhDkcbadaDal2cdtfgDydlgwawcjjjj94SEgwcH4aw7c:F:b:DD2cbaDydbgwawcjjjj94SEgwcH4aw7c;D;O:B8J27cbaDydwgDaDcjjjj94SEgDcH4aD7c:3F;N8N27axGhwamcdthPdndndnavTmbakawcdtfgrydbgDcuSmeadavaPfydbal2cdtfgsIdbhzcehqinaqhrdnadavaDcdtfydbal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmlkarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbxdkkakawcdtfgrydbgDcuSmbadamal2cdtfgsIdbhzcehqinaqhrdnadaDal2cdtfgqIdbaz9CmbaqIdlasIdl9CmbaqIdwasIdw9BmikarcefhqakawarfaxGgwcdtfgrydbgDcu9hmbkkaramBdbamhDkabaPfaDBdbamcefgmai9hmbkkakcbyd:m:jjjbH:bjjjbbaoaoyd9GcufBd9GdnaeTmbaiTmbcbhDaehwinawaDBdbawclfhwaiaDcefgD9hmbkcbhDaehwindnaDabydbgrSmbawaearcdtfgrydbBdbaraDBdbkawclfhwabclfhbaiaDcefgD9hmbkkk:hrdvuv998Jjjjjbca9Rgoczfcwfcbyd11jjbBdbaocb8Pdj1jjb83izaocwfcbydN1jjbBdbaocb8Pd:m1jjb83ibdnadTmbaicd4hrdnabmbdnalTmbcbhwinaealawcdtfydbar2cdtfhDcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxikkarcdthwcbhDincbhiinaoczfaifgqaeaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaeawfheaDcefgDad9hmbxdkkdnalTmbcbhwinabawcx2fgiaealawcdtfydbar2cdtfgDIdbUdbaiaDIdlUdlaiaDIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkawcefgwad9hmbxdkkarcdthlcbhwaehDinabawcx2fgiaeawar2cdtfgqIdbUdbaiaqIdlUdlaiaqIdwUdwcbhiinaoczfaifgqaDaifIdbgkaqIdbgxaxak9EEUdbaoaifgqakaqIdbgxaxak9DEUdbaiclfgicx9hmbkaDalfhDawcefgwad9hmbkkJbbbbaoIdbaoIdzgx:tgkakJbbbb9DEgkaoIdlaoIdCgm:tgPaPak9DEgkaoIdwaoIdKgP:tgsasak9DEhsdnabTmbadTmbJbbbbJbbjZas:vasJbbbb9BEhkinabakabIdbax:tNUdbabclfgoakaoIdbam:tNUdbabcwfgoakaoIdbaP:tNUdbabcxfhbadcufgdmbkkdnavTmbavaPUdwavamUdlavaxUdbkask:ZlewudnaeTmbcbhvabhoinaoavBdbaoclfhoaeavcefgv9hmbkkdnaiTmbcbhrinadarcdtfhwcbhDinalawaDcdtgvc:G1jjbfydbcdtfydbcdtfydbhodnabalawavfydbcdtfydbgqcdtfgkydbgvaqSmbinakabavgqcdtfgxydbgvBdbaxhkaqav9hmbkkdnabaocdtfgkydbgvaoSmbinakabavgocdtfgxydbgvBdbaxhkaoav9hmbkkdnaqaoSmbabaqaoaqao0Ecdtfaqaoaqao6EBdbkaDcefgDci9hmbkarcifgrai6mbkkdnaembcbskcbhxindnalaxcdtgvfydbax9hmbaxhodnabavfgDydbgvaxSmbaDhqinaqabavgocdtfgkydbgvBdbakhqaoav9hmbkkaDaoBdbkaxcefgxae9hmbkcbhvabhocbhkindndnavalydbgq9hmbdnavaoydbgq9hmbaoakBdbakcefhkxdkaoabaqcdtfydbBdbxekaoabaqcdtfydbBdbkaoclfhoalclfhlaeavcefgv9hmbkakk;Jiilud99duabcbaecltz:tjjjbhvdnalTmbadhoaihralhwinarcwfIdbhDarclfIdbhqavaoydbcltfgkarIdbakIdbMUdbakclfgxaqaxIdbMUdbakcwfgxaDaxIdbMUdbakcxfgkakIdbJbbjZMUdbaoclfhoarcxfhrawcufgwmbkkdnaeTmbavhraehkinarcxfgoIdbhDaocbBdbararIdbJbbbbJbbjZaD:vaDJbbbb9BEgDNUdbarclfgoaDaoIdbNUdbarcwfgoaDaoIdbNUdbarczfhrakcufgkmbkkdnalTmbinavadydbcltfgrcxfgkaicwfIdbarcwfIdb:tgDaDNaiIdbarIdb:tgDaDNaiclfIdbarclfIdb:tgDaDNMMgDakIdbgqaqaD9DEUdbadclfhdaicxfhialcufglmbkkdnaeTmbavcxfhrinabarIdbUdbarczfhrabclfhbaecufgembkkk:moerudnaoTmbaecd4hzdnavTmbaicd4hHavcdthOcbhAindnaPaAfRbbTmbaAhednaDTmbaDaAcdtfydbhekdnasTmbasaefRbbceGmekdnamaAfRbbclSmbabaeaz2cdtfgiaraAcx2fgCIdbakNaxIdbMUdbaiaCIdlakNaxIdlMUdlaiaCIdwakNaxIdwMUdwkadaeaH2cdtfhXaqheawhiavhCinaXaeydbcdtgQfaiIdbalaQfIdb:vUdbaeclfheaiclfhiaCcufgCmbkkawaOfhwaAcefgAao9hmbxdkkdnasmbcbheaDhiindnaPaefRbbTmbaehCdnaDTmbaiydbhCkamaefRbbclSmbabaCaz2cdtfgCarIdbakNaxIdbMUdbaCarclfIdbakNaxIdlMUdlaCarcwfIdbakNaxIdwMUdwkaiclfhiarcxfhraoaecefge9hmbxdkkdnaDTmbindnaPRbbTmbasaDydbgefRbbceGmbamRbbclSmbabaeaz2cdtfgearIdbakNaxIdbMUdbaearclfIdbakNaxIdlMUdlaearcwfIdbakNaxIdwMUdwkaPcefhPaDclfhDamcefhmarcxfhraocufgombxdkkazcdthicbheindnaPaefRbbTmbasaefRbbceGmbamaefRbbclSmbabarIdbakNaxIdbMUdbabclfarclfIdbakNaxIdlMUdbabcwfarcwfIdbakNaxIdwMUdbkarcxfhrabaifhbaoaecefge9hmbkkk8MbabaeadaialavcbcbcbcbcbaoarawaDz:bjjjbk8MbabaeadaialavaoarawaDaqakaxamaPz:bjjjbkRbababaeadaialavaoarawaDaqakaxcjjjjdVamz:bjjjbk:d8Koque99due99duq998Jjjjjbc;Wb9Rgq8Kjjjjbcbhkaqcxfcbc;Kbz:tjjjb8Aaqcualcx2alc;v:Q;v:Qe0Ecbyd1:jjjbHjjjjbbgxBdxaqceBd2axaialavcbcbz:ejjjb8AaqcualcdtalcFFFFi0Egmcbyd1:jjjbHjjjjbbgiBdzaqcdBd2dndnJFF959eJbbjZawJbbjZawJbbjZ9DE:vawJ9VO:d869DEgw:lJbbb9p9DTmbaw:OhPxekcjjjj94hPkadci9Uhsarco9UhzdndnaombaPcd9imekdnalTmbaPcuf:YhwdnaoTmbcbhvaihHaxhOindndnaoavfRbbceGTmbavcjjjjlVhAxekdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHaOcxfhOalavcefgv9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkadTmbcbhkaehvcbhOinakaiavclfydbcdtfydbgHaiavcwfydbcdtfydbgA9haiavydbcdtfydbgXaH9haXaA9hGGfhkavcxfhvaOcifgOad6mbkkarci9UhQdndnaz:Z:rJbbbZMgw:lJbbb9p9DTmbaw:Ohvxekcjjjj94hvkaQ:ZhLcbhKc:bwhzdninakaQ9pmeazaP9Rcd9imeavazcufavaz9iEaPcefavaP9kEhYdnalTmbaYcuf:YhwdnaoTmbcbhOaihHaxhvindndnaoaOfRbbceGTmbaOcjjjjlVhAxekdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcqthAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXVhAdndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaAaXcCtVhAkaHaABdbaHclfhHavcxfhvalaOcefgO9hmbxdkkaxhvaihOalhHindndnavIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhAxekcjjjj94hAkaAcCthAdndnavclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqtaAVhAdndnavcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaOaAaXVBdbavcxfhvaOclfhOaHcufgHmbkkcbhOdnadTmbaehvcbhHinaOaiavclfydbcdtfydbgAaiavcwfydbcdtfydbgX9haiavydbcdtfydbgraA9haraX9hGGfhOavcxfhvaHcifgHad6mbkkJbbbbh8Adnas:ZgCaL:taY:Ygwaz:Y:tgENak:Zg3aO:Zg5:tNa3aL:tawaP:Y:tg8ENa5aC:tNMg8FJbbbb9BmbaCa3:ta8EaEa5aL:tNNNa8F:vh8AkdndnaOaQ0mbaOhkaYhPxekaOhsaYhzkdndnaKcl0mbdna8AawMJbbbZMgw:lJbbb9p9DTmbaw:Ohvxdkcjjjj94hvxekaPazfcd9ThvkaKcefgKcs9hmbkkdndndnakmbJbbjZhwcbhicdhvaDmexdkalcd4alfhHcehOinaOgvcethOavaH6mbkcbhOaqcuavcdtgYavcFFFFi0Ecbyd1:jjjbHjjjjbbgKBdCaqciBd2aqamcbyd1:jjjbHjjjjbbgzBdKaqclBd2dndndndnalTmbaPcuf:YhwaoTmecbhOaihAaxhHindndnaoaOfRbbceGTmbaOcjjjjlVhXxekdndnaHclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcqthXdndnaHcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarVhXdndnaHIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaXarcCtVhXkaAaXBdbaAclfhAaHcxfhHalaOcefgO9hmbxikkaKcFeaYz:tjjjb8AcbhPcbhvxdkaxhOaihHalhAindndnaOIdbawNJbbbZMgC:lJbbb9p9DTmbaC:OhXxekcjjjj94hXkaXcCthXdndnaOclfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkarcqtaXVhXdndnaOcwfIdbawNJbbbZMgC:lJbbb9p9DTmbaC:Ohrxekcjjjj94hrkaHaXarVBdbaOcxfhOaHclfhHaAcufgAmbkkaKcFeaYz:tjjjbhravcufhocbhPcbhYindndndnaraiaYcdtgKfydbgAcm4aA7c:v;t;h;Ev2gvcs4av7aoGgHcdtfgXydbgOcuSmbcehvinaiaOcdtgOfydbaASmdaHavfhOavcefhvaraOaoGgHcdtfgXydbgOcu9hmbkkaXaYBdbaPhvaPcefhPxekazaOfydbhvkazaKfavBdbaYcefgYal9hmbkcuaPc8S2gOaPc;D;O;f8U0Ehvkcbhraqavcbyd1:jjjbHjjjjbbgvBd3aqcvBd2avcbaOz:tjjjbhOdnadTmbaehiinJbbnnJbbjZazaiydbgAcdtfydbgvazaiclfydbgHcdtfydbgYSavazaicwfydbgXcdtfydbgKSGgoEh8EdnaxaHcx2fgHIdbaxaAcx2fgAIdbg5:tgCaxaXcx2fgXIdlaAIdlg8A:tgwNaXIdba5:tg3aHIdla8A:tg8FN:tgLaLNa8FaXIdwaAIdwgE:tgaNawaHIdwaE:tg8FN:tgwawNa8Fa3NaaaCN:tgCaCNMM:rg3Jbbbb9ETmbaLa3:vhLaCa3:vhCawa3:vhwkaOavc8S2fgvavIdbawa8Ea3:rNg3awNNg8FMUdbavaCa3aCNgaNghavIdlMUdlavaLa3aLNg8ENggavIdwMUdwavaaawNgaavIdxMUdxava8EawNg8JavIdzMUdzava8EaCNg8EavIdCMUdCavawa3aLaENawa5Na8AaCNMM:mg8ANg5NgwavIdKMUdKavaCa5NgCavId3MUd3avaLa5NgLavIdaMUdaava5a8ANg5avId8KMUd8Kava3avIdyMUdydnaombaOaYc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava5avId8KMUd8Kava3avIdyMUdyaOaKc8S2fgva8FavIdbMUdbavahavIdlMUdlavagavIdwMUdwavaaavIdxMUdxava8JavIdzMUdzava8EavIdCMUdCavawavIdKMUdKavaCavId3MUd3avaLavIdaMUdaava5avId8KMUd8Kava3avIdyMUdykaicxfhiarcifgrad6mbkkcbhAaqcuaPcdtgvaPcFFFFi0Egicbyd1:jjjbHjjjjbbgHBdaaqcoBd2aqaicbyd1:jjjbHjjjjbbgiBd8KaqcrBd2aHcFeavz:tjjjbhYdnalTmbazhHinJbbbbJbbjZaOaHydbgXc8S2fgvIdygw:vawJbbbb9BEavIdwaxcwfIdbgwNavIdzaxIdbgCNavIdaMgLaLMMawNavIdlaxclfIdbgLNavIdCawNavId3MgwawMMaLNavIdbaCNavIdxaLNavIdKMgwawMMaCNavId8KMMM:lNhwdndnaYaXcdtgvfgXydbcuSmbaiavfIdbaw9ETmekaXaABdbaiavfawUdbkaHclfhHaxcxfhxalaAcefgA9hmbkkJbbbbhwdnaPTmbinaiIdbgCawawaC9DEhwaiclfhiaPcufgPmbkkakcd4akfhOcehiinaigvcethiavaO6mbkcbhiaqcuavcdtgOavcFFFFi0Ecbyd1:jjjbHjjjjbbgHBdyaHcFeaOz:tjjjbhXdnadTmbavcufhrcbhPcbhxindnazaeaxcdtfgvydbcdtfydbgiazavclfydbcdtfydbgOSmbaiazavcwfydbcdtfydbgvSmbaOavSmbaYavcdtfydbhAdndnaYaOcdtfydbgvaYaicdtfydbgi9pmbavaA9pmbaAhlaihoavhAxekdnaAai9pmbaAav9pmbaihlavhoxekavhlaAhoaihAkabaPcx2fgvaABdbavcwfaoBdbavclfalBdbdnaXaoc:3F;N8N2alc:F:b:DD27aAc;D;O:B8J27arGgOcdtfgvydbgicuSmbcehHinaHhvdnabaicx2fgiydbaA9hmbaiydlal9hmbaiydwaoSmikavcefhHaXaOavfarGgOcdtfgvydbgicu9hmbkkavaPBdbaPcefhPkaxcifgxad6mbkaPci2hikdnaDmbcwhvxdkaw:rhwcwhvkaDawUdbkavcdthvdninavTmeavc98fgvaqcxffydbcbyd:m:jjjbH:bjjjbbxbkkaqc;Wbf8Kjjjjbaik:2ldwue9:8Jjjjjbc;Wb9Rgr8Kjjjjbcbhwarcxfcbc;Kbz:tjjjb8AdnabaeSmbabaeadcdtzMjjjb8AkarcualcdtalcFFFFi0EgDcbyd1:jjjbHjjjjbbgqBdxarceBd2aqcbaialavcbarcxfz:djjjbcualcx2alc;v:Q;v:Qe0Ecbyd1:jjjbHjjjjbbhkarcxfaryd2gxcdtgmfakBdbaraxcefgPBd2akaialavcbcbz:ejjjb8AarcxfaPcdtfaDcbyd1:jjjbHjjjjbbgvBdbaraxcdfgiBd2arcxfaicdtfcuavalaeadaqz:fjjjbgecltaecjjjjiGEcbyd1:jjjbHjjjjbbgiBdbaiaeavakalz:gjjjbdnadTmbaoaoNhocbhwabhlcbhkindnaiavalydbgecdtfydbcdtfIdbao9ETmbalclf8PdbhsabawcdtfgqaeBdbaqclfas83dbawcifhwkalcxfhlakcifgkad6mbkkaxcifhlamarcxffcwfhkdninalTmeakydbcbyd:m:jjjbH:bjjjbbakc98fhkalcufhlxbkkarc;Wbf8Kjjjjbawk:XCoDud99vue99vuo998Jjjjjbc;Wb9Rgw8KjjjjbdndnarmbcbhDxekawcxfcbc;Kbz:tjjjb8Aawcuadcx2adc;v:Q;v:Qe0Ecbyd1:jjjbHjjjjbbgqBdxawceBd2aqaeadaicbcbz:ejjjb8AawcuadcdtadcFFFFi0Egkcbyd1:jjjbHjjjjbbgxBdzawcdBd2adcd4adfhmceheinaegicetheaiam6mbkcbhPawcuaicdtgsaicFFFFi0Ecbyd1:jjjbHjjjjbbgzBdCawciBd2dndnar:ZgH:rJbbbZMgO:lJbbb9p9DTmbaO:Ohexekcjjjj94hekaicufhAc:bwhDcbhCadhXcbhQinaeaDcufaeaD9iEaPcefaeaP9kEhLdndnadTmbaLcuf:YhOaqhiaxheadhmindndnaiIdbaONJbbbZMgK:lJbbb9p9DTmbaK:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaONJbbbZMgK:lJbbb9p9DTmbaK:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbh3cbh5indnaEaxa5cdtfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbaeaYSmbcehiinaEamaifaAGgmcdtfg8AydbgecuSmeaicefhiaeaY9hmbkka8AaYBdba3aecuSfh3a5cefg5ad9hmbxdkkazcFeasz:tjjjb8Acbh3kJbbbbh8EdnaX:ZgKaH:taL:YgOaD:Y:tg8FNaC:Zgaa3:Zgh:tNaaaH:taOaP:Y:tggNahaK:tNMg8JJbbbb9BmbaKaa:taga8FahaH:tNNNa8J:vh8EkaPaLa3ar0giEhPaCa3aiEhCdna3arSmbaLaDaiEgDaP9Rcd9imbdndnaQcl0mbdna8EaOMJbbbZMgO:lJbbb9p9DTmbaO:Ohexdkcjjjj94hexekaPaDfcd9Theka3aXaiEhXaQcefgQcs9hmekkdndnaCmbcihicbhDxekcbhiawakcbyd1:jjjbHjjjjbbg5BdKawclBd2aPcuf:YhKdndnadTmbaqhiaxheadhmindndnaiIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:OhYxekcjjjj94hYkaYcCthYdndnaiclfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8Aka8AcqtaYVhYdndnaicwfIdbaKNJbbbZMgO:lJbbb9p9DTmbaO:Oh8Axekcjjjj94h8AkaeaYa8AVBdbaicxfhiaeclfheamcufgmmbkazcFeasz:tjjjbhEcbhDcbh3indndndnaEaxa3cdtgLfydbgYcm4aY7c:v;t;h;Ev2gics4ai7aAGgmcdtfg8AydbgecuSmbcehiinaxaecdtgefydbaYSmdamaifheaicefhiaEaeaAGgmcdtfg8Aydbgecu9hmbkka8Aa3BdbaDhiaDcefhDxeka5aefydbhika5aLfaiBdba3cefg3ad9hmbkcuaDc32giaDc;j:KM;jb0EhexekazcFeasz:tjjjb8AcbhDcbhekawaecbyd1:jjjbHjjjjbbgeBd3awcvBd2aecbaiz:tjjjbh8Aavcd4hxdnadTmbdnalTmbaxcdthEa5hYaqhealhmadhAina8AaYydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiamIdbaiIdxMUdxaiamclfIdbaiIdzMUdzaiamcwfIdbaiIdCMUdCaiaiIdKJbbjZMUdKaYclfhYaecxfheamaEfhmaAcufgAmbxdkka5hmaqheadhYina8Aamydbc32fgiaeIdbaiIdbMUdbaiaeclfIdbaiIdlMUdlaiaecwfIdbaiIdwMUdwaiaiIdxJbbbbMUdxaiaiIdzJbbbbMUdzaiaiIdCJbbbbMUdCaiaiIdKJbbjZMUdKamclfhmaecxfheaYcufgYmbkkdnaDTmba8AhiaDheinaiaiIdbJbbbbJbbjZaicKfIdbgO:vaOJbbbb9BEgONUdbaiclfgmaOamIdbNUdbaicwfgmaOamIdbNUdbaicxfgmaOamIdbNUdbaiczfgmaOamIdbNUdbaicCfgmaOamIdbNUdbaic3fhiaecufgembkkcbhYawcuaDcdtgLaDcFFFFi0Egicbyd1:jjjbHjjjjbbgeBdaawcoBd2awaicbyd1:jjjbHjjjjbbgEBd8KaecFeaLz:tjjjbh3dnadTmbJbbjZJbbjZaK:vaPceSEaoNgOaONhKaxcdthxalheinaKaec;81jjbalEgmIdwa8Aa5ydbgAc32fgiIdC:tgOaONamIdbaiIdx:tgOaONamIdlaiIdz:tgOaONMMNaqcwfIdbaiIdw:tgOaONaqIdbaiIdb:tgOaONaqclfIdbaiIdl:tgOaONMMMhOdndna3aAcdtgifgmydbcuSmbaEaifIdbaO9ETmekamaYBdbaEaifaOUdbka5clfh5aqcxfhqaeaxfheadaYcefgY9hmbkkaba3aLzMjjjb8AcrhikaicdthiinaiTmeaic98fgiawcxffydbcbyd:m:jjjbH:bjjjbbxbkkawc;Wbf8KjjjjbaDk:Ydidui99ducbhi8Jjjjjbca9Rglczfcwfcbyd11jjbBdbalcb8Pdj1jjb83izalcwfcbydN1jjbBdbalcb8Pd:m1jjb83ibdndnaembJbbjFhvJbbjFhoJbbjFhrxekadcd4cdthwincbhdinalczfadfgDabadfIdbgvaDIdbgoaoav9EEUdbaladfgDavaDIdbgoaoav9DEUdbadclfgdcx9hmbkabawfhbaicefgiae9hmbkalIdwalIdK:thralIdlalIdC:thoalIdbalIdz:thvkJbbbbavavJbbbb9DEgvaoaoav9DEgvararav9DEk9DeeuabcFeaicdtz:tjjjbhlcbhbdnadTmbindnalaeydbcdtfgiydbcu9hmbaiabBdbabcefhbkaeclfheadcufgdmbkkabk;7idqui998Jjjjjbc;Wb9Rgl8Kjjjjbalcxfcbc;Kbz:tjjjb8Aadcd4adfhvcehoinaogrcethoarav6mbkalcuarcdtgoarcFFFFi0Ecbyd1:jjjbHjjjjbbgvBdxavcFeaoz:tjjjbhwdnadTmbaicd4hDarcufhqcbhkindndnawcbaeakaD2cdtfgrydlgiaicjjjj94SEgocH4ao7c:F:b:DD2cbarydbgxaxcjjjj94SEgocH4ao7c;D;O:B8J27cbarydwgmamcjjjj94SEgrcH4ar7c:3F;N8N27aqGgvcdtfgrydbgocuSmbam::hPai::hsax::hzcehiinaihrdnaeaoaD2cdtfgiIdbaz9CmbaiIdlas9CmbaiIdwaP9BmikarcefhiawavarfaqGgvcdtfgrydbgocu9hmbkkarakBdbakhokabakcdtfaoBdbakcefgkad9hmbkkcbhrdninarc98Smealcxfarfydbcbyd:m:jjjbH:bjjjbbarc98fhrxbkkalc;Wbf8Kjjjjbk9teiucbcbyd:q:jjjbgeabcifc98GfgbBd:q:jjjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaik;teeeudndnaeabVciGTmbabhixekdndnadcz9pmbabhixekabhiinaiaeydbBdbaiaeydlBdlaiaeydwBdwaiaeydxBdxaeczfheaiczfhiadc9Wfgdcs0mbkkadcl6mbinaiaeydbBdbaeclfheaiclfhiadc98fgdci0mbkkdnadTmbinaiaeRbb86bbaicefhiaecefheadcufgdmbkkabk:3eedudndnabciGTmbabhixekaecFeGc:b:c:ew2hldndnadcz9pmbabhixekabhiinaialBdxaialBdwaialBdlaialBdbaiczfhiadc9Wfgdcs0mbkkadcl6mbinaialBdbaiclfhiadc98fgdci0mbkkdnadTmbinaiae86bbaicefhiadcufgdmbkkabk9teiucbcbyd:q:jjjbgeabcrfc94GfgbBd:q:jjjbdndnabZbcztgd9nmbcuhiabad9RcFFifcz4nbcuSmekaehikaikTeeucbabcbyd:q:jjjbge9Rcifc98GaefgbBd:q:jjjbdnabZbcztge9nmbabae9RcFFifcz4nb8Akkk:Iedbcjwk1eFFuuFFuuFFuuFFuFFFuFFFuFbbbbbbbbebbbdbbbbbbbebbbebbbdbbbbbbbbbbbeeeeebebbebbebebbbeebbbbbbbbbbbbeeeeeebebbeeebeebbbbebebbbbbbbbbbbbbbbbbbc1Dkxebbbdbbb:GNbb'; // embed! wasm var wasmpack = new Uint8Array([ 32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115, ]); if (typeof WebAssembly !== 'object') { return { supported: false, }; } var instance; var ready = WebAssembly.instantiate(unpack(wasm), {}).then(function (result) { instance = result.instance; instance.exports.__wasm_call_ctors(); }); function unpack(data) { var result = new Uint8Array(data.length); for (var i = 0; i < data.length; ++i) { var ch = data.charCodeAt(i); result[i] = ch > 96 ? ch - 97 : ch > 64 ? ch - 39 : ch + 4; } var write = 0; for (var i = 0; i < data.length; ++i) { result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i]; } return result.buffer.slice(0, write); } function assert(cond) { if (!cond) { throw new Error('Assertion failed'); } } function bytes(view) { return new Uint8Array(view.buffer, view.byteOffset, view.byteLength); } function genremap(fun, positions, vertices, stride) { var sbrk = instance.exports.sbrk; var rp = sbrk(vertices * 4); var sp = sbrk(vertices * stride * 4); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(positions), sp); fun(rp, sp, vertices, stride * 4); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var remap = new Uint32Array(vertices); new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4)); sbrk(rp - sbrk(0)); return remap; } function reorder(fun, indices, vertices) { var sbrk = instance.exports.sbrk; var ip = sbrk(indices.length * 4); var rp = sbrk(vertices * 4); var heap = new Uint8Array(instance.exports.memory.buffer); var indices8 = bytes(indices); heap.set(indices8, ip); var unique = fun(rp, ip, indices.length, vertices); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var remap = new Uint32Array(vertices); new Uint8Array(remap.buffer).set(heap.subarray(rp, rp + vertices * 4)); indices8.set(heap.subarray(ip, ip + indices.length * 4)); sbrk(ip - sbrk(0)); for (var i = 0; i < indices.length; ++i) indices[i] = remap[indices[i]]; return [remap, unique]; } function maxindex(source) { var result = 0; for (var i = 0; i < source.length; ++i) { var index = source[i]; result = result < index ? index : result; } return result; } function simplify(fun, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options) { var sbrk = instance.exports.sbrk; var te = sbrk(4); var ti = sbrk(index_count * 4); var sp = sbrk(vertex_count * vertex_positions_stride); var si = sbrk(index_count * 4); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); heap.set(bytes(indices), si); var result = fun(ti, si, index_count, sp, vertex_count, vertex_positions_stride, target_index_count, target_error, options, te); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var target = new Uint32Array(result); bytes(target).set(heap.subarray(ti, ti + result * 4)); var error = new Float32Array(1); bytes(error).set(heap.subarray(te, te + 4)); sbrk(te - sbrk(0)); return [target, error[0]]; } function simplifyAttr( fun, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, vertex_lock, target_index_count, target_error, options ) { var sbrk = instance.exports.sbrk; var te = sbrk(4); var ti = sbrk(index_count * 4); var sp = sbrk(vertex_count * vertex_positions_stride); var sa = sbrk(vertex_count * vertex_attributes_stride); var sw = sbrk(attribute_weights.length * 4); var si = sbrk(index_count * 4); var vl = vertex_lock ? sbrk(vertex_count) : 0; var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); heap.set(bytes(vertex_attributes), sa); heap.set(bytes(attribute_weights), sw); heap.set(bytes(indices), si); if (vertex_lock) { heap.set(bytes(vertex_lock), vl); } var result = fun( ti, si, index_count, sp, vertex_count, vertex_positions_stride, sa, vertex_attributes_stride, sw, attribute_weights.length, vl, target_index_count, target_error, options, te ); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var target = new Uint32Array(result); bytes(target).set(heap.subarray(ti, ti + result * 4)); var error = new Float32Array(1); bytes(error).set(heap.subarray(te, te + 4)); sbrk(te - sbrk(0)); return [target, error[0]]; } function simplifyUpdate( fun, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, vertex_lock, target_index_count, target_error, options ) { var sbrk = instance.exports.sbrk; var te = sbrk(4); var sp = sbrk(vertex_count * vertex_positions_stride); var sa = sbrk(vertex_count * vertex_attributes_stride); var sw = sbrk(attribute_weights.length * 4); var si = sbrk(index_count * 4); var vl = vertex_lock ? sbrk(vertex_count) : 0; var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); heap.set(bytes(vertex_attributes), sa); heap.set(bytes(attribute_weights), sw); heap.set(bytes(indices), si); if (vertex_lock) { heap.set(bytes(vertex_lock), vl); } var result = fun( si, index_count, sp, vertex_count, vertex_positions_stride, sa, vertex_attributes_stride, sw, attribute_weights.length, vl, target_index_count, target_error, options, te ); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); bytes(indices).set(heap.subarray(si, si + result * 4)); bytes(vertex_positions).set(heap.subarray(sp, sp + vertex_count * vertex_positions_stride)); bytes(vertex_attributes).set(heap.subarray(sa, sa + vertex_count * vertex_attributes_stride)); var error = new Float32Array(1); bytes(error).set(heap.subarray(te, te + 4)); sbrk(te - sbrk(0)); return [result, error[0]]; } function simplifyScale(fun, vertex_positions, vertex_count, vertex_positions_stride) { var sbrk = instance.exports.sbrk; var sp = sbrk(vertex_count * vertex_positions_stride); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); var result = fun(sp, vertex_count, vertex_positions_stride); sbrk(sp - sbrk(0)); return result; } function simplifyPoints( fun, vertex_positions, vertex_count, vertex_positions_stride, vertex_colors, vertex_colors_stride, color_weight, target_vertex_count ) { var sbrk = instance.exports.sbrk; var ti = sbrk(target_vertex_count * 4); var sp = sbrk(vertex_count * vertex_positions_stride); var sc = sbrk(vertex_count * vertex_colors_stride); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); if (vertex_colors) { heap.set(bytes(vertex_colors), sc); } var result = fun(ti, sp, vertex_count, vertex_positions_stride, sc, vertex_colors_stride, color_weight, target_vertex_count); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var target = new Uint32Array(result); bytes(target).set(heap.subarray(ti, ti + result * 4)); sbrk(ti - sbrk(0)); return target; } function simplifySloppy( fun, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_lock, target_index_count, target_error ) { var sbrk = instance.exports.sbrk; var te = sbrk(4); var ti = sbrk(index_count * 4); var sp = sbrk(vertex_count * vertex_positions_stride); var si = sbrk(index_count * 4); var vl = vertex_lock ? sbrk(vertex_count) : 0; var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); heap.set(bytes(indices), si); if (vertex_lock) { heap.set(bytes(vertex_lock), vl); } var result = fun(ti, si, index_count, sp, vertex_count, vertex_positions_stride, vl, target_index_count, target_error, te); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var target = new Uint32Array(result); bytes(target).set(heap.subarray(ti, ti + result * 4)); var error = new Float32Array(1); bytes(error).set(heap.subarray(te, te + 4)); sbrk(te - sbrk(0)); return [target, error[0]]; } function simplifyPrune(fun, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_error) { var sbrk = instance.exports.sbrk; var ti = sbrk(index_count * 4); var sp = sbrk(vertex_count * vertex_positions_stride); var si = sbrk(index_count * 4); var heap = new Uint8Array(instance.exports.memory.buffer); heap.set(bytes(vertex_positions), sp); heap.set(bytes(indices), si); var result = fun(ti, si, index_count, sp, vertex_count, vertex_positions_stride, target_error); // heap may have grown heap = new Uint8Array(instance.exports.memory.buffer); var target = new Uint32Array(result); bytes(target).set(heap.subarray(ti, ti + result * 4)); sbrk(ti - sbrk(0)); return target; } var simplifyOptions = { LockBorder: 1, Sparse: 2, ErrorAbsolute: 4, Prune: 8, Regularize: 16, Permissive: 32, _InternalDebug: 1 << 30, // internal, don't use! }; return { ready: ready, supported: true, compactMesh: function (indices) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); return reorder(instance.exports.meshopt_optimizeVertexFetchRemap, indices32, maxindex(indices) + 1); }, generatePositionRemap: function (vertex_positions, vertex_positions_stride) { assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); return genremap( instance.exports.meshopt_generatePositionRemap, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride ); }, simplify: function (indices, vertex_positions, vertex_positions_stride, target_index_count, target_error, flags) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(target_index_count >= 0 && target_index_count <= indices.length); assert(target_index_count % 3 == 0); assert(target_error >= 0); var options = 0; for (var i = 0; i < (flags ? flags.length : 0); ++i) { assert(flags[i] in simplifyOptions); options |= simplifyOptions[flags[i]]; } var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); var result = simplify( instance.exports.meshopt_simplify, indices32, indices.length, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, target_index_count, target_error, options ); result[0] = indices instanceof Uint32Array ? result[0] : new indices.constructor(result[0]); return result; }, simplifyWithAttributes: function ( indices, vertex_positions, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, vertex_lock, target_index_count, target_error, flags ) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(vertex_attributes instanceof Float32Array); assert(vertex_attributes.length == vertex_attributes_stride * (vertex_positions.length / vertex_positions_stride)); assert(vertex_attributes_stride >= 0); assert(vertex_lock == null || vertex_lock instanceof Uint8Array); assert(vertex_lock == null || vertex_lock.length == vertex_positions.length / vertex_positions_stride); assert(target_index_count >= 0 && target_index_count <= indices.length); assert(target_index_count % 3 == 0); assert(target_error >= 0); assert(Array.isArray(attribute_weights)); assert(vertex_attributes_stride >= attribute_weights.length); assert(attribute_weights.length <= 32); for (var i = 0; i < attribute_weights.length; ++i) { assert(attribute_weights[i] >= 0); } var options = 0; for (var i = 0; i < (flags ? flags.length : 0); ++i) { assert(flags[i] in simplifyOptions); options |= simplifyOptions[flags[i]]; } var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); var result = simplifyAttr( instance.exports.meshopt_simplifyWithAttributes, indices32, indices.length, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, vertex_attributes, vertex_attributes_stride * 4, new Float32Array(attribute_weights), vertex_lock, target_index_count, target_error, options ); result[0] = indices instanceof Uint32Array ? result[0] : new indices.constructor(result[0]); return result; }, simplifyWithUpdate: function ( indices, vertex_positions, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, vertex_lock, target_index_count, target_error, flags ) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(vertex_attributes instanceof Float32Array); assert(vertex_attributes.length == vertex_attributes_stride * (vertex_positions.length / vertex_positions_stride)); assert(vertex_attributes_stride >= 0); assert(vertex_lock == null || vertex_lock instanceof Uint8Array); assert(vertex_lock == null || vertex_lock.length == vertex_positions.length / vertex_positions_stride); assert(target_index_count >= 0 && target_index_count <= indices.length); assert(target_index_count % 3 == 0); assert(target_error >= 0); assert(Array.isArray(attribute_weights)); assert(vertex_attributes_stride >= attribute_weights.length); assert(attribute_weights.length <= 32); for (var i = 0; i < attribute_weights.length; ++i) { assert(attribute_weights[i] >= 0); } var options = 0; for (var i = 0; i < (flags ? flags.length : 0); ++i) { assert(flags[i] in simplifyOptions); options |= simplifyOptions[flags[i]]; } var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); var result = simplifyUpdate( instance.exports.meshopt_simplifyWithUpdate, indices32, indices.length, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, vertex_attributes, vertex_attributes_stride * 4, new Float32Array(attribute_weights), vertex_lock, target_index_count, target_error, options ); if (indices !== indices32) { // copy back indices if they were converted to Uint32Array for (var i = 0; i < result[0]; ++i) { indices[i] = indices32[i]; } } return result; }, getScale: function (vertex_positions, vertex_positions_stride) { assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); return simplifyScale( instance.exports.meshopt_simplifyScale, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4 ); }, simplifyPoints: function (vertex_positions, vertex_positions_stride, target_vertex_count, vertex_colors, vertex_colors_stride, color_weight) { assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(target_vertex_count >= 0 && target_vertex_count <= vertex_positions.length / vertex_positions_stride); if (vertex_colors) { assert(vertex_colors instanceof Float32Array); assert(vertex_colors.length % vertex_colors_stride == 0); assert(vertex_colors_stride >= 3); assert(vertex_positions.length / vertex_positions_stride == vertex_colors.length / vertex_colors_stride); return simplifyPoints( instance.exports.meshopt_simplifyPoints, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, vertex_colors, vertex_colors_stride * 4, color_weight, target_vertex_count ); } else { return simplifyPoints( instance.exports.meshopt_simplifyPoints, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, undefined, 0, 0, target_vertex_count ); } }, simplifySloppy: function (indices, vertex_positions, vertex_positions_stride, vertex_lock, target_index_count, target_error) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(vertex_lock == null || vertex_lock instanceof Uint8Array); assert(vertex_lock == null || vertex_lock.length == vertex_positions.length / vertex_positions_stride); assert(target_index_count >= 0 && target_index_count <= indices.length); assert(target_index_count % 3 == 0); assert(target_error >= 0); var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); var result = simplifySloppy( instance.exports.meshopt_simplifySloppy, indices32, indices.length, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, vertex_lock, target_index_count, target_error ); result[0] = indices instanceof Uint32Array ? result[0] : new indices.constructor(result[0]); return result; }, simplifyPrune: function (indices, vertex_positions, vertex_positions_stride, target_error) { assert( indices instanceof Uint32Array || indices instanceof Int32Array || indices instanceof Uint16Array || indices instanceof Int16Array ); assert(indices.length % 3 == 0); assert(vertex_positions instanceof Float32Array); assert(vertex_positions.length % vertex_positions_stride == 0); assert(vertex_positions_stride >= 3); assert(target_error >= 0); var indices32 = indices.BYTES_PER_ELEMENT == 4 ? indices : new Uint32Array(indices); var result = simplifyPrune( instance.exports.meshopt_simplifyPrune, indices32, indices.length, vertex_positions, vertex_positions.length / vertex_positions_stride, vertex_positions_stride * 4, target_error ); result = indices instanceof Uint32Array ? result : new indices.constructor(result); return result; }, }; })(); export { MeshoptSimplifier };
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
js/meshopt_simplifier.test.js
JavaScript
import assert from 'assert/strict'; import { MeshoptSimplifier as simplifier } from './meshopt_simplifier.js'; process.on('unhandledRejection', (error) => { console.log('unhandledRejection', error); process.exit(1); }); var tests = { compactMesh: function () { var indices = new Uint32Array([0, 1, 3, 3, 1, 5]); var expected = new Uint32Array([0, 1, 2, 2, 1, 3]); var missing = 2 ** 32 - 1; var remap = new Uint32Array([0, 1, missing, 2, missing, 3]); var res = simplifier.compactMesh(indices); assert.deepEqual(indices, expected); assert.deepEqual(res[0], remap); assert.equal(res[1], 4); // unique }, simplify: function () { // 0 // 1 2 // 3 4 5 var indices = new Uint32Array([0, 2, 1, 1, 2, 3, 3, 2, 4, 2, 5, 4]); var positions = new Float32Array([0, 4, 0, 0, 1, 0, 2, 2, 0, 0, 0, 0, 1, 0, 0, 4, 0, 0]); var res = simplifier.simplify(indices, positions, 3, /* target indices */ 3, /* target error */ 0.01); var expected = new Uint32Array([0, 5, 3]); assert.deepEqual(res[0], expected); assert(res[1] < 1e-4); // error }, simplify16: function () { // 0 // 1 2 // 3 4 5 var indices = new Uint16Array([0, 2, 1, 1, 2, 3, 3, 2, 4, 2, 5, 4]); var positions = new Float32Array([0, 4, 0, 0, 1, 0, 2, 2, 0, 0, 0, 0, 1, 0, 0, 4, 0, 0]); var res = simplifier.simplify(indices, positions, 3, /* target indices */ 3, /* target error */ 0.01); var expected = new Uint16Array([0, 5, 3]); assert.deepEqual(res[0], expected); assert(res[1] < 1e-4); // error }, simplifyLockBorder: function () { // 0 // 1 2 // 3 4 5 var indices = new Uint32Array([0, 2, 1, 1, 2, 3, 3, 2, 4, 2, 5, 4]); var positions = new Float32Array([0, 2, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0]); var res = simplifier.simplify(indices, positions, 3, /* target indices */ 3, /* target error */ 0.01, ['LockBorder']); var expected = new Uint32Array([0, 2, 1, 1, 2, 3, 3, 2, 4, 2, 5, 4]); assert.deepEqual(res[0], expected); assert(res[1] < 1e-4); // error }, simplifyAttr: function () { var vb_pos = new Float32Array(8 * 3 * 3); var vb_att = new Float32Array(8 * 3 * 3); for (var y = 0; y < 8; ++y) { // first four rows are a blue gradient, next four rows are a yellow gradient var r = y < 4 ? 0.8 + y * 0.05 : 0; var g = y < 4 ? 0.8 + y * 0.05 : 0; var b = y < 4 ? 0 : 0.8 + (7 - y) * 0.05; for (var x = 0; x < 3; ++x) { vb_pos[(y * 3 + x) * 3 + 0] = x; vb_pos[(y * 3 + x) * 3 + 1] = y; vb_pos[(y * 3 + x) * 3 + 2] = 0.03 * x + 0.028 * (y % 2) + (x == 2 && y == 7 ? 1 : 0) * 0.03; vb_att[(y * 3 + x) * 3 + 0] = r; vb_att[(y * 3 + x) * 3 + 1] = g; vb_att[(y * 3 + x) * 3 + 2] = b; } } var ib = new Uint32Array(7 * 2 * 6); for (var y = 0; y < 7; ++y) { for (var x = 0; x < 2; ++x) { ib[(y * 2 + x) * 6 + 0] = (y + 0) * 3 + (x + 0); ib[(y * 2 + x) * 6 + 1] = (y + 0) * 3 + (x + 1); ib[(y * 2 + x) * 6 + 2] = (y + 1) * 3 + (x + 0); ib[(y * 2 + x) * 6 + 3] = (y + 1) * 3 + (x + 0); ib[(y * 2 + x) * 6 + 4] = (y + 0) * 3 + (x + 1); ib[(y * 2 + x) * 6 + 5] = (y + 1) * 3 + (x + 1); } } var attr_weights = [0.5, 0.5, 0.5]; var res = simplifier.simplifyWithAttributes(ib, vb_pos, 3, vb_att, 3, attr_weights, null, 6 * 3, 1e-2); var expected = new Uint32Array([0, 2, 11, 0, 11, 9, 9, 11, 12, 12, 11, 14, 12, 14, 23, 12, 23, 21]); assert.deepEqual(res[0], expected); }, simplifyUpdate: function () { var indices = new Uint32Array([0, 1, 3, 3, 1, 4, 4, 1, 2, 0, 3, 2, 3, 4, 2]); var positions = new Float32Array([0, 0, 0, 1, 1, 0, 2, 0, 0, 0.9, 0.2, 0.1, 1.1, 0.2, 0.1]); var attributes = new Float32Array([0, 0, 0, 0.2, 0.1]); var res = simplifier.simplifyWithUpdate(indices, positions, 3, attributes, 1, [1], null, 9, 1); var expected = new Uint32Array([0, 1, 3, 3, 1, 2, 0, 3, 2]); assert.equal(res[0], expected.length); assert.deepEqual(indices.subarray(0, expected.length), expected); // border vertices haven't moved but may have small floating point drift for (var i = 0; i < 3; ++i) { assert(Math.abs(attributes[i]) < 1e-6); } // center vertex got updated assert(Math.abs(positions[3 * 3 + 0] - 0.88) < 1e-2); assert(Math.abs(positions[3 * 3 + 1] - 0.19) < 1e-2); assert(Math.abs(positions[3 * 3 + 2] - 0.11) < 1e-2); assert(Math.abs(attributes[3] - 0.18) < 1e-2); }, simplifyLockFlags: function () { // 0 // 1 2 // 3 4 5 var indices = new Uint32Array([0, 2, 1, 1, 2, 3, 3, 2, 4, 2, 5, 4]); var positions = new Float32Array([0, 2, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0]); var locks = new Uint8Array([1, 1, 1, 1, 0, 1]); // only vertex 4 can move var res = simplifier.simplifyWithAttributes(indices, positions, 3, new Float32Array(), 0, [], locks, 3, 0.01); var expected = new Uint32Array([0, 2, 1, 1, 2, 3, 2, 5, 3]); assert.deepEqual(res[0], expected); assert(res[1] < 1e-4); // error }, getScale: function () { var positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3]); assert(simplifier.getScale(positions, 3) == 3.0); }, simplifyPoints: function () { var positions = new Float32Array([0, 0, 0, 100, 0, 0, 100, 1, 1, 110, 0, 0]); var colors = new Float32Array([1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]); var expected = new Uint32Array([0, 1]); var expectedC = new Uint32Array([0, 2]); var res = simplifier.simplifyPoints(positions, 3, 2); assert.deepEqual(res, expected); // note: recommended value for color_weight is 1e-2 but here we push color weight to be very high to bias candidate selection for testing var resC1 = simplifier.simplifyPoints(positions, 3, 2, colors, 3, 1e-1); assert.deepEqual(resC1, expectedC); var resC2 = simplifier.simplifyPoints(positions, 3, 2, colors, 3, 1e-2); assert.deepEqual(resC2, expected); }, simplifyPrune: function () { var indices = new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 8]); var positions = new Float32Array([0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 2, 1, 2, 0, 1, 0, 0, 2, 0, 4, 2, 4, 0, 2]); var expected = new Uint32Array([6, 7, 8]); var res = simplifier.simplifyPrune(indices, positions, 3, 0.5); assert.deepEqual(res, expected); }, }; Promise.all([simplifier.ready]).then(() => { var count = 0; for (var key in tests) { tests[key](); count++; } console.log(count, 'tests passed'); });
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
js/wasi_trace.js
JavaScript
// Usage: // 1. import { wasi_trace } from './wasi_trace.js'; // 2. Pass wasi_trace as an import object to WebAssembly.instantiate // 3. Call wasi_trace.init(instance) after instantiation var instance; var wasi_snapshot_preview1 = { fd_close: function () { return 8; }, fd_seek: function () { return 8; }, fd_fdstat_get: function (fd, stat) { // needed for isatty() to enable line buffering for stdout var heap = new DataView(instance.exports.memory.buffer); heap.setUint8(stat, 2); for (var i = 1; i < 24; ++i) heap.setUint8(stat + i, 0); return 0; }, fd_write: function (fd, iovs, iovs_len, nwritten) { var heap = new DataView(instance.exports.memory.buffer); var written = 0; var str = ''; for (var i = 0; i < iovs_len; ++i) { var buf = heap.getUint32(iovs + 8 * i + 0, true); var buf_len = heap.getUint32(iovs + 8 * i + 4, true); var buf_data = new Uint8Array(heap.buffer, buf, buf_len); for (var j = 0; j < buf_data.length; ++j) { str += String.fromCharCode(buf_data[j]); } written += buf_len; } console.log(str); heap.setUint32(nwritten, written, true); return 0; }, }; var wasi_trace = { wasi_snapshot_preview1, init: function (inst) { instance = inst; }, }; export { wasi_trace };
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/allocator.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #ifdef MESHOPTIMIZER_ALLOC_EXPORT meshopt_Allocator::Storage& meshopt_Allocator::storage() { static Storage s = {::operator new, ::operator delete }; return s; } #endif void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*)) { meshopt_Allocator::Storage& s = meshopt_Allocator::storage(); s.allocate = allocate; s.deallocate = deallocate; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/clusterizer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <math.h> #include <string.h> // The block below auto-detects SIMD ISA that can be used on the target platform #ifndef MESHOPTIMIZER_NO_SIMD #if defined(__SSE2__) || (defined(_MSC_VER) && defined(_M_X64)) #define SIMD_SSE #include <emmintrin.h> #elif defined(__aarch64__) || (defined(_MSC_VER) && defined(_M_ARM64) && _MSC_VER >= 1922) #define SIMD_NEON #include <arm_neon.h> #endif #endif // !MESHOPTIMIZER_NO_SIMD // This work is based on: // Graham Wihlidal. Optimizing the Graphics Pipeline with Compute. 2016 // Matthaeus Chajdas. GeometryFX 1.2 - Cluster Culling. 2016 // Jack Ritter. An Efficient Bounding Sphere. 1990 // Thomas Larsson. Fast and Tight Fitting Bounding Spheres. 2008 // Ingo Wald, Vlastimil Havran. On building fast kd-Trees for Ray Tracing, and on doing that in O(N log N). 2006 namespace meshopt { // This must be <= 256 since meshlet indices are stored as bytes const size_t kMeshletMaxVertices = 256; // A reasonable limit is around 2*max_vertices or less const size_t kMeshletMaxTriangles = 512; // We keep a limited number of seed triangles and add a few triangles per finished meshlet const size_t kMeshletMaxSeeds = 256; const size_t kMeshletAddSeeds = 4; // To avoid excessive recursion for malformed inputs, we limit the maximum depth of the tree const int kMeshletMaxTreeDepth = 50; struct TriangleAdjacency2 { unsigned int* counts; unsigned int* offsets; unsigned int* data; }; static void buildTriangleAdjacency(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator) { size_t face_count = index_count / 3; // allocate arrays adjacency.counts = allocator.allocate<unsigned int>(vertex_count); adjacency.offsets = allocator.allocate<unsigned int>(vertex_count); adjacency.data = allocator.allocate<unsigned int>(index_count); // fill triangle counts memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int)); for (size_t i = 0; i < index_count; ++i) { assert(indices[i] < vertex_count); adjacency.counts[indices[i]]++; } // fill offset table unsigned int offset = 0; for (size_t i = 0; i < vertex_count; ++i) { adjacency.offsets[i] = offset; offset += adjacency.counts[i]; } assert(offset == index_count); // fill triangle data for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; adjacency.data[adjacency.offsets[a]++] = unsigned(i); adjacency.data[adjacency.offsets[b]++] = unsigned(i); adjacency.data[adjacency.offsets[c]++] = unsigned(i); } // fix offsets that have been disturbed by the previous pass for (size_t i = 0; i < vertex_count; ++i) { assert(adjacency.offsets[i] >= adjacency.counts[i]); adjacency.offsets[i] -= adjacency.counts[i]; } } static void buildTriangleAdjacencySparse(TriangleAdjacency2& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator) { size_t face_count = index_count / 3; // sparse mode can build adjacency more quickly by ignoring unused vertices, using a bit to mark visited vertices const unsigned int sparse_seen = 1u << 31; assert(index_count < sparse_seen); // allocate arrays adjacency.counts = allocator.allocate<unsigned int>(vertex_count); adjacency.offsets = allocator.allocate<unsigned int>(vertex_count); adjacency.data = allocator.allocate<unsigned int>(index_count); // fill triangle counts for (size_t i = 0; i < index_count; ++i) assert(indices[i] < vertex_count); for (size_t i = 0; i < index_count; ++i) adjacency.counts[indices[i]] = 0; for (size_t i = 0; i < index_count; ++i) adjacency.counts[indices[i]]++; // fill offset table; uses sparse_seen bit to tag visited vertices unsigned int offset = 0; for (size_t i = 0; i < index_count; ++i) { unsigned int v = indices[i]; if ((adjacency.counts[v] & sparse_seen) == 0) { adjacency.offsets[v] = offset; offset += adjacency.counts[v]; adjacency.counts[v] |= sparse_seen; } } assert(offset == index_count); // fill triangle data for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; adjacency.data[adjacency.offsets[a]++] = unsigned(i); adjacency.data[adjacency.offsets[b]++] = unsigned(i); adjacency.data[adjacency.offsets[c]++] = unsigned(i); } // fix offsets that have been disturbed by the previous pass // also fix counts (that were marked with sparse_seen by the first pass) for (size_t i = 0; i < index_count; ++i) { unsigned int v = indices[i]; if (adjacency.counts[v] & sparse_seen) { adjacency.counts[v] &= ~sparse_seen; assert(adjacency.offsets[v] >= adjacency.counts[v]); adjacency.offsets[v] -= adjacency.counts[v]; } } } static void clearUsed(short* used, size_t vertex_count, const unsigned int* indices, size_t index_count) { // for sparse inputs, it's faster to only clear vertices referenced by the index buffer if (vertex_count <= index_count) memset(used, -1, vertex_count * sizeof(short)); else for (size_t i = 0; i < index_count; ++i) { assert(indices[i] < vertex_count); used[indices[i]] = -1; } } static void computeBoundingSphere(float result[4], const float* points, size_t count, size_t points_stride, const float* radii, size_t radii_stride, size_t axis_count) { static const float kAxes[7][3] = { // X, Y, Z {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, // XYZ, -XYZ, X-YZ, XY-Z; normalized to unit length {0.57735026f, 0.57735026f, 0.57735026f}, {-0.57735026f, 0.57735026f, 0.57735026f}, {0.57735026f, -0.57735026f, 0.57735026f}, {0.57735026f, 0.57735026f, -0.57735026f}, }; assert(count > 0); assert(axis_count <= sizeof(kAxes) / sizeof(kAxes[0])); size_t points_stride_float = points_stride / sizeof(float); size_t radii_stride_float = radii_stride / sizeof(float); // find extremum points along all axes; for each axis we get a pair of points with min/max coordinates size_t pmin[7], pmax[7]; float tmin[7], tmax[7]; for (size_t axis = 0; axis < axis_count; ++axis) { pmin[axis] = pmax[axis] = 0; tmin[axis] = FLT_MAX; tmax[axis] = -FLT_MAX; } for (size_t i = 0; i < count; ++i) { const float* p = points + i * points_stride_float; float r = radii[i * radii_stride_float]; for (size_t axis = 0; axis < axis_count; ++axis) { const float* ax = kAxes[axis]; float tp = ax[0] * p[0] + ax[1] * p[1] + ax[2] * p[2]; float tpmin = tp - r, tpmax = tp + r; pmin[axis] = (tpmin < tmin[axis]) ? i : pmin[axis]; pmax[axis] = (tpmax > tmax[axis]) ? i : pmax[axis]; tmin[axis] = (tpmin < tmin[axis]) ? tpmin : tmin[axis]; tmax[axis] = (tpmax > tmax[axis]) ? tpmax : tmax[axis]; } } // find the pair of points with largest distance size_t paxis = 0; float paxisdr = 0; for (size_t axis = 0; axis < axis_count; ++axis) { const float* p1 = points + pmin[axis] * points_stride_float; const float* p2 = points + pmax[axis] * points_stride_float; float r1 = radii[pmin[axis] * radii_stride_float]; float r2 = radii[pmax[axis] * radii_stride_float]; float d2 = (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2]); float dr = sqrtf(d2) + r1 + r2; if (dr > paxisdr) { paxisdr = dr; paxis = axis; } } // use the longest segment as the initial sphere diameter const float* p1 = points + pmin[paxis] * points_stride_float; const float* p2 = points + pmax[paxis] * points_stride_float; float r1 = radii[pmin[paxis] * radii_stride_float]; float r2 = radii[pmax[paxis] * radii_stride_float]; float paxisd = sqrtf((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]) + (p2[2] - p1[2]) * (p2[2] - p1[2])); float paxisk = paxisd > 0 ? (paxisd + r2 - r1) / (2 * paxisd) : 0.f; float center[3] = {p1[0] + (p2[0] - p1[0]) * paxisk, p1[1] + (p2[1] - p1[1]) * paxisk, p1[2] + (p2[2] - p1[2]) * paxisk}; float radius = paxisdr / 2; // iteratively adjust the sphere up until all points fit for (size_t i = 0; i < count; ++i) { const float* p = points + i * points_stride_float; float r = radii[i * radii_stride_float]; float d2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]) + (p[2] - center[2]) * (p[2] - center[2]); float d = sqrtf(d2); if (d + r > radius) { float k = d > 0 ? (d + r - radius) / (2 * d) : 0.f; center[0] += k * (p[0] - center[0]); center[1] += k * (p[1] - center[1]); center[2] += k * (p[2] - center[2]); radius = (radius + d + r) / 2; } } result[0] = center[0]; result[1] = center[1]; result[2] = center[2]; result[3] = radius; } struct Cone { float px, py, pz; float nx, ny, nz; }; static float getMeshletScore(float distance, float spread, float cone_weight, float expected_radius) { float cone = 1.f - spread * cone_weight; float cone_clamped = cone < 1e-3f ? 1e-3f : cone; return (1 + distance / expected_radius * (1 - cone_weight)) * cone_clamped; } static Cone getMeshletCone(const Cone& acc, unsigned int triangle_count) { Cone result = acc; float center_scale = triangle_count == 0 ? 0.f : 1.f / float(triangle_count); result.px *= center_scale; result.py *= center_scale; result.pz *= center_scale; float axis_length = result.nx * result.nx + result.ny * result.ny + result.nz * result.nz; float axis_scale = axis_length == 0.f ? 0.f : 1.f / sqrtf(axis_length); result.nx *= axis_scale; result.ny *= axis_scale; result.nz *= axis_scale; return result; } static float computeTriangleCones(Cone* triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { (void)vertex_count; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); size_t face_count = index_count / 3; float mesh_area = 0; for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); const float* p0 = vertex_positions + vertex_stride_float * a; const float* p1 = vertex_positions + vertex_stride_float * b; const float* p2 = vertex_positions + vertex_stride_float * c; float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]}; float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]}; float normalx = p10[1] * p20[2] - p10[2] * p20[1]; float normaly = p10[2] * p20[0] - p10[0] * p20[2]; float normalz = p10[0] * p20[1] - p10[1] * p20[0]; float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz); float invarea = (area == 0.f) ? 0.f : 1.f / area; triangles[i].px = (p0[0] + p1[0] + p2[0]) / 3.f; triangles[i].py = (p0[1] + p1[1] + p2[1]) / 3.f; triangles[i].pz = (p0[2] + p1[2] + p2[2]) / 3.f; triangles[i].nx = normalx * invarea; triangles[i].ny = normaly * invarea; triangles[i].nz = normalz * invarea; mesh_area += area; } return mesh_area; } static bool appendMeshlet(meshopt_Meshlet& meshlet, unsigned int a, unsigned int b, unsigned int c, short* used, meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t meshlet_offset, size_t max_vertices, size_t max_triangles, bool split = false) { short& av = used[a]; short& bv = used[b]; short& cv = used[c]; bool result = false; int used_extra = (av < 0) + (bv < 0) + (cv < 0); if (meshlet.vertex_count + used_extra > max_vertices || meshlet.triangle_count >= max_triangles || split) { meshlets[meshlet_offset] = meshlet; for (size_t j = 0; j < meshlet.vertex_count; ++j) used[meshlet_vertices[meshlet.vertex_offset + j]] = -1; meshlet.vertex_offset += meshlet.vertex_count; meshlet.triangle_offset += meshlet.triangle_count * 3; meshlet.vertex_count = 0; meshlet.triangle_count = 0; result = true; } if (av < 0) { av = short(meshlet.vertex_count); meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = a; } if (bv < 0) { bv = short(meshlet.vertex_count); meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = b; } if (cv < 0) { cv = short(meshlet.vertex_count); meshlet_vertices[meshlet.vertex_offset + meshlet.vertex_count++] = c; } meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 0] = (unsigned char)av; meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 1] = (unsigned char)bv; meshlet_triangles[meshlet.triangle_offset + meshlet.triangle_count * 3 + 2] = (unsigned char)cv; meshlet.triangle_count++; return result; } static unsigned int getNeighborTriangle(const meshopt_Meshlet& meshlet, const Cone& meshlet_cone, const unsigned int* meshlet_vertices, const unsigned int* indices, const TriangleAdjacency2& adjacency, const Cone* triangles, const unsigned int* live_triangles, const short* used, float meshlet_expected_radius, float cone_weight) { unsigned int best_triangle = ~0u; int best_priority = 5; float best_score = FLT_MAX; for (size_t i = 0; i < meshlet.vertex_count; ++i) { unsigned int index = meshlet_vertices[meshlet.vertex_offset + i]; unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index]; size_t neighbors_size = adjacency.counts[index]; for (size_t j = 0; j < neighbors_size; ++j) { unsigned int triangle = neighbors[j]; unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2]; int extra = (used[a] < 0) + (used[b] < 0) + (used[c] < 0); assert(extra <= 2); int priority = -1; // triangles that don't add new vertices to meshlets are max. priority if (extra == 0) priority = 0; // artificially increase the priority of dangling triangles as they're expensive to add to new meshlets else if (live_triangles[a] == 1 || live_triangles[b] == 1 || live_triangles[c] == 1) priority = 1; // if two vertices have live count of 2, removing this triangle will make another triangle dangling which is good for overall flow else if ((live_triangles[a] == 2) + (live_triangles[b] == 2) + (live_triangles[c] == 2) >= 2) priority = 1 + extra; // otherwise adjust priority to be after the above cases, 3 or 4 based on used[] count else priority = 2 + extra; // since topology-based priority is always more important than the score, we can skip scoring in some cases if (priority > best_priority) continue; const Cone& tri_cone = triangles[triangle]; float dx = tri_cone.px - meshlet_cone.px, dy = tri_cone.py - meshlet_cone.py, dz = tri_cone.pz - meshlet_cone.pz; float distance = sqrtf(dx * dx + dy * dy + dz * dz); float spread = tri_cone.nx * meshlet_cone.nx + tri_cone.ny * meshlet_cone.ny + tri_cone.nz * meshlet_cone.nz; float score = getMeshletScore(distance, spread, cone_weight, meshlet_expected_radius); // note that topology-based priority is always more important than the score // this helps maintain reasonable effectiveness of meshlet data and reduces scoring cost if (priority < best_priority || score < best_score) { best_triangle = triangle; best_priority = priority; best_score = score; } } } return best_triangle; } static size_t appendSeedTriangles(unsigned int* seeds, const meshopt_Meshlet& meshlet, const unsigned int* meshlet_vertices, const unsigned int* indices, const TriangleAdjacency2& adjacency, const Cone* triangles, const unsigned int* live_triangles, float cornerx, float cornery, float cornerz) { unsigned int best_seeds[kMeshletAddSeeds]; unsigned int best_live[kMeshletAddSeeds]; float best_score[kMeshletAddSeeds]; for (size_t i = 0; i < kMeshletAddSeeds; ++i) { best_seeds[i] = ~0u; best_live[i] = ~0u; best_score[i] = FLT_MAX; } for (size_t i = 0; i < meshlet.vertex_count; ++i) { unsigned int index = meshlet_vertices[meshlet.vertex_offset + i]; unsigned int best_neighbor = ~0u; unsigned int best_neighbor_live = ~0u; // find the neighbor with the smallest live metric unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index]; size_t neighbors_size = adjacency.counts[index]; for (size_t j = 0; j < neighbors_size; ++j) { unsigned int triangle = neighbors[j]; unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2]; unsigned int live = live_triangles[a] + live_triangles[b] + live_triangles[c]; if (live < best_neighbor_live) { best_neighbor = triangle; best_neighbor_live = live; } } // add the neighbor to the list of seeds; the list is unsorted and the replacement criteria is approximate if (best_neighbor == ~0u) continue; float dx = triangles[best_neighbor].px - cornerx, dy = triangles[best_neighbor].py - cornery, dz = triangles[best_neighbor].pz - cornerz; float best_neighbor_score = sqrtf(dx * dx + dy * dy + dz * dz); for (size_t j = 0; j < kMeshletAddSeeds; ++j) { // non-strict comparison reduces the number of duplicate seeds (triangles adjacent to multiple vertices) if (best_neighbor_live < best_live[j] || (best_neighbor_live == best_live[j] && best_neighbor_score <= best_score[j])) { best_seeds[j] = best_neighbor; best_live[j] = best_neighbor_live; best_score[j] = best_neighbor_score; break; } } } // add surviving seeds to the meshlet size_t seed_count = 0; for (size_t i = 0; i < kMeshletAddSeeds; ++i) if (best_seeds[i] != ~0u) seeds[seed_count++] = best_seeds[i]; return seed_count; } static size_t pruneSeedTriangles(unsigned int* seeds, size_t seed_count, const unsigned char* emitted_flags) { size_t result = 0; for (size_t i = 0; i < seed_count; ++i) { unsigned int index = seeds[i]; seeds[result] = index; result += emitted_flags[index] == 0; } return result; } static unsigned int selectSeedTriangle(const unsigned int* seeds, size_t seed_count, const unsigned int* indices, const Cone* triangles, const unsigned int* live_triangles, float cornerx, float cornery, float cornerz) { unsigned int best_seed = ~0u; unsigned int best_live = ~0u; float best_score = FLT_MAX; for (size_t i = 0; i < seed_count; ++i) { unsigned int index = seeds[i]; unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2]; unsigned int live = live_triangles[a] + live_triangles[b] + live_triangles[c]; float dx = triangles[index].px - cornerx, dy = triangles[index].py - cornery, dz = triangles[index].pz - cornerz; float score = sqrtf(dx * dx + dy * dy + dz * dz); if (live < best_live || (live == best_live && score < best_score)) { best_seed = index; best_live = live; best_score = score; } } return best_seed; } struct KDNode { union { float split; unsigned int index; }; // leaves: axis = 3, children = number of points including this one // branches: axis != 3, left subtree = skip 1, right subtree = skip 1+children unsigned int axis : 2; unsigned int children : 30; }; static size_t kdtreePartition(unsigned int* indices, size_t count, const float* points, size_t stride, int axis, float pivot) { size_t m = 0; // invariant: elements in range [0, m) are < pivot, elements in range [m, i) are >= pivot for (size_t i = 0; i < count; ++i) { float v = points[indices[i] * stride + axis]; // swap(m, i) unconditionally unsigned int t = indices[m]; indices[m] = indices[i]; indices[i] = t; // when v >= pivot, we swap i with m without advancing it, preserving invariants m += v < pivot; } return m; } static size_t kdtreeBuildLeaf(size_t offset, KDNode* nodes, size_t node_count, unsigned int* indices, size_t count) { assert(offset + count <= node_count); (void)node_count; KDNode& result = nodes[offset]; result.index = indices[0]; result.axis = 3; result.children = unsigned(count); // all remaining points are stored in nodes immediately following the leaf for (size_t i = 1; i < count; ++i) { KDNode& tail = nodes[offset + i]; tail.index = indices[i]; tail.axis = 3; tail.children = ~0u >> 2; // bogus value to prevent misuse } return offset + count; } static size_t kdtreeBuild(size_t offset, KDNode* nodes, size_t node_count, const float* points, size_t stride, unsigned int* indices, size_t count, size_t leaf_size, int depth) { assert(count > 0); assert(offset < node_count); if (count <= leaf_size) return kdtreeBuildLeaf(offset, nodes, node_count, indices, count); float mean[3] = {}; float vars[3] = {}; float runc = 1, runs = 1; // gather statistics on the points in the subtree using Welford's algorithm for (size_t i = 0; i < count; ++i, runc += 1.f, runs = 1.f / runc) { const float* point = points + indices[i] * stride; for (int k = 0; k < 3; ++k) { float delta = point[k] - mean[k]; mean[k] += delta * runs; vars[k] += delta * (point[k] - mean[k]); } } // split axis is one where the variance is largest int axis = (vars[0] >= vars[1] && vars[0] >= vars[2]) ? 0 : (vars[1] >= vars[2] ? 1 : 2); float split = mean[axis]; size_t middle = kdtreePartition(indices, count, points, stride, axis, split); // when the partition is degenerate simply consolidate the points into a single node // this also ensures recursion depth is bounded on pathological inputs if (middle <= leaf_size / 2 || middle >= count - leaf_size / 2 || depth >= kMeshletMaxTreeDepth) return kdtreeBuildLeaf(offset, nodes, node_count, indices, count); KDNode& result = nodes[offset]; result.split = split; result.axis = axis; // left subtree is right after our node size_t next_offset = kdtreeBuild(offset + 1, nodes, node_count, points, stride, indices, middle, leaf_size, depth + 1); // distance to the right subtree is represented explicitly assert(next_offset - offset > 1); result.children = unsigned(next_offset - offset - 1); return kdtreeBuild(next_offset, nodes, node_count, points, stride, indices + middle, count - middle, leaf_size, depth + 1); } static void kdtreeNearest(KDNode* nodes, unsigned int root, const float* points, size_t stride, const unsigned char* emitted_flags, const float* position, unsigned int& result, float& limit) { const KDNode& node = nodes[root]; if (node.children == 0) return; if (node.axis == 3) { // leaf bool inactive = true; for (unsigned int i = 0; i < node.children; ++i) { unsigned int index = nodes[root + i].index; if (emitted_flags[index]) continue; inactive = false; const float* point = points + index * stride; float dx = point[0] - position[0], dy = point[1] - position[1], dz = point[2] - position[2]; float distance = sqrtf(dx * dx + dy * dy + dz * dz); if (distance < limit) { result = index; limit = distance; } } // deactivate leaves that no longer have items to emit if (inactive) nodes[root].children = 0; } else { // branch; we order recursion to process the node that search position is in first float delta = position[node.axis] - node.split; unsigned int first = (delta <= 0) ? 0 : node.children; unsigned int second = first ^ node.children; // deactivate branches that no longer have items to emit to accelerate traversal // note that we do this *before* recursing which delays deactivation but keeps tail calls if ((nodes[root + 1 + first].children | nodes[root + 1 + second].children) == 0) nodes[root].children = 0; // recursion depth is bounded by tree depth (which is limited by construction) kdtreeNearest(nodes, root + 1 + first, points, stride, emitted_flags, position, result, limit); // only process the other node if it can have a match based on closest distance so far if (fabsf(delta) <= limit) kdtreeNearest(nodes, root + 1 + second, points, stride, emitted_flags, position, result, limit); } } struct BVHBoxT { float min[4]; float max[4]; }; struct BVHBox { float min[3]; float max[3]; }; #if defined(SIMD_SSE) static float boxMerge(BVHBoxT& box, const BVHBox& other) { __m128 min = _mm_loadu_ps(box.min); __m128 max = _mm_loadu_ps(box.max); // note: over-read is safe because BVHBox array is allocated with padding min = _mm_min_ps(min, _mm_loadu_ps(other.min)); max = _mm_max_ps(max, _mm_loadu_ps(other.max)); _mm_storeu_ps(box.min, min); _mm_storeu_ps(box.max, max); __m128 size = _mm_sub_ps(max, min); __m128 size_yzx = _mm_shuffle_ps(size, size, _MM_SHUFFLE(0, 0, 2, 1)); __m128 mul = _mm_mul_ps(size, size_yzx); __m128 sum_xy = _mm_add_ss(mul, _mm_shuffle_ps(mul, mul, _MM_SHUFFLE(1, 1, 1, 1))); __m128 sum_xyz = _mm_add_ss(sum_xy, _mm_shuffle_ps(mul, mul, _MM_SHUFFLE(2, 2, 2, 2))); return _mm_cvtss_f32(sum_xyz); } #elif defined(SIMD_NEON) static float boxMerge(BVHBoxT& box, const BVHBox& other) { float32x4_t min = vld1q_f32(box.min); float32x4_t max = vld1q_f32(box.max); // note: over-read is safe because BVHBox array is allocated with padding min = vminq_f32(min, vld1q_f32(other.min)); max = vmaxq_f32(max, vld1q_f32(other.max)); vst1q_f32(box.min, min); vst1q_f32(box.max, max); float32x4_t size = vsubq_f32(max, min); float32x4_t size_yzx = vextq_f32(vextq_f32(size, size, 3), size, 2); float32x4_t mul = vmulq_f32(size, size_yzx); float sum_xy = vgetq_lane_f32(mul, 0) + vgetq_lane_f32(mul, 1); float sum_xyz = sum_xy + vgetq_lane_f32(mul, 2); return sum_xyz; } #else static float boxMerge(BVHBoxT& box, const BVHBox& other) { for (int k = 0; k < 3; ++k) { box.min[k] = other.min[k] < box.min[k] ? other.min[k] : box.min[k]; box.max[k] = other.max[k] > box.max[k] ? other.max[k] : box.max[k]; } float sx = box.max[0] - box.min[0], sy = box.max[1] - box.min[1], sz = box.max[2] - box.min[2]; return sx * sy + sx * sz + sy * sz; } #endif inline unsigned int radixFloat(unsigned int v) { // if sign bit is 0, flip sign bit // if sign bit is 1, flip everything unsigned int mask = (int(v) >> 31) | 0x80000000; return v ^ mask; } static void computeHistogram(unsigned int (&hist)[1024][3], const float* data, size_t count) { memset(hist, 0, sizeof(hist)); const unsigned int* bits = reinterpret_cast<const unsigned int*>(data); // compute 3 10-bit histograms in parallel (dropping 2 LSB) for (size_t i = 0; i < count; ++i) { unsigned int id = radixFloat(bits[i]); hist[(id >> 2) & 1023][0]++; hist[(id >> 12) & 1023][1]++; hist[(id >> 22) & 1023][2]++; } unsigned int sum0 = 0, sum1 = 0, sum2 = 0; // replace histogram data with prefix histogram sums in-place for (int i = 0; i < 1024; ++i) { unsigned int hx = hist[i][0], hy = hist[i][1], hz = hist[i][2]; hist[i][0] = sum0; hist[i][1] = sum1; hist[i][2] = sum2; sum0 += hx; sum1 += hy; sum2 += hz; } assert(sum0 == count && sum1 == count && sum2 == count); } static void radixPass(unsigned int* destination, const unsigned int* source, const float* keys, size_t count, unsigned int (&hist)[1024][3], int pass) { const unsigned int* bits = reinterpret_cast<const unsigned int*>(keys); int bitoff = pass * 10 + 2; // drop 2 LSB to be able to use 3 10-bit passes for (size_t i = 0; i < count; ++i) { unsigned int id = (radixFloat(bits[source[i]]) >> bitoff) & 1023; destination[hist[id][pass]++] = source[i]; } } static void bvhPrepare(BVHBox* boxes, float* centroids, const unsigned int* indices, size_t face_count, const float* vertex_positions, size_t vertex_count, size_t vertex_stride_float) { (void)vertex_count; for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); const float* va = vertex_positions + vertex_stride_float * a; const float* vb = vertex_positions + vertex_stride_float * b; const float* vc = vertex_positions + vertex_stride_float * c; BVHBox& box = boxes[i]; for (int k = 0; k < 3; ++k) { box.min[k] = va[k] < vb[k] ? va[k] : vb[k]; box.min[k] = vc[k] < box.min[k] ? vc[k] : box.min[k]; box.max[k] = va[k] > vb[k] ? va[k] : vb[k]; box.max[k] = vc[k] > box.max[k] ? vc[k] : box.max[k]; centroids[i + face_count * k] = (box.min[k] + box.max[k]) / 2.f; } } } static size_t bvhCountVertices(const unsigned int* order, size_t count, short* used, const unsigned int* indices, unsigned int* out = NULL) { // count number of unique vertices size_t used_vertices = 0; for (size_t i = 0; i < count; ++i) { unsigned int index = order[i]; unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2]; used_vertices += (used[a] < 0) + (used[b] < 0) + (used[c] < 0); used[a] = used[b] = used[c] = 1; if (out) out[i] = unsigned(used_vertices); } // reset used[] for future invocations for (size_t i = 0; i < count; ++i) { unsigned int index = order[i]; unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2]; used[a] = used[b] = used[c] = -1; } return used_vertices; } static void bvhPackLeaf(unsigned char* boundary, size_t count) { // mark meshlet boundary for future reassembly assert(count > 0); boundary[0] = 1; memset(boundary + 1, 0, count - 1); } static void bvhPackTail(unsigned char* boundary, const unsigned int* order, size_t count, short* used, const unsigned int* indices, size_t max_vertices, size_t max_triangles) { for (size_t i = 0; i < count;) { size_t chunk = i + max_triangles <= count ? max_triangles : count - i; if (bvhCountVertices(order + i, chunk, used, indices) <= max_vertices) { bvhPackLeaf(boundary + i, chunk); i += chunk; continue; } // chunk is vertex bound, split it into smaller meshlets assert(chunk > max_vertices / 3); bvhPackLeaf(boundary + i, max_vertices / 3); i += max_vertices / 3; } } static bool bvhDivisible(size_t count, size_t min, size_t max) { // count is representable as a sum of values in [min..max] if if it in range of [k*min..k*min+k*(max-min)] // equivalent to ceil(count / max) <= floor(count / min), but the form below allows using idiv (see nv_cluster_builder) // we avoid expensive integer divisions in the common case where min is <= max/2 return min * 2 <= max ? count >= min : count % min <= (count / min) * (max - min); } static void bvhComputeArea(float* areas, const BVHBox* boxes, const unsigned int* order, size_t count) { BVHBoxT accuml = {{FLT_MAX, FLT_MAX, FLT_MAX, 0}, {-FLT_MAX, -FLT_MAX, -FLT_MAX, 0}}; BVHBoxT accumr = accuml; for (size_t i = 0; i < count; ++i) { float larea = boxMerge(accuml, boxes[order[i]]); float rarea = boxMerge(accumr, boxes[order[count - 1 - i]]); areas[i] = larea; areas[i + count] = rarea; } } static size_t bvhPivot(const float* areas, const unsigned int* vertices, size_t count, size_t step, size_t min, size_t max, float fill, size_t maxfill, float* out_cost) { bool aligned = count >= min * 2 && bvhDivisible(count, min, max); size_t end = aligned ? count - min : count - 1; float rmaxfill = 1.f / float(int(maxfill)); // find best split that minimizes SAH size_t bestsplit = 0; float bestcost = FLT_MAX; for (size_t i = min - 1; i < end; i += step) { size_t lsplit = i + 1, rsplit = count - (i + 1); if (!bvhDivisible(lsplit, min, max)) continue; if (aligned && !bvhDivisible(rsplit, min, max)) continue; // areas[x] = inclusive surface area of boxes[0..x] // areas[count-1-x] = inclusive surface area of boxes[x..count-1] float larea = areas[i], rarea = areas[(count - 1 - (i + 1)) + count]; float cost = larea * float(int(lsplit)) + rarea * float(int(rsplit)); if (cost > bestcost) continue; // use vertex fill when splitting vertex limited clusters; note that we use the same (left->right) vertex count // using bidirectional vertex counts is a little more expensive to compute and produces slightly worse results in practice size_t lfill = vertices ? vertices[i] : lsplit; size_t rfill = vertices ? vertices[i] : rsplit; // fill cost; use floating point math to round up to maxfill to avoid expensive integer modulo int lrest = int(float(int(lfill + maxfill - 1)) * rmaxfill) * int(maxfill) - int(lfill); int rrest = int(float(int(rfill + maxfill - 1)) * rmaxfill) * int(maxfill) - int(rfill); cost += fill * (float(lrest) * larea + float(rrest) * rarea); if (cost < bestcost) { bestcost = cost; bestsplit = i + 1; } } *out_cost = bestcost; return bestsplit; } static void bvhPartition(unsigned int* target, const unsigned int* order, const unsigned char* sides, size_t split, size_t count) { size_t l = 0, r = split; for (size_t i = 0; i < count; ++i) { unsigned char side = sides[order[i]]; target[side ? r : l] = order[i]; l += 1; l -= side; r += side; } assert(l == split && r == count); } static void bvhSplit(const BVHBox* boxes, unsigned int* orderx, unsigned int* ordery, unsigned int* orderz, unsigned char* boundary, size_t count, int depth, void* scratch, short* used, const unsigned int* indices, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight) { if (count <= max_triangles && bvhCountVertices(orderx, count, used, indices) <= max_vertices) return bvhPackLeaf(boundary, count); unsigned int* axes[3] = {orderx, ordery, orderz}; // we can use step=1 unconditionally but to reduce the cost for min=max case we use step=max size_t step = min_triangles == max_triangles && count > max_triangles ? max_triangles : 1; // if we could not pack the meshlet, we must be vertex bound size_t mint = count <= max_triangles && max_vertices / 3 < min_triangles ? max_vertices / 3 : min_triangles; size_t maxfill = count <= max_triangles ? max_vertices : max_triangles; // find best split that minimizes SAH int bestk = -1; size_t bestsplit = 0; float bestcost = FLT_MAX; for (int k = 0; k < 3; ++k) { float* areas = static_cast<float*>(scratch); unsigned int* vertices = NULL; bvhComputeArea(areas, boxes, axes[k], count); if (count <= max_triangles) { // for vertex bound clusters, count number of unique vertices for each split vertices = reinterpret_cast<unsigned int*>(areas + 2 * count); bvhCountVertices(axes[k], count, used, indices, vertices); } float axiscost = FLT_MAX; size_t axissplit = bvhPivot(areas, vertices, count, step, mint, max_triangles, fill_weight, maxfill, &axiscost); if (axissplit && axiscost < bestcost) { bestk = k; bestcost = axiscost; bestsplit = axissplit; } } // this may happen if SAH costs along the admissible splits are NaN, or due to imbalanced splits on pathological inputs if (bestk < 0 || depth >= kMeshletMaxTreeDepth) return bvhPackTail(boundary, orderx, count, used, indices, max_vertices, max_triangles); // mark sides of split for partitioning unsigned char* sides = static_cast<unsigned char*>(scratch) + count * sizeof(unsigned int); for (size_t i = 0; i < bestsplit; ++i) sides[axes[bestk][i]] = 0; for (size_t i = bestsplit; i < count; ++i) sides[axes[bestk][i]] = 1; // partition all axes into two sides, maintaining order unsigned int* temp = static_cast<unsigned int*>(scratch); for (int k = 0; k < 3; ++k) { if (k == bestk) continue; unsigned int* axis = axes[k]; memcpy(temp, axis, sizeof(unsigned int) * count); bvhPartition(axis, temp, sides, bestsplit, count); } // recursion depth is bounded due to max depth check above bvhSplit(boxes, orderx, ordery, orderz, boundary, bestsplit, depth + 1, scratch, used, indices, max_vertices, min_triangles, max_triangles, fill_weight); bvhSplit(boxes, orderx + bestsplit, ordery + bestsplit, orderz + bestsplit, boundary + bestsplit, count - bestsplit, depth + 1, scratch, used, indices, max_vertices, min_triangles, max_triangles, fill_weight); } } // namespace meshopt size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles) { using namespace meshopt; assert(index_count % 3 == 0); assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices); assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles); (void)kMeshletMaxVertices; (void)kMeshletMaxTriangles; // meshlet construction is limited by max vertices and max triangles per meshlet // the worst case is that the input is an unindexed stream since this equally stresses both limits // note that we assume that in the worst case, we leave 2 vertices unpacked in each meshlet - if we have space for 3 we can pack any triangle size_t max_vertices_conservative = max_vertices - 2; size_t meshlet_limit_vertices = (index_count + max_vertices_conservative - 1) / max_vertices_conservative; size_t meshlet_limit_triangles = (index_count / 3 + max_triangles - 1) / max_triangles; return meshlet_limit_vertices > meshlet_limit_triangles ? meshlet_limit_vertices : meshlet_limit_triangles; } size_t meshopt_buildMeshletsFlex(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices); assert(min_triangles >= 1 && min_triangles <= max_triangles && max_triangles <= kMeshletMaxTriangles); assert(cone_weight >= 0 && cone_weight <= 1); assert(split_factor >= 0); if (index_count == 0) return 0; meshopt_Allocator allocator; TriangleAdjacency2 adjacency = {}; if (vertex_count > index_count && index_count < (1u << 31)) buildTriangleAdjacencySparse(adjacency, indices, index_count, vertex_count, allocator); else buildTriangleAdjacency(adjacency, indices, index_count, vertex_count, allocator); // live triangle counts; note, we alias adjacency.counts as we remove triangles after emitting them so the counts always match unsigned int* live_triangles = adjacency.counts; size_t face_count = index_count / 3; unsigned char* emitted_flags = allocator.allocate<unsigned char>(face_count); memset(emitted_flags, 0, face_count); // for each triangle, precompute centroid & normal to use for scoring Cone* triangles = allocator.allocate<Cone>(face_count); float mesh_area = computeTriangleCones(triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride); // assuming each meshlet is a square patch, expected radius is sqrt(expected area) float triangle_area_avg = face_count == 0 ? 0.f : mesh_area / float(face_count) * 0.5f; float meshlet_expected_radius = sqrtf(triangle_area_avg * max_triangles) * 0.5f; // build a kd-tree for nearest neighbor lookup unsigned int* kdindices = allocator.allocate<unsigned int>(face_count); for (size_t i = 0; i < face_count; ++i) kdindices[i] = unsigned(i); KDNode* nodes = allocator.allocate<KDNode>(face_count * 2); kdtreeBuild(0, nodes, face_count * 2, &triangles[0].px, sizeof(Cone) / sizeof(float), kdindices, face_count, /* leaf_size= */ 8, 0); // find a specific corner of the mesh to use as a starting point for meshlet flow float cornerx = FLT_MAX, cornery = FLT_MAX, cornerz = FLT_MAX; for (size_t i = 0; i < face_count; ++i) { const Cone& tri = triangles[i]; cornerx = cornerx > tri.px ? tri.px : cornerx; cornery = cornery > tri.py ? tri.py : cornery; cornerz = cornerz > tri.pz ? tri.pz : cornerz; } // index of the vertex in the meshlet, -1 if the vertex isn't used short* used = allocator.allocate<short>(vertex_count); clearUsed(used, vertex_count, indices, index_count); // initial seed triangle is the one closest to the corner unsigned int initial_seed = ~0u; float initial_score = FLT_MAX; for (size_t i = 0; i < face_count; ++i) { const Cone& tri = triangles[i]; float dx = tri.px - cornerx, dy = tri.py - cornery, dz = tri.pz - cornerz; float score = sqrtf(dx * dx + dy * dy + dz * dz); if (initial_seed == ~0u || score < initial_score) { initial_seed = unsigned(i); initial_score = score; } } // seed triangles to continue meshlet flow unsigned int seeds[kMeshletMaxSeeds] = {}; size_t seed_count = 0; meshopt_Meshlet meshlet = {}; size_t meshlet_offset = 0; Cone meshlet_cone_acc = {}; for (;;) { Cone meshlet_cone = getMeshletCone(meshlet_cone_acc, meshlet.triangle_count); unsigned int best_triangle = ~0u; // for the first triangle, we don't have a meshlet cone yet, so we use the initial seed // to continue the meshlet, we select an adjacent triangle based on connectivity and spatial scoring if (meshlet_offset == 0 && meshlet.triangle_count == 0) best_triangle = initial_seed; else best_triangle = getNeighborTriangle(meshlet, meshlet_cone, meshlet_vertices, indices, adjacency, triangles, live_triangles, used, meshlet_expected_radius, cone_weight); bool split = false; // when we run out of adjacent triangles we need to switch to spatial search; we currently just pick the closest triangle irrespective of connectivity if (best_triangle == ~0u) { float position[3] = {meshlet_cone.px, meshlet_cone.py, meshlet_cone.pz}; unsigned int index = ~0u; float distance = FLT_MAX; kdtreeNearest(nodes, 0, &triangles[0].px, sizeof(Cone) / sizeof(float), emitted_flags, position, index, distance); best_triangle = index; split = meshlet.triangle_count >= min_triangles && split_factor > 0 && distance > meshlet_expected_radius * split_factor; } if (best_triangle == ~0u) break; int best_extra = (used[indices[best_triangle * 3 + 0]] < 0) + (used[indices[best_triangle * 3 + 1]] < 0) + (used[indices[best_triangle * 3 + 2]] < 0); // if the best triangle doesn't fit into current meshlet, we re-select using seeds to maintain global flow if (split || (meshlet.vertex_count + best_extra > max_vertices || meshlet.triangle_count >= max_triangles)) { seed_count = pruneSeedTriangles(seeds, seed_count, emitted_flags); seed_count = (seed_count + kMeshletAddSeeds <= kMeshletMaxSeeds) ? seed_count : kMeshletMaxSeeds - kMeshletAddSeeds; seed_count += appendSeedTriangles(seeds + seed_count, meshlet, meshlet_vertices, indices, adjacency, triangles, live_triangles, cornerx, cornery, cornerz); unsigned int best_seed = selectSeedTriangle(seeds, seed_count, indices, triangles, live_triangles, cornerx, cornery, cornerz); // we may not find a valid seed triangle if the mesh is disconnected as seeds are based on adjacency best_triangle = best_seed != ~0u ? best_seed : best_triangle; } unsigned int a = indices[best_triangle * 3 + 0], b = indices[best_triangle * 3 + 1], c = indices[best_triangle * 3 + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); // add meshlet to the output; when the current meshlet is full we reset the accumulated bounds if (appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles, split)) { meshlet_offset++; memset(&meshlet_cone_acc, 0, sizeof(meshlet_cone_acc)); } // remove emitted triangle from adjacency data // this makes sure that we spend less time traversing these lists on subsequent iterations // live triangle counts are updated as a byproduct of these adjustments for (size_t k = 0; k < 3; ++k) { unsigned int index = indices[best_triangle * 3 + k]; unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index]; size_t neighbors_size = adjacency.counts[index]; for (size_t i = 0; i < neighbors_size; ++i) { unsigned int tri = neighbors[i]; if (tri == best_triangle) { neighbors[i] = neighbors[neighbors_size - 1]; adjacency.counts[index]--; break; } } } // update aggregated meshlet cone data for scoring subsequent triangles meshlet_cone_acc.px += triangles[best_triangle].px; meshlet_cone_acc.py += triangles[best_triangle].py; meshlet_cone_acc.pz += triangles[best_triangle].pz; meshlet_cone_acc.nx += triangles[best_triangle].nx; meshlet_cone_acc.ny += triangles[best_triangle].ny; meshlet_cone_acc.nz += triangles[best_triangle].nz; assert(!emitted_flags[best_triangle]); emitted_flags[best_triangle] = 1; } if (meshlet.triangle_count) meshlets[meshlet_offset++] = meshlet; assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, min_triangles)); assert(meshlet.triangle_offset + meshlet.triangle_count * 3 <= index_count && meshlet.vertex_offset + meshlet.vertex_count <= index_count); return meshlet_offset; } size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight) { return meshopt_buildMeshletsFlex(meshlets, meshlet_vertices, meshlet_triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, max_triangles, max_triangles, cone_weight, 0.0f); } size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles) { using namespace meshopt; assert(index_count % 3 == 0); assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices); assert(max_triangles >= 1 && max_triangles <= kMeshletMaxTriangles); meshopt_Allocator allocator; // index of the vertex in the meshlet, -1 if the vertex isn't used short* used = allocator.allocate<short>(vertex_count); clearUsed(used, vertex_count, indices, index_count); meshopt_Meshlet meshlet = {}; size_t meshlet_offset = 0; for (size_t i = 0; i < index_count; i += 3) { unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); // appends triangle to the meshlet and writes previous meshlet to the output if full meshlet_offset += appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles); } if (meshlet.triangle_count) meshlets[meshlet_offset++] = meshlet; assert(meshlet_offset <= meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles)); assert(meshlet.triangle_offset + meshlet.triangle_count * 3 <= index_count && meshlet.vertex_offset + meshlet.vertex_count <= index_count); return meshlet_offset; } size_t meshopt_buildMeshletsSpatial(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(max_vertices >= 3 && max_vertices <= kMeshletMaxVertices); assert(min_triangles >= 1 && min_triangles <= max_triangles && max_triangles <= kMeshletMaxTriangles); if (index_count == 0) return 0; size_t face_count = index_count / 3; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); meshopt_Allocator allocator; // 3 floats plus 1 uint for sorting, or // 2 floats plus 1 uint for pivoting, or // 1 uint plus 1 byte for partitioning float* scratch = allocator.allocate<float>(face_count * 4); // compute bounding boxes and centroids for sorting BVHBox* boxes = allocator.allocate<BVHBox>(face_count + 1); // padding for SIMD bvhPrepare(boxes, scratch, indices, face_count, vertex_positions, vertex_count, vertex_stride_float); memset(boxes + face_count, 0, sizeof(BVHBox)); unsigned int* axes = allocator.allocate<unsigned int>(face_count * 3); unsigned int* temp = reinterpret_cast<unsigned int*>(scratch) + face_count * 3; for (int k = 0; k < 3; ++k) { unsigned int* order = axes + k * face_count; const float* keys = scratch + k * face_count; unsigned int hist[1024][3]; computeHistogram(hist, keys, face_count); // 3-pass radix sort computes the resulting order into axes for (size_t i = 0; i < face_count; ++i) temp[i] = unsigned(i); radixPass(order, temp, keys, face_count, hist, 0); radixPass(temp, order, keys, face_count, hist, 1); radixPass(order, temp, keys, face_count, hist, 2); } // index of the vertex in the meshlet, -1 if the vertex isn't used short* used = allocator.allocate<short>(vertex_count); clearUsed(used, vertex_count, indices, index_count); unsigned char* boundary = allocator.allocate<unsigned char>(face_count); bvhSplit(boxes, &axes[0], &axes[face_count], &axes[face_count * 2], boundary, face_count, 0, scratch, used, indices, max_vertices, min_triangles, max_triangles, fill_weight); // compute the desired number of meshlets; note that on some meshes with a lot of vertex bound clusters this might go over the bound size_t meshlet_count = 0; for (size_t i = 0; i < face_count; ++i) { assert(boundary[i] <= 1); meshlet_count += boundary[i]; } size_t meshlet_bound = meshopt_buildMeshletsBound(index_count, max_vertices, min_triangles); // pack triangles into meshlets according to the order and boundaries marked by bvhSplit meshopt_Meshlet meshlet = {}; size_t meshlet_offset = 0; size_t meshlet_pending = meshlet_count; for (size_t i = 0; i < face_count; ++i) { assert(boundary[i] <= 1); bool split = i > 0 && boundary[i] == 1; // while we are over the limit, we ignore boundary[] data and disable splits until we free up enough space if (split && meshlet_count > meshlet_bound && meshlet_offset + meshlet_pending >= meshlet_bound) split = false; unsigned int index = axes[i]; assert(index < face_count); unsigned int a = indices[index * 3 + 0], b = indices[index * 3 + 1], c = indices[index * 3 + 2]; // appends triangle to the meshlet and writes previous meshlet to the output if full meshlet_offset += appendMeshlet(meshlet, a, b, c, used, meshlets, meshlet_vertices, meshlet_triangles, meshlet_offset, max_vertices, max_triangles, split); meshlet_pending -= boundary[i]; } if (meshlet.triangle_count) meshlets[meshlet_offset++] = meshlet; assert(meshlet_offset <= meshlet_bound); assert(meshlet.triangle_offset + meshlet.triangle_count * 3 <= index_count && meshlet.vertex_offset + meshlet.vertex_count <= index_count); return meshlet_offset; } meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(index_count / 3 <= kMeshletMaxTriangles); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); (void)vertex_count; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); // compute triangle normals and gather triangle corners float normals[kMeshletMaxTriangles][3]; float corners[kMeshletMaxTriangles][3][3]; size_t triangles = 0; for (size_t i = 0; i < index_count; i += 3) { unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); const float* p0 = vertex_positions + vertex_stride_float * a; const float* p1 = vertex_positions + vertex_stride_float * b; const float* p2 = vertex_positions + vertex_stride_float * c; float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]}; float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]}; float normalx = p10[1] * p20[2] - p10[2] * p20[1]; float normaly = p10[2] * p20[0] - p10[0] * p20[2]; float normalz = p10[0] * p20[1] - p10[1] * p20[0]; float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz); // no need to include degenerate triangles - they will be invisible anyway if (area == 0.f) continue; // record triangle normals & corners for future use; normal and corner 0 define a plane equation normals[triangles][0] = normalx / area; normals[triangles][1] = normaly / area; normals[triangles][2] = normalz / area; memcpy(corners[triangles][0], p0, 3 * sizeof(float)); memcpy(corners[triangles][1], p1, 3 * sizeof(float)); memcpy(corners[triangles][2], p2, 3 * sizeof(float)); triangles++; } meshopt_Bounds bounds = {}; // degenerate cluster, no valid triangles => trivial reject (cone data is 0) if (triangles == 0) return bounds; const float rzero = 0.f; // compute cluster bounding sphere; we'll use the center to determine normal cone apex as well float psphere[4] = {}; computeBoundingSphere(psphere, corners[0][0], triangles * 3, sizeof(float) * 3, &rzero, 0, 7); float center[3] = {psphere[0], psphere[1], psphere[2]}; // treating triangle normals as points, find the bounding sphere - the sphere center determines the optimal cone axis float nsphere[4] = {}; computeBoundingSphere(nsphere, normals[0], triangles, sizeof(float) * 3, &rzero, 0, 3); float axis[3] = {nsphere[0], nsphere[1], nsphere[2]}; float axislength = sqrtf(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]); float invaxislength = axislength == 0.f ? 0.f : 1.f / axislength; axis[0] *= invaxislength; axis[1] *= invaxislength; axis[2] *= invaxislength; // compute a tight cone around all normals, mindp = cos(angle/2) float mindp = 1.f; for (size_t i = 0; i < triangles; ++i) { float dp = normals[i][0] * axis[0] + normals[i][1] * axis[1] + normals[i][2] * axis[2]; mindp = (dp < mindp) ? dp : mindp; } // fill bounding sphere info; note that below we can return bounds without cone information for degenerate cones bounds.center[0] = center[0]; bounds.center[1] = center[1]; bounds.center[2] = center[2]; bounds.radius = psphere[3]; // degenerate cluster, normal cone is larger than a hemisphere => trivial accept // note that if mindp is positive but close to 0, the triangle intersection code below gets less stable // we arbitrarily decide that if a normal cone is ~168 degrees wide or more, the cone isn't useful if (mindp <= 0.1f) { bounds.cone_cutoff = 1; bounds.cone_cutoff_s8 = 127; return bounds; } float maxt = 0; // we need to find the point on center-t*axis ray that lies in negative half-space of all triangles for (size_t i = 0; i < triangles; ++i) { // dot(center-t*axis-corner, trinormal) = 0 // dot(center-corner, trinormal) - t * dot(axis, trinormal) = 0 float cx = center[0] - corners[i][0][0]; float cy = center[1] - corners[i][0][1]; float cz = center[2] - corners[i][0][2]; float dc = cx * normals[i][0] + cy * normals[i][1] + cz * normals[i][2]; float dn = axis[0] * normals[i][0] + axis[1] * normals[i][1] + axis[2] * normals[i][2]; // dn should be larger than mindp cutoff above assert(dn > 0.f); float t = dc / dn; maxt = (t > maxt) ? t : maxt; } // cone apex should be in the negative half-space of all cluster triangles by construction bounds.cone_apex[0] = center[0] - axis[0] * maxt; bounds.cone_apex[1] = center[1] - axis[1] * maxt; bounds.cone_apex[2] = center[2] - axis[2] * maxt; // note: this axis is the axis of the normal cone, but our test for perspective camera effectively negates the axis bounds.cone_axis[0] = axis[0]; bounds.cone_axis[1] = axis[1]; bounds.cone_axis[2] = axis[2]; // cos(a) for normal cone is mindp; we need to add 90 degrees on both sides and invert the cone // which gives us -cos(a+90) = -(-sin(a)) = sin(a) = sqrt(1 - cos^2(a)) bounds.cone_cutoff = sqrtf(1 - mindp * mindp); // quantize axis & cutoff to 8-bit SNORM format bounds.cone_axis_s8[0] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[0], 8)); bounds.cone_axis_s8[1] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[1], 8)); bounds.cone_axis_s8[2] = (signed char)(meshopt_quantizeSnorm(bounds.cone_axis[2], 8)); // for the 8-bit test to be conservative, we need to adjust the cutoff by measuring the max. error float cone_axis_s8_e0 = fabsf(bounds.cone_axis_s8[0] / 127.f - bounds.cone_axis[0]); float cone_axis_s8_e1 = fabsf(bounds.cone_axis_s8[1] / 127.f - bounds.cone_axis[1]); float cone_axis_s8_e2 = fabsf(bounds.cone_axis_s8[2] / 127.f - bounds.cone_axis[2]); // note that we need to round this up instead of rounding to nearest, hence +1 int cone_cutoff_s8 = int(127 * (bounds.cone_cutoff + cone_axis_s8_e0 + cone_axis_s8_e1 + cone_axis_s8_e2) + 1); bounds.cone_cutoff_s8 = (cone_cutoff_s8 > 127) ? 127 : (signed char)(cone_cutoff_s8); return bounds; } meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(triangle_count <= kMeshletMaxTriangles); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); unsigned int indices[kMeshletMaxTriangles * 3]; for (size_t i = 0; i < triangle_count * 3; ++i) { unsigned int index = meshlet_vertices[meshlet_triangles[i]]; assert(index < vertex_count); indices[i] = index; } return meshopt_computeClusterBounds(indices, triangle_count * 3, vertex_positions, vertex_count, vertex_positions_stride); } meshopt_Bounds meshopt_computeSphereBounds(const float* positions, size_t count, size_t positions_stride, const float* radii, size_t radii_stride) { using namespace meshopt; assert(positions_stride >= 12 && positions_stride <= 256); assert(positions_stride % sizeof(float) == 0); assert((radii_stride >= 4 && radii_stride <= 256) || radii == NULL); assert(radii_stride % sizeof(float) == 0); meshopt_Bounds bounds = {}; if (count == 0) return bounds; const float rzero = 0.f; float psphere[4] = {}; computeBoundingSphere(psphere, positions, count, positions_stride, radii ? radii : &rzero, radii ? radii_stride : 0, 7); bounds.center[0] = psphere[0]; bounds.center[1] = psphere[1]; bounds.center[2] = psphere[2]; bounds.radius = psphere[3]; return bounds; } void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count) { using namespace meshopt; assert(triangle_count <= kMeshletMaxTriangles); assert(vertex_count <= kMeshletMaxVertices); unsigned char* indices = meshlet_triangles; unsigned int* vertices = meshlet_vertices; // cache tracks vertex timestamps (corresponding to triangle index! all 3 vertices are added at the same time and never removed) unsigned char cache[kMeshletMaxVertices]; memset(cache, 0, vertex_count); // note that we start from a value that means all vertices aren't in cache unsigned char cache_last = 128; const unsigned char cache_cutoff = 3; // 3 triangles = ~5..9 vertices depending on reuse for (size_t i = 0; i < triangle_count; ++i) { int next = -1; int next_match = -1; for (size_t j = i; j < triangle_count; ++j) { unsigned char a = indices[j * 3 + 0], b = indices[j * 3 + 1], c = indices[j * 3 + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); // score each triangle by how many vertices are in cache // note: the distance is computed using unsigned 8-bit values, so cache timestamp overflow is handled gracefully int aok = (unsigned char)(cache_last - cache[a]) < cache_cutoff; int bok = (unsigned char)(cache_last - cache[b]) < cache_cutoff; int cok = (unsigned char)(cache_last - cache[c]) < cache_cutoff; if (aok + bok + cok > next_match) { next = (int)j; next_match = aok + bok + cok; // note that we could end up with all 3 vertices in the cache, but 2 is enough for ~strip traversal if (next_match >= 2) break; } } assert(next >= 0); unsigned char a = indices[next * 3 + 0], b = indices[next * 3 + 1], c = indices[next * 3 + 2]; // shift triangles before the next one forward so that we always keep an ordered partition // note: this could have swapped triangles [i] and [next] but that distorts the order and may skew the output sequence memmove(indices + (i + 1) * 3, indices + i * 3, (next - i) * 3 * sizeof(unsigned char)); indices[i * 3 + 0] = a; indices[i * 3 + 1] = b; indices[i * 3 + 2] = c; // cache timestamp is the same between all vertices of each triangle to reduce overflow cache_last++; cache[a] = cache_last; cache[b] = cache_last; cache[c] = cache_last; } // rotate triangles to maximize compressibility memset(cache, 0, vertex_count); for (size_t i = 0; i < triangle_count; ++i) { unsigned char a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; // if only the middle vertex has been used, rotate triangle to ensure new vertices are always sequential if (!cache[a] && cache[b] && !cache[c]) { // abc -> bca unsigned char t = a; a = b, b = c, c = t; } else if (!cache[a] && !cache[b] && !cache[c]) { // out of three edges, the edge ab can not be reused by subsequent triangles in some encodings // if subsequent triangles don't share edges ca or bc, we can rotate the triangle to fix this bool needab = false, needbc = false, needca = false; for (size_t j = i + 1; j < triangle_count && j <= i + cache_cutoff; ++j) { unsigned char oa = indices[j * 3 + 0], ob = indices[j * 3 + 1], oc = indices[j * 3 + 2]; // note: edge comparisons are reversed as reused edges are flipped needab |= (oa == b && ob == a) || (ob == b && oc == a) || (oc == b && oa == a); needbc |= (oa == c && ob == b) || (ob == c && oc == b) || (oc == c && oa == b); needca |= (oa == a && ob == c) || (ob == a && oc == c) || (oc == a && oa == c); } if (needab && !needbc) { // abc -> bca unsigned char t = a; a = b, b = c, c = t; } else if (needab && !needca) { // abc -> cab unsigned char t = c; c = b, b = a, a = t; } } indices[i * 3 + 0] = a, indices[i * 3 + 1] = b, indices[i * 3 + 2] = c; cache[a] = cache[b] = cache[c] = 1; } // reorder meshlet vertices for access locality assuming index buffer is scanned sequentially unsigned int order[kMeshletMaxVertices]; short remap[kMeshletMaxVertices]; memset(remap, -1, vertex_count * sizeof(short)); size_t vertex_offset = 0; for (size_t i = 0; i < triangle_count * 3; ++i) { short& r = remap[indices[i]]; if (r < 0) { r = short(vertex_offset); order[vertex_offset] = vertices[indices[i]]; vertex_offset++; } indices[i] = (unsigned char)r; } assert(vertex_offset <= vertex_count); memcpy(vertices, order, vertex_offset * sizeof(unsigned int)); } #undef SIMD_SSE #undef SIMD_NEON
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/indexanalyzer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size) { assert(index_count % 3 == 0); assert(cache_size >= 3); assert(warp_size == 0 || warp_size >= 3); meshopt_Allocator allocator; meshopt_VertexCacheStatistics result = {}; unsigned int warp_offset = 0; unsigned int primgroup_offset = 0; unsigned int* cache_timestamps = allocator.allocate<unsigned int>(vertex_count); memset(cache_timestamps, 0, vertex_count * sizeof(unsigned int)); unsigned int timestamp = cache_size + 1; for (size_t i = 0; i < index_count; i += 3) { unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); bool ac = (timestamp - cache_timestamps[a]) > cache_size; bool bc = (timestamp - cache_timestamps[b]) > cache_size; bool cc = (timestamp - cache_timestamps[c]) > cache_size; // flush cache if triangle doesn't fit into warp or into the primitive buffer if ((primgroup_size && primgroup_offset == primgroup_size) || (warp_size && warp_offset + ac + bc + cc > warp_size)) { result.warps_executed += warp_offset > 0; warp_offset = 0; primgroup_offset = 0; // reset cache timestamp += cache_size + 1; } // update cache and add vertices to warp for (int j = 0; j < 3; ++j) { unsigned int index = indices[i + j]; if (timestamp - cache_timestamps[index] > cache_size) { cache_timestamps[index] = timestamp++; result.vertices_transformed++; warp_offset++; } } primgroup_offset++; } size_t unique_vertex_count = 0; for (size_t i = 0; i < vertex_count; ++i) unique_vertex_count += cache_timestamps[i] > 0; result.warps_executed += warp_offset > 0; result.acmr = index_count == 0 ? 0 : float(result.vertices_transformed) / float(index_count / 3); result.atvr = unique_vertex_count == 0 ? 0 : float(result.vertices_transformed) / float(unique_vertex_count); return result; } meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size) { assert(index_count % 3 == 0); assert(vertex_size > 0 && vertex_size <= 256); meshopt_Allocator allocator; meshopt_VertexFetchStatistics result = {}; unsigned char* vertex_visited = allocator.allocate<unsigned char>(vertex_count); memset(vertex_visited, 0, vertex_count); const size_t kCacheLine = 64; const size_t kCacheSize = 128 * 1024; // simple direct mapped cache; on typical mesh data this is close to 4-way cache, and this model is a gross approximation anyway size_t cache[kCacheSize / kCacheLine] = {}; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); vertex_visited[index] = 1; size_t start_address = index * vertex_size; size_t end_address = start_address + vertex_size; size_t start_tag = start_address / kCacheLine; size_t end_tag = (end_address + kCacheLine - 1) / kCacheLine; assert(start_tag < end_tag); for (size_t tag = start_tag; tag < end_tag; ++tag) { size_t line = tag % (sizeof(cache) / sizeof(cache[0])); // we store +1 since cache is filled with 0 by default result.bytes_fetched += (cache[line] != tag + 1) * kCacheLine; cache[line] = tag + 1; } } size_t unique_vertex_count = 0; for (size_t i = 0; i < vertex_count; ++i) unique_vertex_count += vertex_visited[i]; result.overfetch = unique_vertex_count == 0 ? 0 : float(result.bytes_fetched) / float(unique_vertex_count * vertex_size); return result; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/indexcodec.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> // This work is based on: // Fabian Giesen. Simple lossless index buffer compression & follow-up. 2013 // Conor Stokes. Vertex Cache Optimised Index Buffer Compression. 2014 namespace meshopt { const unsigned char kIndexHeader = 0xe0; const unsigned char kSequenceHeader = 0xd0; static int gEncodeIndexVersion = 1; const int kDecodeIndexVersion = 1; typedef unsigned int VertexFifo[16]; typedef unsigned int EdgeFifo[16][2]; static const unsigned char kCodeAuxEncodingTable[16] = { 0x00, 0x76, 0x87, 0x56, 0x67, 0x78, 0xa9, 0x86, 0x65, 0x89, 0x68, 0x98, 0x01, 0x69, 0, 0, // last two entries aren't used for encoding }; static int rotateTriangle(unsigned int a, unsigned int b, unsigned int c, unsigned int next) { (void)a; return (b == next) ? 1 : (c == next ? 2 : 0); } static int getEdgeFifo(EdgeFifo fifo, unsigned int a, unsigned int b, unsigned int c, size_t offset) { for (int i = 0; i < 16; ++i) { size_t index = (offset - 1 - i) & 15; unsigned int e0 = fifo[index][0]; unsigned int e1 = fifo[index][1]; if (e0 == a && e1 == b) return (i << 2) | 0; if (e0 == b && e1 == c) return (i << 2) | 1; if (e0 == c && e1 == a) return (i << 2) | 2; } return -1; } static void pushEdgeFifo(EdgeFifo fifo, unsigned int a, unsigned int b, size_t& offset) { fifo[offset][0] = a; fifo[offset][1] = b; offset = (offset + 1) & 15; } static int getVertexFifo(VertexFifo fifo, unsigned int v, size_t offset) { for (int i = 0; i < 16; ++i) { size_t index = (offset - 1 - i) & 15; if (fifo[index] == v) return i; } return -1; } static void pushVertexFifo(VertexFifo fifo, unsigned int v, size_t& offset, int cond = 1) { fifo[offset] = v; offset = (offset + cond) & 15; } static void encodeVByte(unsigned char*& data, unsigned int v) { // encode 32-bit value in up to 5 7-bit groups do { *data++ = (v & 127) | (v > 127 ? 128 : 0); v >>= 7; } while (v); } static unsigned int decodeVByte(const unsigned char*& data) { unsigned char lead = *data++; // fast path: single byte if (lead < 128) return lead; // slow path: up to 4 extra bytes // note that this loop always terminates, which is important for malformed data unsigned int result = lead & 127; unsigned int shift = 7; for (int i = 0; i < 4; ++i) { unsigned char group = *data++; result |= unsigned(group & 127) << shift; shift += 7; if (group < 128) break; } return result; } static void encodeIndex(unsigned char*& data, unsigned int index, unsigned int last) { unsigned int d = index - last; unsigned int v = (d << 1) ^ (int(d) >> 31); encodeVByte(data, v); } static unsigned int decodeIndex(const unsigned char*& data, unsigned int last) { unsigned int v = decodeVByte(data); unsigned int d = (v >> 1) ^ -int(v & 1); return last + d; } static int getCodeAuxIndex(unsigned char v, const unsigned char* table) { for (int i = 0; i < 16; ++i) if (table[i] == v) return i; return -1; } static void writeTriangle(void* destination, size_t offset, size_t index_size, unsigned int a, unsigned int b, unsigned int c) { if (index_size == 2) { static_cast<unsigned short*>(destination)[offset + 0] = (unsigned short)(a); static_cast<unsigned short*>(destination)[offset + 1] = (unsigned short)(b); static_cast<unsigned short*>(destination)[offset + 2] = (unsigned short)(c); } else { static_cast<unsigned int*>(destination)[offset + 0] = a; static_cast<unsigned int*>(destination)[offset + 1] = b; static_cast<unsigned int*>(destination)[offset + 2] = c; } } } // namespace meshopt size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count) { using namespace meshopt; assert(index_count % 3 == 0); // the minimum valid encoding is header, 1 byte per triangle and a 16-byte codeaux table if (buffer_size < 1 + index_count / 3 + 16) return 0; int version = gEncodeIndexVersion; buffer[0] = (unsigned char)(kIndexHeader | version); EdgeFifo edgefifo; memset(edgefifo, -1, sizeof(edgefifo)); VertexFifo vertexfifo; memset(vertexfifo, -1, sizeof(vertexfifo)); size_t edgefifooffset = 0; size_t vertexfifooffset = 0; unsigned int next = 0; unsigned int last = 0; unsigned char* code = buffer + 1; unsigned char* data = code + index_count / 3; unsigned char* data_safe_end = buffer + buffer_size - 16; int fecmax = version >= 1 ? 13 : 15; static const int rotations[] = {0, 1, 2, 0, 1}; // use static encoding table; it's possible to pack the result and then build an optimal table and repack // for now we keep it simple and use the table that has been generated based on symbol frequency on a training mesh set const unsigned char* codeaux_table = kCodeAuxEncodingTable; for (size_t i = 0; i < index_count; i += 3) { // make sure we have enough space to write a triangle // each triangle writes at most 16 bytes: 1b for codeaux and 5b for each free index // after this we can be sure we can write without extra bounds checks if (data > data_safe_end) return 0; int fer = getEdgeFifo(edgefifo, indices[i + 0], indices[i + 1], indices[i + 2], edgefifooffset); if (fer >= 0 && (fer >> 2) < 15) { // note: getEdgeFifo implicitly rotates triangles by matching a/b to existing edge const int* order = rotations + (fer & 3); unsigned int a = indices[i + order[0]], b = indices[i + order[1]], c = indices[i + order[2]]; // encode edge index and vertex fifo index, next or free index int fe = fer >> 2; int fc = getVertexFifo(vertexfifo, c, vertexfifooffset); int fec = (fc >= 1 && fc < fecmax) ? fc : (c == next ? (next++, 0) : 15); if (fec == 15 && version >= 1) { // encode last-1 and last+1 to optimize strip-like sequences if (c + 1 == last) fec = 13, last = c; if (c == last + 1) fec = 14, last = c; } *code++ = (unsigned char)((fe << 4) | fec); // note that we need to update the last index since free indices are delta-encoded if (fec == 15) encodeIndex(data, c, last), last = c; // we only need to push third vertex since first two are likely already in the vertex fifo if (fec == 0 || fec >= fecmax) pushVertexFifo(vertexfifo, c, vertexfifooffset); // we only need to push two new edges to edge fifo since the third one is already there pushEdgeFifo(edgefifo, c, b, edgefifooffset); pushEdgeFifo(edgefifo, a, c, edgefifooffset); } else { int rotation = rotateTriangle(indices[i + 0], indices[i + 1], indices[i + 2], next); const int* order = rotations + rotation; unsigned int a = indices[i + order[0]], b = indices[i + order[1]], c = indices[i + order[2]]; // if a/b/c are 0/1/2, we emit a reset code bool reset = false; if (a == 0 && b == 1 && c == 2 && next > 0 && version >= 1) { reset = true; next = 0; // reset vertex fifo to make sure we don't accidentally reference vertices from that in the future // this makes sure next continues to get incremented instead of being stuck memset(vertexfifo, -1, sizeof(vertexfifo)); } int fb = getVertexFifo(vertexfifo, b, vertexfifooffset); int fc = getVertexFifo(vertexfifo, c, vertexfifooffset); // after rotation, a is almost always equal to next, so we don't waste bits on FIFO encoding for a // note: decoder implicitly assumes that if feb=fec=0, then fea=0 (reset code); this is enforced by rotation int fea = (a == next) ? (next++, 0) : 15; int feb = (fb >= 0 && fb < 14) ? fb + 1 : (b == next ? (next++, 0) : 15); int fec = (fc >= 0 && fc < 14) ? fc + 1 : (c == next ? (next++, 0) : 15); // we encode feb & fec in 4 bits using a table if possible, and as a full byte otherwise unsigned char codeaux = (unsigned char)((feb << 4) | fec); int codeauxindex = getCodeAuxIndex(codeaux, codeaux_table); // <14 encodes an index into codeaux table, 14 encodes fea=0, 15 encodes fea=15 if (fea == 0 && codeauxindex >= 0 && codeauxindex < 14 && !reset) { *code++ = (unsigned char)((15 << 4) | codeauxindex); } else { *code++ = (unsigned char)((15 << 4) | 14 | fea); *data++ = codeaux; } // note that we need to update the last index since free indices are delta-encoded if (fea == 15) encodeIndex(data, a, last), last = a; if (feb == 15) encodeIndex(data, b, last), last = b; if (fec == 15) encodeIndex(data, c, last), last = c; // only push vertices that weren't already in fifo if (fea == 0 || fea == 15) pushVertexFifo(vertexfifo, a, vertexfifooffset); if (feb == 0 || feb == 15) pushVertexFifo(vertexfifo, b, vertexfifooffset); if (fec == 0 || fec == 15) pushVertexFifo(vertexfifo, c, vertexfifooffset); // all three edges aren't in the fifo; pushing all of them is important so that we can match them for later triangles pushEdgeFifo(edgefifo, b, a, edgefifooffset); pushEdgeFifo(edgefifo, c, b, edgefifooffset); pushEdgeFifo(edgefifo, a, c, edgefifooffset); } } // make sure we have enough space to write codeaux table if (data > data_safe_end) return 0; // add codeaux encoding table to the end of the stream; this is used for decoding codeaux *and* as padding // we need padding for decoding to be able to assume that each triangle is encoded as <= 16 bytes of extra data // this is enough space for aux byte + 5 bytes per varint index which is the absolute worst case for any input for (size_t i = 0; i < 16; ++i) { // decoder assumes that table entries never refer to separately encoded indices assert((codeaux_table[i] & 0xf) != 0xf && (codeaux_table[i] >> 4) != 0xf); *data++ = codeaux_table[i]; } // since we encode restarts as codeaux without a table reference, we need to make sure 00 is encoded as a table reference assert(codeaux_table[0] == 0); assert(data >= buffer + index_count / 3 + 16); assert(data <= buffer + buffer_size); return data - buffer; } size_t meshopt_encodeIndexBufferBound(size_t index_count, size_t vertex_count) { assert(index_count % 3 == 0); // compute number of bits required for each index unsigned int vertex_bits = 1; while (vertex_bits < 32 && vertex_count > size_t(1) << vertex_bits) vertex_bits++; // worst-case encoding is 2 header bytes + 3 varint-7 encoded index deltas unsigned int vertex_groups = (vertex_bits + 1 + 6) / 7; return 1 + (index_count / 3) * (2 + 3 * vertex_groups) + 16; } void meshopt_encodeIndexVersion(int version) { assert(unsigned(version) <= unsigned(meshopt::kDecodeIndexVersion)); meshopt::gEncodeIndexVersion = version; } int meshopt_decodeIndexVersion(const unsigned char* buffer, size_t buffer_size) { if (buffer_size < 1) return -1; unsigned char header = buffer[0]; if ((header & 0xf0) != meshopt::kIndexHeader && (header & 0xf0) != meshopt::kSequenceHeader) return -1; int version = header & 0x0f; if (version > meshopt::kDecodeIndexVersion) return -1; return version; } int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size) { using namespace meshopt; assert(index_count % 3 == 0); assert(index_size == 2 || index_size == 4); // the minimum valid encoding is header, 1 byte per triangle and a 16-byte codeaux table if (buffer_size < 1 + index_count / 3 + 16) return -2; if ((buffer[0] & 0xf0) != kIndexHeader) return -1; int version = buffer[0] & 0x0f; if (version > kDecodeIndexVersion) return -1; EdgeFifo edgefifo; memset(edgefifo, -1, sizeof(edgefifo)); VertexFifo vertexfifo; memset(vertexfifo, -1, sizeof(vertexfifo)); size_t edgefifooffset = 0; size_t vertexfifooffset = 0; unsigned int next = 0; unsigned int last = 0; int fecmax = version >= 1 ? 13 : 15; // since we store 16-byte codeaux table at the end, triangle data has to begin before data_safe_end const unsigned char* code = buffer + 1; const unsigned char* data = code + index_count / 3; const unsigned char* data_safe_end = buffer + buffer_size - 16; const unsigned char* codeaux_table = data_safe_end; for (size_t i = 0; i < index_count; i += 3) { // make sure we have enough data to read for a triangle // each triangle reads at most 16 bytes of data: 1b for codeaux and 5b for each free index // after this we can be sure we can read without extra bounds checks if (data > data_safe_end) return -2; unsigned char codetri = *code++; if (codetri < 0xf0) { int fe = codetri >> 4; // fifo reads are wrapped around 16 entry buffer unsigned int a = edgefifo[(edgefifooffset - 1 - fe) & 15][0]; unsigned int b = edgefifo[(edgefifooffset - 1 - fe) & 15][1]; unsigned int c = 0; int fec = codetri & 15; // note: this is the most common path in the entire decoder // inside this if we try to stay branchless (by using cmov/etc.) since these aren't predictable if (fec < fecmax) { // fifo reads are wrapped around 16 entry buffer unsigned int cf = vertexfifo[(vertexfifooffset - 1 - fec) & 15]; c = (fec == 0) ? next : cf; int fec0 = fec == 0; next += fec0; // push vertex fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly pushVertexFifo(vertexfifo, c, vertexfifooffset, fec0); } else { // fec - (fec ^ 3) decodes 13, 14 into -1, 1 // note that we need to update the last index since free indices are delta-encoded last = c = (fec != 15) ? last + (fec - (fec ^ 3)) : decodeIndex(data, last); // push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly pushVertexFifo(vertexfifo, c, vertexfifooffset); } // push edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly pushEdgeFifo(edgefifo, c, b, edgefifooffset); pushEdgeFifo(edgefifo, a, c, edgefifooffset); // output triangle writeTriangle(destination, i, index_size, a, b, c); } else { // fast path: read codeaux from the table if (codetri < 0xfe) { unsigned char codeaux = codeaux_table[codetri & 15]; // note: table can't contain feb/fec=15 int feb = codeaux >> 4; int fec = codeaux & 15; // fifo reads are wrapped around 16 entry buffer // also note that we increment next for all three vertices before decoding indices - this matches encoder behavior unsigned int a = next++; unsigned int bf = vertexfifo[(vertexfifooffset - feb) & 15]; unsigned int b = (feb == 0) ? next : bf; int feb0 = feb == 0; next += feb0; unsigned int cf = vertexfifo[(vertexfifooffset - fec) & 15]; unsigned int c = (fec == 0) ? next : cf; int fec0 = fec == 0; next += fec0; // output triangle writeTriangle(destination, i, index_size, a, b, c); // push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly pushVertexFifo(vertexfifo, a, vertexfifooffset); pushVertexFifo(vertexfifo, b, vertexfifooffset, feb0); pushVertexFifo(vertexfifo, c, vertexfifooffset, fec0); pushEdgeFifo(edgefifo, b, a, edgefifooffset); pushEdgeFifo(edgefifo, c, b, edgefifooffset); pushEdgeFifo(edgefifo, a, c, edgefifooffset); } else { // slow path: read a full byte for codeaux instead of using a table lookup unsigned char codeaux = *data++; int fea = codetri == 0xfe ? 0 : 15; int feb = codeaux >> 4; int fec = codeaux & 15; // reset: codeaux is 0 but encoded as not-a-table if (codeaux == 0) next = 0; // fifo reads are wrapped around 16 entry buffer // also note that we increment next for all three vertices before decoding indices - this matches encoder behavior unsigned int a = (fea == 0) ? next++ : 0; unsigned int b = (feb == 0) ? next++ : vertexfifo[(vertexfifooffset - feb) & 15]; unsigned int c = (fec == 0) ? next++ : vertexfifo[(vertexfifooffset - fec) & 15]; // note that we need to update the last index since free indices are delta-encoded if (fea == 15) last = a = decodeIndex(data, last); if (feb == 15) last = b = decodeIndex(data, last); if (fec == 15) last = c = decodeIndex(data, last); // output triangle writeTriangle(destination, i, index_size, a, b, c); // push vertex/edge fifo must match the encoding step *exactly* otherwise the data will not be decoded correctly pushVertexFifo(vertexfifo, a, vertexfifooffset); pushVertexFifo(vertexfifo, b, vertexfifooffset, (feb == 0) | (feb == 15)); pushVertexFifo(vertexfifo, c, vertexfifooffset, (fec == 0) | (fec == 15)); pushEdgeFifo(edgefifo, b, a, edgefifooffset); pushEdgeFifo(edgefifo, c, b, edgefifooffset); pushEdgeFifo(edgefifo, a, c, edgefifooffset); } } } // we should've read all data bytes and stopped at the boundary between data and codeaux table if (data != data_safe_end) return -3; return 0; } size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count) { using namespace meshopt; // the minimum valid encoding is header, 1 byte per index and a 4-byte tail if (buffer_size < 1 + index_count + 4) return 0; int version = gEncodeIndexVersion; buffer[0] = (unsigned char)(kSequenceHeader | version); unsigned int last[2] = {}; unsigned int current = 0; unsigned char* data = buffer + 1; unsigned char* data_safe_end = buffer + buffer_size - 4; for (size_t i = 0; i < index_count; ++i) { // make sure we have enough data to write // each index writes at most 5 bytes of data; there's a 4 byte tail after data_safe_end // after this we can be sure we can write without extra bounds checks if (data >= data_safe_end) return 0; unsigned int index = indices[i]; // this is a heuristic that switches between baselines when the delta grows too large // we want the encoded delta to fit into one byte (7 bits), but 2 bits are used for sign and baseline index // for now we immediately switch the baseline when delta grows too large - this can be adjusted arbitrarily int cd = int(index - last[current]); current ^= ((cd < 0 ? -cd : cd) >= 30); // encode delta from the last index unsigned int d = index - last[current]; unsigned int v = (d << 1) ^ (int(d) >> 31); // note: low bit encodes the index of the last baseline which will be used for reconstruction encodeVByte(data, (v << 1) | current); // update last for the next iteration that uses it last[current] = index; } // make sure we have enough space to write tail if (data > data_safe_end) return 0; for (int k = 0; k < 4; ++k) *data++ = 0; return data - buffer; } size_t meshopt_encodeIndexSequenceBound(size_t index_count, size_t vertex_count) { // compute number of bits required for each index unsigned int vertex_bits = 1; while (vertex_bits < 32 && vertex_count > size_t(1) << vertex_bits) vertex_bits++; // worst-case encoding is 1 varint-7 encoded index delta for a K bit value and an extra bit unsigned int vertex_groups = (vertex_bits + 1 + 1 + 6) / 7; return 1 + index_count * vertex_groups + 4; } int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size) { using namespace meshopt; // the minimum valid encoding is header, 1 byte per index and a 4-byte tail if (buffer_size < 1 + index_count + 4) return -2; if ((buffer[0] & 0xf0) != kSequenceHeader) return -1; int version = buffer[0] & 0x0f; if (version > kDecodeIndexVersion) return -1; const unsigned char* data = buffer + 1; const unsigned char* data_safe_end = buffer + buffer_size - 4; unsigned int last[2] = {}; for (size_t i = 0; i < index_count; ++i) { // make sure we have enough data to read // each index reads at most 5 bytes of data; there's a 4 byte tail after data_safe_end // after this we can be sure we can read without extra bounds checks if (data >= data_safe_end) return -2; unsigned int v = decodeVByte(data); // decode the index of the last baseline unsigned int current = v & 1; v >>= 1; // reconstruct index as a delta unsigned int d = (v >> 1) ^ -int(v & 1); unsigned int index = last[current] + d; // update last for the next iteration that uses it last[current] = index; if (index_size == 2) { static_cast<unsigned short*>(destination)[i] = (unsigned short)(index); } else { static_cast<unsigned int*>(destination)[i] = index; } } // we should've read all data bytes and stopped at the boundary between data and tail if (data != data_safe_end) return -3; return 0; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/indexgenerator.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> // This work is based on: // Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003 // John McDonald, Mark Kilgard. Crack-Free Point-Normal Triangles using Adjacent Edge Normals. 2010 // John Hable. Variable Rate Shading with Visibility Buffer Rendering. 2024 namespace meshopt { static unsigned int hashUpdate4(unsigned int h, const unsigned char* key, size_t len) { // MurmurHash2 const unsigned int m = 0x5bd1e995; const int r = 24; while (len >= 4) { unsigned int k = *reinterpret_cast<const unsigned int*>(key); k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; key += 4; len -= 4; } return h; } struct VertexHasher { const unsigned char* vertices; size_t vertex_size; size_t vertex_stride; size_t hash(unsigned int index) const { return hashUpdate4(0, vertices + index * vertex_stride, vertex_size); } bool equal(unsigned int lhs, unsigned int rhs) const { return memcmp(vertices + lhs * vertex_stride, vertices + rhs * vertex_stride, vertex_size) == 0; } }; struct VertexStreamHasher { const meshopt_Stream* streams; size_t stream_count; size_t hash(unsigned int index) const { unsigned int h = 0; for (size_t i = 0; i < stream_count; ++i) { const meshopt_Stream& s = streams[i]; const unsigned char* data = static_cast<const unsigned char*>(s.data); h = hashUpdate4(h, data + index * s.stride, s.size); } return h; } bool equal(unsigned int lhs, unsigned int rhs) const { for (size_t i = 0; i < stream_count; ++i) { const meshopt_Stream& s = streams[i]; const unsigned char* data = static_cast<const unsigned char*>(s.data); if (memcmp(data + lhs * s.stride, data + rhs * s.stride, s.size) != 0) return false; } return true; } }; struct VertexCustomHasher { const float* vertex_positions; size_t vertex_stride_float; int (*callback)(void*, unsigned int, unsigned int); void* context; size_t hash(unsigned int index) const { const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + index * vertex_stride_float); unsigned int x = key[0], y = key[1], z = key[2]; // replace negative zero with zero x = (x == 0x80000000) ? 0 : x; y = (y == 0x80000000) ? 0 : y; z = (z == 0x80000000) ? 0 : z; // scramble bits to make sure that integer coordinates have entropy in lower bits x ^= x >> 17; y ^= y >> 17; z ^= z >> 17; // Optimized Spatial Hashing for Collision Detection of Deformable Objects return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791); } bool equal(unsigned int lhs, unsigned int rhs) const { const float* lp = vertex_positions + lhs * vertex_stride_float; const float* rp = vertex_positions + rhs * vertex_stride_float; if (lp[0] != rp[0] || lp[1] != rp[1] || lp[2] != rp[2]) return false; return callback ? callback(context, lhs, rhs) : true; } }; struct EdgeHasher { const unsigned int* remap; size_t hash(unsigned long long edge) const { unsigned int e0 = unsigned(edge >> 32); unsigned int e1 = unsigned(edge); unsigned int h1 = remap[e0]; unsigned int h2 = remap[e1]; const unsigned int m = 0x5bd1e995; // MurmurHash64B finalizer h1 ^= h2 >> 18; h1 *= m; h2 ^= h1 >> 22; h2 *= m; h1 ^= h2 >> 17; h1 *= m; h2 ^= h1 >> 19; h2 *= m; return h2; } bool equal(unsigned long long lhs, unsigned long long rhs) const { unsigned int l0 = unsigned(lhs >> 32); unsigned int l1 = unsigned(lhs); unsigned int r0 = unsigned(rhs >> 32); unsigned int r1 = unsigned(rhs); return remap[l0] == remap[r0] && remap[l1] == remap[r1]; } }; static size_t hashBuckets(size_t count) { size_t buckets = 1; while (buckets < count + count / 4) buckets *= 2; return buckets; } template <typename T, typename Hash> static T* hashLookup(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty) { assert(buckets > 0); assert((buckets & (buckets - 1)) == 0); size_t hashmod = buckets - 1; size_t bucket = hash.hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { T& item = table[bucket]; if (item == empty) return &item; if (hash.equal(item, key)) return &item; // hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } assert(false && "Hash table is full"); // unreachable return NULL; } static void buildPositionRemap(unsigned int* remap, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, meshopt_Allocator& allocator) { VertexHasher vertex_hasher = {reinterpret_cast<const unsigned char*>(vertex_positions), 3 * sizeof(float), vertex_positions_stride}; size_t vertex_table_size = hashBuckets(vertex_count); unsigned int* vertex_table = allocator.allocate<unsigned int>(vertex_table_size); memset(vertex_table, -1, vertex_table_size * sizeof(unsigned int)); for (size_t i = 0; i < vertex_count; ++i) { unsigned int index = unsigned(i); unsigned int* entry = hashLookup(vertex_table, vertex_table_size, vertex_hasher, index, ~0u); if (*entry == ~0u) *entry = index; remap[index] = *entry; } allocator.deallocate(vertex_table); } template <typename Hash> static size_t generateVertexRemap(unsigned int* remap, const unsigned int* indices, size_t index_count, size_t vertex_count, const Hash& hash, meshopt_Allocator& allocator) { memset(remap, -1, vertex_count * sizeof(unsigned int)); size_t table_size = hashBuckets(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); memset(table, -1, table_size * sizeof(unsigned int)); unsigned int next_vertex = 0; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices ? indices[i] : unsigned(i); assert(index < vertex_count); if (remap[index] != ~0u) continue; unsigned int* entry = hashLookup(table, table_size, hash, index, ~0u); if (*entry == ~0u) { *entry = index; remap[index] = next_vertex++; } else { assert(remap[*entry] != ~0u); remap[index] = remap[*entry]; } } assert(next_vertex <= vertex_count); return next_vertex; } template <size_t BlockSize> static void remapVertices(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap) { size_t block_size = BlockSize == 0 ? vertex_size : BlockSize; assert(block_size == vertex_size); for (size_t i = 0; i < vertex_count; ++i) if (remap[i] != ~0u) { assert(remap[i] < vertex_count); memcpy(static_cast<unsigned char*>(destination) + remap[i] * block_size, static_cast<const unsigned char*>(vertices) + i * block_size, block_size); } } template <typename Hash> static void generateShadowBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const Hash& hash, meshopt_Allocator& allocator) { unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); memset(remap, -1, vertex_count * sizeof(unsigned int)); size_t table_size = hashBuckets(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); memset(table, -1, table_size * sizeof(unsigned int)); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); if (remap[index] == ~0u) { unsigned int* entry = hashLookup(table, table_size, hash, index, ~0u); if (*entry == ~0u) *entry = index; remap[index] = *entry; } destination[i] = remap[index]; } } } // namespace meshopt size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) { using namespace meshopt; assert(indices || index_count == vertex_count); assert(!indices || index_count % 3 == 0); assert(vertex_size > 0 && vertex_size <= 256); meshopt_Allocator allocator; VertexHasher hasher = {static_cast<const unsigned char*>(vertices), vertex_size, vertex_size}; return generateVertexRemap(destination, indices, index_count, vertex_count, hasher, allocator); } size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count) { using namespace meshopt; assert(indices || index_count == vertex_count); assert(!indices || index_count % 3 == 0); assert(stream_count > 0 && stream_count <= 16); for (size_t i = 0; i < stream_count; ++i) { assert(streams[i].size > 0 && streams[i].size <= 256); assert(streams[i].size <= streams[i].stride); } meshopt_Allocator allocator; VertexStreamHasher hasher = {streams, stream_count}; return generateVertexRemap(destination, indices, index_count, vertex_count, hasher, allocator); } size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int (*callback)(void*, unsigned int, unsigned int), void* context) { using namespace meshopt; assert(indices || index_count == vertex_count); assert(!indices || index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; VertexCustomHasher hasher = {vertex_positions, vertex_positions_stride / sizeof(float), callback, context}; return generateVertexRemap(destination, indices, index_count, vertex_count, hasher, allocator); } void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap) { using namespace meshopt; assert(vertex_size > 0 && vertex_size <= 256); meshopt_Allocator allocator; // support in-place remap if (destination == vertices) { unsigned char* vertices_copy = allocator.allocate<unsigned char>(vertex_count * vertex_size); memcpy(vertices_copy, vertices, vertex_count * vertex_size); vertices = vertices_copy; } // specialize the loop for common vertex sizes to ensure memcpy is compiled as an inlined intrinsic switch (vertex_size) { case 4: return remapVertices<4>(destination, vertices, vertex_count, vertex_size, remap); case 8: return remapVertices<8>(destination, vertices, vertex_count, vertex_size, remap); case 12: return remapVertices<12>(destination, vertices, vertex_count, vertex_size, remap); case 16: return remapVertices<16>(destination, vertices, vertex_count, vertex_size, remap); default: return remapVertices<0>(destination, vertices, vertex_count, vertex_size, remap); } } void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap) { assert(index_count % 3 == 0); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices ? indices[i] : unsigned(i); assert(remap[index] != ~0u); destination[i] = remap[index]; } } void meshopt_generateShadowIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride) { using namespace meshopt; assert(indices); assert(index_count % 3 == 0); assert(vertex_size > 0 && vertex_size <= 256); assert(vertex_size <= vertex_stride); meshopt_Allocator allocator; VertexHasher hasher = {static_cast<const unsigned char*>(vertices), vertex_size, vertex_stride}; generateShadowBuffer(destination, indices, index_count, vertex_count, hasher, allocator); } void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count) { using namespace meshopt; assert(indices); assert(index_count % 3 == 0); assert(stream_count > 0 && stream_count <= 16); for (size_t i = 0; i < stream_count; ++i) { assert(streams[i].size > 0 && streams[i].size <= 256); assert(streams[i].size <= streams[i].stride); } meshopt_Allocator allocator; VertexStreamHasher hasher = {streams, stream_count}; generateShadowBuffer(destination, indices, index_count, vertex_count, hasher, allocator); } void meshopt_generatePositionRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; VertexCustomHasher hasher = {vertex_positions, vertex_positions_stride / sizeof(float), NULL, NULL}; size_t table_size = hashBuckets(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); memset(table, -1, table_size * sizeof(unsigned int)); for (size_t i = 0; i < vertex_count; ++i) { unsigned int* entry = hashLookup(table, table_size, hasher, unsigned(i), ~0u); if (*entry == ~0u) *entry = unsigned(i); destination[i] = *entry; } } void meshopt_generateAdjacencyIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; static const int next[4] = {1, 2, 0, 1}; // build position remap: for each vertex, which other (canonical) vertex does it map to? unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); buildPositionRemap(remap, vertex_positions, vertex_count, vertex_positions_stride, allocator); // build edge set; this stores all triangle edges but we can look these up by any other wedge EdgeHasher edge_hasher = {remap}; size_t edge_table_size = hashBuckets(index_count); unsigned long long* edge_table = allocator.allocate<unsigned long long>(edge_table_size); unsigned int* edge_vertex_table = allocator.allocate<unsigned int>(edge_table_size); memset(edge_table, -1, edge_table_size * sizeof(unsigned long long)); memset(edge_vertex_table, -1, edge_table_size * sizeof(unsigned int)); for (size_t i = 0; i < index_count; i += 3) { for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; unsigned int i2 = indices[i + next[e + 1]]; assert(i0 < vertex_count && i1 < vertex_count && i2 < vertex_count); unsigned long long edge = ((unsigned long long)i0 << 32) | i1; unsigned long long* entry = hashLookup(edge_table, edge_table_size, edge_hasher, edge, ~0ull); if (*entry == ~0ull) { *entry = edge; // store vertex opposite to the edge edge_vertex_table[entry - edge_table] = i2; } } } // build resulting index buffer: 6 indices for each input triangle for (size_t i = 0; i < index_count; i += 3) { unsigned int patch[6]; for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; assert(i0 < vertex_count && i1 < vertex_count); // note: this refers to the opposite edge! unsigned long long edge = ((unsigned long long)i1 << 32) | i0; unsigned long long* oppe = hashLookup(edge_table, edge_table_size, edge_hasher, edge, ~0ull); patch[e * 2 + 0] = i0; patch[e * 2 + 1] = (*oppe == ~0ull) ? i0 : edge_vertex_table[oppe - edge_table]; } memcpy(destination + i * 2, patch, sizeof(patch)); } } void meshopt_generateTessellationIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; static const int next[3] = {1, 2, 0}; // build position remap: for each vertex, which other (canonical) vertex does it map to? unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); buildPositionRemap(remap, vertex_positions, vertex_count, vertex_positions_stride, allocator); // build edge set; this stores all triangle edges but we can look these up by any other wedge EdgeHasher edge_hasher = {remap}; size_t edge_table_size = hashBuckets(index_count); unsigned long long* edge_table = allocator.allocate<unsigned long long>(edge_table_size); memset(edge_table, -1, edge_table_size * sizeof(unsigned long long)); for (size_t i = 0; i < index_count; i += 3) { for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; assert(i0 < vertex_count && i1 < vertex_count); unsigned long long edge = ((unsigned long long)i0 << 32) | i1; unsigned long long* entry = hashLookup(edge_table, edge_table_size, edge_hasher, edge, ~0ull); if (*entry == ~0ull) *entry = edge; } } // build resulting index buffer: 12 indices for each input triangle for (size_t i = 0; i < index_count; i += 3) { unsigned int patch[12]; for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; assert(i0 < vertex_count && i1 < vertex_count); // note: this refers to the opposite edge! unsigned long long edge = ((unsigned long long)i1 << 32) | i0; unsigned long long oppe = *hashLookup(edge_table, edge_table_size, edge_hasher, edge, ~0ull); // use the same edge if opposite edge doesn't exist (border) oppe = (oppe == ~0ull) ? edge : oppe; // triangle index (0, 1, 2) patch[e] = i0; // opposite edge (3, 4; 5, 6; 7, 8) patch[3 + e * 2 + 0] = unsigned(oppe); patch[3 + e * 2 + 1] = unsigned(oppe >> 32); // dominant vertex (9, 10, 11) patch[9 + e] = remap[i0]; } memcpy(destination + i * 4, patch, sizeof(patch)); } } size_t meshopt_generateProvokingIndexBuffer(unsigned int* destination, unsigned int* reorder, const unsigned int* indices, size_t index_count, size_t vertex_count) { assert(index_count % 3 == 0); meshopt_Allocator allocator; unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); memset(remap, -1, vertex_count * sizeof(unsigned int)); // compute vertex valence; this is used to prioritize least used corner // note: we use 8-bit counters for performance; for outlier vertices the valence is incorrect but that just affects the heuristic unsigned char* valence = allocator.allocate<unsigned char>(vertex_count); memset(valence, 0, vertex_count); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); valence[index]++; } unsigned int reorder_offset = 0; // assign provoking vertices; leave the rest for the next pass for (size_t i = 0; i < index_count; i += 3) { unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); // try to rotate triangle such that provoking vertex hasn't been seen before // if multiple vertices are new, prioritize the one with least valence // this reduces the risk that a future triangle will have all three vertices seen unsigned int va = remap[a] == ~0u ? valence[a] : ~0u; unsigned int vb = remap[b] == ~0u ? valence[b] : ~0u; unsigned int vc = remap[c] == ~0u ? valence[c] : ~0u; if (vb != ~0u && vb <= va && vb <= vc) { // abc -> bca unsigned int t = a; a = b, b = c, c = t; } else if (vc != ~0u && vc <= va && vc <= vb) { // abc -> cab unsigned int t = c; c = b, b = a, a = t; } unsigned int newidx = reorder_offset; // now remap[a] = ~0u or all three vertices are old // recording remap[a] makes it possible to remap future references to the same index, conserving space if (remap[a] == ~0u) remap[a] = newidx; // we need to clone the provoking vertex to get a unique index // if all three are used the choice is arbitrary since no future triangle will be able to reuse any of these reorder[reorder_offset++] = a; // note: first vertex is final, the other two will be fixed up in next pass destination[i + 0] = newidx; destination[i + 1] = b; destination[i + 2] = c; // update vertex valences for corner heuristic valence[a]--; valence[b]--; valence[c]--; } // remap or clone non-provoking vertices (iterating to skip provoking vertices) int step = 1; for (size_t i = 1; i < index_count; i += step, step ^= 3) { unsigned int index = destination[i]; if (remap[index] == ~0u) { // we haven't seen the vertex before as a provoking vertex // to maintain the reference to the original vertex we need to clone it unsigned int newidx = reorder_offset; remap[index] = newidx; reorder[reorder_offset++] = index; } destination[i] = remap[index]; } assert(reorder_offset <= vertex_count + index_count / 3); return reorder_offset; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/meshletcodec.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> // The block below auto-detects SIMD ISA that can be used on the target platform #ifndef MESHOPTIMIZER_NO_SIMD // The SIMD implementation requires SSE4.1, which can be enabled unconditionally through compiler settings #if defined(__AVX__) || defined(__SSE4_1__) #define SIMD_SSE #endif // MSVC supports compiling SSE4.1 code regardless of compile options; we use a cpuid-based scalar fallback #if !defined(SIMD_SSE) && defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_X64)) #define SIMD_SSE #define SIMD_FALLBACK #endif // GCC 4.9+ and clang 3.8+ support targeting SIMD ISA from individual functions; we use a cpuid-based scalar fallback #if !defined(SIMD_SSE) && ((defined(__clang__) && __clang_major__ * 100 + __clang_minor__ >= 308) || (defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ >= 409)) && (defined(__i386__) || defined(__x86_64__)) #define SIMD_SSE #define SIMD_FALLBACK #define SIMD_TARGET __attribute__((target("sse4.1"))) #endif // When targeting AArch64, enable NEON SIMD unconditionally; we do not support SIMD decoding for 32-bit ARM #if defined(__aarch64__) || (defined(_MSC_VER) && defined(_M_ARM64) && _MSC_VER >= 1922) #define SIMD_NEON #endif #if defined(_MSC_VER) && _MSC_VER > 1930 #define SIMD_FLATTEN [[msvc::flatten]] #elif defined(__GNUC__) || defined(__clang__) #define SIMD_FLATTEN __attribute__((flatten)) #else #define SIMD_FLATTEN #endif #ifndef SIMD_TARGET #define SIMD_TARGET #endif #endif // !MESHOPTIMIZER_NO_SIMD #ifdef SIMD_SSE #include <smmintrin.h> #endif #ifdef SIMD_NEON #include <arm_neon.h> #endif #if defined(SIMD_SSE) && defined(SIMD_FALLBACK) #ifdef _MSC_VER #include <intrin.h> // __cpuid #else #include <cpuid.h> // __cpuid #endif #endif #ifndef TRACE #define TRACE 0 #endif #if TRACE #include <stdio.h> #endif namespace meshopt { typedef unsigned int EdgeFifo8[8][2]; static int rotateTriangle(unsigned int a, unsigned int b, unsigned int c) { return (a > b && a > c) ? 1 : (b > c ? 2 : 0); } static int getEdgeFifo8(EdgeFifo8 fifo, unsigned int a, unsigned int b, unsigned int c, size_t offset) { for (int i = 0; i < 8; ++i) { size_t index = (offset - 1 - i) & 7; unsigned int e0 = fifo[index][0]; unsigned int e1 = fifo[index][1]; if (e0 == a && e1 == b) return (i << 2) | 0; if (e0 == b && e1 == c) return (i << 2) | 1; if (e0 == c && e1 == a) return (i << 2) | 2; } return -1; } static void pushEdgeFifo8(EdgeFifo8 fifo, unsigned int a, unsigned int b, size_t& offset) { fifo[offset][0] = a; fifo[offset][1] = b; offset = (offset + 1) & 7; } static size_t encodeTriangles(unsigned char* codes, unsigned char* extra, const unsigned char* triangles, size_t triangle_count) { EdgeFifo8 edgefifo; memset(edgefifo, -1, sizeof(edgefifo)); size_t edgefifooffset = 0; unsigned int next = 0; // 4-bit triangle codes give us 16 options that we use as follows: // 3*2 edge reuse (2 edges * 3 last triangles) * 2 next/explicit = 12 options // 4 remaining options = next bits; 000, 001, 011, 111. // triangles are rotated to make next bits line up. memset(codes, 0, (triangle_count + 1) / 2); static const int rotations[] = {0, 1, 2, 0, 1}; unsigned char* start = extra; for (size_t i = 0; i < triangle_count; ++i) { #if TRACE > 1 unsigned int last = next; #endif int fer = getEdgeFifo8(edgefifo, triangles[i * 3 + 0], triangles[i * 3 + 1], triangles[i * 3 + 2], edgefifooffset); if (fer >= 0 && (fer >> 2) < 6) { // note: getEdgeFifo8 implicitly rotates triangles by matching a/b to existing edge const int* order = rotations + (fer & 3); unsigned int a = triangles[i * 3 + order[0]], b = triangles[i * 3 + order[1]], c = triangles[i * 3 + order[2]]; int fec = (c == next) ? (next++, 0) : 1; #if TRACE > 1 printf("%3d+ | %3d %3d %3d | edge: e%d c%d\n", last, a, b, c, fer >> 2, fec); #endif unsigned int code = (fer >> 2) * 2 + fec; codes[i / 2] |= (unsigned char)(code << ((i & 1) * 4)); if (fec) *extra++ = (unsigned char)c; pushEdgeFifo8(edgefifo, c, b, edgefifooffset); pushEdgeFifo8(edgefifo, a, c, edgefifooffset); } else { // rotate triangles to minimize the need for extra vertices int rotation = rotateTriangle(triangles[i * 3 + 0], triangles[i * 3 + 1], triangles[i * 3 + 2]); const int* order = rotations + rotation; unsigned int a = triangles[i * 3 + order[0]], b = triangles[i * 3 + order[1]], c = triangles[i * 3 + order[2]]; // fe must be continuous: once a vertex is encoded with next, further vertices must also be encoded with next int fea = (a == next && b == next + 1 && c == next + 2) ? (next++, 0) : 1; int feb = (b == next && c == next + 1) ? (next++, 0) : 1; int fec = (c == next) ? (next++, 0) : 1; assert(fea == 1 || feb == 0); assert(feb == 1 || fec == 0); #if TRACE > 1 printf("%3d+ | %3d %3d %3d | restart: %d%d%d\n", last, a, b, c, fea, feb, fec); #endif unsigned int code = 12 + (fea + feb + fec); codes[i / 2] |= (unsigned char)(code << ((i & 1) * 4)); if (fea) *extra++ = (unsigned char)a; if (feb) *extra++ = (unsigned char)b; if (fec) *extra++ = (unsigned char)c; pushEdgeFifo8(edgefifo, c, b, edgefifooffset); pushEdgeFifo8(edgefifo, a, c, edgefifooffset); } } return extra - start; } static size_t encodeVertices(unsigned char* ctrl, unsigned char* data, const unsigned int* vertices, size_t vertex_count) { // grouped varint, 2 bit per value to indicate 0/1/2/3 byte deltas, with per-group 4-byte fallback memset(ctrl, 0, (vertex_count + 3) / 4); unsigned char* start = data; unsigned int last = ~0u; for (size_t i = 0; i < vertex_count; i += 4) { unsigned int gv[4] = {}; for (int k = 0; k < 4 && i + k < vertex_count; ++k) { unsigned int d = vertices[i + k] - last - 1; unsigned int v = (d << 1) ^ (int(d) >> 31); gv[k] = v; last = vertices[i + k]; } // if any value needs 4 bytes, or if *all* values need 3 bytes, we use 4 bytes for all values // this allows us to encode most 3-byte deltas with 3 bytes which saves space overall bool use4 = (gv[0] | gv[1] | gv[2] | gv[3]) > 0xffffff || (gv[0] > 0xffff && gv[1] > 0xffff && gv[2] > 0xffff && gv[3] > 0xffff); for (int k = 0; k < 4; ++k) { unsigned int v = gv[k]; // 0/1/2/3 bytes per value, or all 4 values use 4 bytes int code = use4 ? 3 : (v == 0 ? 0 : (v < 256 ? 1 : (v < 65536 ? 2 : 3))); if (code > 0) *data++ = (unsigned char)(v & 0xff); if (code > 1) *data++ = (unsigned char)((v >> 8) & 0xff); if (code > 2) *data++ = (unsigned char)((v >> 16) & 0xff); if (use4) *data++ = (unsigned char)((v >> 24) & 0xff); // split low and high bits into two nibbles for better packing ctrl[i / 4] |= ((code & 1) << k) | ((code >> 1) << (k + 4)); } } return data - start; } #if defined(SIMD_FALLBACK) || (!defined(SIMD_SSE) && !defined(SIMD_NEON)) inline void writeTriangle(unsigned int* triangles, size_t i, unsigned int fifo) { // output triangle is stored without extra edge vertex (0xcbac => 0xcba) triangles[i] = fifo >> 8; } inline void writeTriangle(unsigned char* triangles, size_t i, unsigned int fifo) { triangles[i * 3 + 0] = (unsigned char)(fifo >> 8); triangles[i * 3 + 1] = (unsigned char)(fifo >> 16); triangles[i * 3 + 2] = (unsigned char)(fifo >> 24); } template <typename T> static const unsigned char* decodeTriangles(T* triangles, const unsigned char* codes, const unsigned char* extra, const unsigned char* bound, size_t triangle_count) { // branchlessly read next or extra vertex and advance pointers #define NEXT(var, ec) \ e = *extra; \ unsigned int var = (ec) ? e : next; \ extra += (ec), next += 1 - (ec) unsigned int next = 0; unsigned int fifo[3] = {}; // two edge fifo entries in one uint: 0xcbac for (size_t i = 0; i < triangle_count; ++i) { if (extra > bound) return NULL; unsigned int code = (codes[i / 2] >> ((i & 1) * 4)) & 0xF; unsigned int tri; if (code < 12) { // reuse unsigned int edge = fifo[code / 4]; edge >>= (code << 3) & 16; // shift by 16 if bit 1 is set (odd edge for each triangle) // 0-1 extra vertices unsigned int e; NEXT(c, code & 1); // repack triangle into edge format (0xcbac) tri = ((edge & 0xff) << 16) | (edge & 0xff00) | c | (c << 24); } else { // restart int fea = code > 12; int feb = code > 13; int fec = code > 14; // 0-3 extra vertices unsigned int e; NEXT(a, fea); NEXT(b, feb); NEXT(c, fec); // repack triangle into edge format (0xcbac) tri = c | (a << 8) | (b << 16) | (c << 24); } writeTriangle(triangles, i, tri); fifo[2] = fifo[1]; fifo[1] = fifo[0]; fifo[0] = tri; } return extra; #undef NEXT } template <typename V> static const unsigned char* decodeVertices(V* vertices, const unsigned char* ctrl, const unsigned char* data, const unsigned char* bound, size_t vertex_count) { unsigned int last = ~0u; for (size_t i = 0; i < vertex_count; i += 4) { if (data > bound) return NULL; unsigned char code4 = ctrl[i / 4]; for (int k = 0; k < 4; ++k) { int code = ((code4 >> k) & 1) | ((code4 >> (k + 3)) & 2); int length = code4 == 0xff ? 4 : code; // branchlessly read up to 4 bytes unsigned int mask = (length == 4) ? ~0u : (1 << (8 * length)) - 1; unsigned int v = (data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24)) & mask; // unzigzag + 1 unsigned int d = (v >> 1) ^ -int(v & 1); unsigned int r = last + d + 1; if (i + k < vertex_count) vertices[i + k] = V(r); data += length; last = r; } } return data; } static int decodeMeshlet(void* vertices, void* triangles, const unsigned char* codes, const unsigned char* ctrl, const unsigned char* data, const unsigned char* bound, size_t vertex_count, size_t triangle_count, size_t vertex_size, size_t triangle_size) { if (vertex_size == 4) data = decodeVertices(static_cast<unsigned int*>(vertices), ctrl, data, bound, vertex_count); else data = decodeVertices(static_cast<unsigned short*>(vertices), ctrl, data, bound, vertex_count); if (!data) return -2; if (triangle_size == 4) data = decodeTriangles(static_cast<unsigned int*>(triangles), codes, data, bound, triangle_count); else data = decodeTriangles(static_cast<unsigned char*>(triangles), codes, data, bound, triangle_count); if (!data) return -2; return (data == bound) ? 0 : -3; } #endif #if defined(SIMD_SSE) || defined(SIMD_NEON) // SIMD state is stored in a single 16b register as follows: // 0..5: 6 next extra bytes // 6..14: 9 bytes = 3 triangles worth of index data // 15: 'next' byte // upon reading each triangle pair we need to transform this state such that the 9 bytes with triangle data contain the newly decoded triangles, // which is a permutation of original state modulo per-element additions // this transform can be chained to decode second triangle from original state; we create tables for 256 combinations of two 4-bit triangle codes // the actual decoding becomes shuffle+add per triangle pair, plus management of extra bytes static unsigned char kDecodeTableMasks[256][16]; static unsigned char kDecodeTableExtra[256]; // for SIMD vertex decoding we need to unpack 4 values with 0-4 bytes in each // this can be done with a single control-dependent shuffle per group static unsigned char kDecodeTableVerts[256][16]; static unsigned char kDecodeTableLength[256]; static bool decodeBuildTables() { #define NEXT(var, ec) \ shuf[var] = (ec) ? (unsigned char)extra : 15; \ next[var] = (ec) ? 0 : (unsigned char)nextoff; \ extra += (ec), nextoff += 1 - (ec) // check for SSE4.1 support if we have a fallback path #if defined(SIMD_SSE) && defined(SIMD_FALLBACK) int cpuinfo[4] = {}; #ifdef _MSC_VER __cpuid(cpuinfo, 1); #else __cpuid(1, cpuinfo[0], cpuinfo[1], cpuinfo[2], cpuinfo[3]); #endif // bit 19 = SSE4.1 if ((cpuinfo[2] & (1 << 19)) == 0) return false; #endif // fill triangle decoding tables for each combination of two triangle codes for (int code = 0; code < 256; ++code) { unsigned char shuf[16] = {}; unsigned char next[16] = {}; int extra = 0; int nextoff = 0; // state 0..5 will be refilled every iteration, so we ignore that // state 6..8 will always contain the last decoded triangle because every triangle shifts fifo equally, so we can decode it independently shuf[6] = 12; shuf[7] = 13; shuf[8] = 14; // state 15 will contain next (potentially incremented a few times) shuf[15] = 15; // state 9..11 will contain the first decoded triangle (tri0), which can refer to extra/next and the original triangle history // state 12..14 will contain the second decoded triangle (tri1); when decoding edge reuse, we need to handle edge 0/1 specially as it was just decoded earlier for (int k = 0; k < 2; ++k) { int tri = (code >> (k * 4)) & 0xf; if (tri < 12) { if (k == 1 && tri / 4 == 0) { // we need to decode one of two edges from the triangle we just decoded earlier // for that we simply need to copy shuf/next values for the two decoded indices shuf[9 + k * 3] = shuf[9 + ((tri & 2) ? 2 : 0)]; next[9 + k * 3] = next[9 + ((tri & 2) ? 2 : 0)]; shuf[10 + k * 3] = shuf[9 + ((tri & 2) ? 1 : 2)]; next[10 + k * 3] = next[9 + ((tri & 2) ? 1 : 2)]; } else { // reuse: edge comes from the history based on edge index // note: we reuse with an offset because last triangle in the original history was consumed by tri0 int trioff = 6 + k * 3 + (2 - tri / 4) * 3; // edge cb or ac shuf[9 + k * 3] = (unsigned char)(trioff + ((tri & 2) ? 2 : 0)); shuf[10 + k * 3] = (unsigned char)(trioff + ((tri & 2) ? 1 : 2)); } // third vertex is either next or comes from extra NEXT(11 + k * 3, tri & 1); } else { // restart: three vertices, each comes from next or extra int fea = tri > 12; int feb = tri > 13; int fec = tri > 14; NEXT(9 + k * 3, fea); NEXT(10 + k * 3, feb); NEXT(11 + k * 3, fec); } } // next needs to advance next[15] = (unsigned char)nextoff; // next[0..8] = 0 trivially (never written to); next[9] must also be 0 because nextoff is 0 initially // shuf[0..5] is not used, which allows us to pack next[10..15] + shuf[6..15] into a single 16-byte entry assert(next[9] == 0); memcpy(&kDecodeTableMasks[code][0], &next[10], 6); memcpy(&kDecodeTableMasks[code][6], &shuf[6], 10); kDecodeTableExtra[code] = (unsigned char)extra; } // fill vertex decoding tables for each combination of four vertex references for (unsigned int i = 0; i < 256; ++i) { unsigned char shuf[16] = {}; int offset = 0; for (int k = 0; k < 4; ++k) { int code = ((i >> k) & 1) | ((i >> (k + 3)) & 2); int length = i == 0xff ? 4 : code; // 0/1/2/3 bytes, or all 4 bytes if code==0xff shuf[k * 4 + 0] = (length > 0) ? (unsigned char)(offset + 0) : 0x80; shuf[k * 4 + 1] = (length > 1) ? (unsigned char)(offset + 1) : 0x80; shuf[k * 4 + 2] = (length > 2) ? (unsigned char)(offset + 2) : 0x80; shuf[k * 4 + 3] = (length > 3) ? (unsigned char)(offset + 3) : 0x80; offset += length; } memcpy(kDecodeTableVerts[i], shuf, sizeof(shuf)); kDecodeTableLength[i] = (unsigned char)offset; } return true; #undef NEXT } static bool gDecodeTablesInitialized = decodeBuildTables(); #endif #if defined(SIMD_SSE) SIMD_TARGET inline __m128i decodeTriangleGroup(__m128i state, unsigned char code, const unsigned char*& extra) { __m128i shuf = _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeTableMasks[code])); __m128i next = _mm_slli_si128(shuf, 10); // patch first 6 bytes with current extra and roll state forward __m128i ext = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(extra)); state = _mm_blend_epi16(state, ext, 7); state = _mm_add_epi8(_mm_shuffle_epi8(state, shuf), next); extra += kDecodeTableExtra[code]; return state; } SIMD_TARGET inline __m128i decodeVertexGroup(__m128i last, unsigned char code, const unsigned char*& data) { __m128i word = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data)); __m128i shuf = _mm_loadu_si128(reinterpret_cast<const __m128i*>(kDecodeTableVerts[code])); __m128i v = _mm_shuffle_epi8(word, shuf); // unzigzag+1 __m128i xl = _mm_sub_epi32(_mm_setzero_si128(), _mm_and_si128(v, _mm_set1_epi32(1))); __m128i xr = _mm_srli_epi32(v, 1); __m128i x = _mm_add_epi32(_mm_xor_si128(xl, xr), _mm_set1_epi32(1)); // prefix sum x = _mm_add_epi32(x, _mm_slli_si128(x, 8)); x = _mm_add_epi32(x, _mm_slli_si128(x, 4)); x = _mm_add_epi32(x, _mm_shuffle_epi32(last, 0xff)); data += kDecodeTableLength[code]; return x; } #endif #if defined(SIMD_NEON) SIMD_TARGET inline uint8x16_t decodeTriangleGroup(uint8x16_t state, unsigned char code, const unsigned char*& extra) { uint8x16_t shuf = vld1q_u8(kDecodeTableMasks[code]); uint8x16_t next = vextq_u8(vdupq_n_u8(0), shuf, 6); // patch first 6 bytes with current extra and roll state forward uint8x8_t extl = vld1_u8(extra); uint8x16_t ext = vcombine_u8(extl, vdup_n_u8(0)); state = vbslq_u8(vcombine_u8(vcreate_u8(0xffffffffffffull), vdup_n_u8(0)), ext, state); state = vaddq_u8(vqtbl1q_u8(state, shuf), next); extra += kDecodeTableExtra[code]; return state; } SIMD_TARGET inline uint32x4_t decodeVertexGroup(uint32x4_t last, unsigned char code, const unsigned char*& data) { uint8x16_t word = vld1q_u8(data); uint8x16_t shuf = vld1q_u8(kDecodeTableVerts[code]); uint32x4_t v = vreinterpretq_u32_u8(vqtbl1q_u8(word, shuf)); // unzigzag+1 uint32x4_t xl = vsubq_u32(vdupq_n_u32(0), vandq_u32(v, vdupq_n_u32(1))); uint32x4_t xr = vshrq_n_u32(v, 1); uint32x4_t x = vaddq_u32(veorq_u32(xl, xr), vdupq_n_u32(1)); // prefix sum x = vaddq_u32(x, vextq_u32(vdupq_n_u32(0), x, 2)); x = vaddq_u32(x, vextq_u32(vdupq_n_u32(0), x, 3)); x = vaddq_u32(x, vdupq_n_u32(vgetq_lane_u32(last, 3))); data += kDecodeTableLength[code]; return x; } #endif #if defined(SIMD_SSE) #ifdef __GNUC__ typedef int __attribute__((aligned(1))) unaligned_int; #else typedef int unaligned_int; #endif #endif #if defined(SIMD_SSE) || defined(SIMD_NEON) SIMD_TARGET static const unsigned char* decodeTrianglesSimd(unsigned int* triangles, const unsigned char* codes, const unsigned char* extra, const unsigned char* bound, size_t triangle_count) { #if defined(SIMD_SSE) __m128i repack = _mm_setr_epi8(9, 10, 11, -1, 12, 13, 14, -1, 0, 0, 0, 0, 0, 0, 0, 0); __m128i state = _mm_setzero_si128(); #elif defined(SIMD_NEON) uint8x8_t repack = vcreate_u8(0xff0e0d0cff0b0a09ull); uint8x16_t state = vdupq_n_u8(0); #endif size_t groups = triangle_count / 2; // process all complete groups for (size_t i = 0; i < groups; ++i) { unsigned char code = *codes++; if (extra > bound) return NULL; state = decodeTriangleGroup(state, code, extra); // write 6 bytes of new triangle data into output, formatted as 8 bytes with 0 padding #if defined(SIMD_SSE) __m128i r = _mm_shuffle_epi8(state, repack); _mm_storel_epi64(reinterpret_cast<__m128i*>(&triangles[i * 2]), r); #elif defined(SIMD_NEON) uint32x2_t r = vreinterpret_u32_u8(vqtbl1_u8(state, repack)); vst1_u32(&triangles[i * 2], r); #endif } // process a 1 triangle tail; to maintain the memory safety guarantee we have to write a 32-bit element if (triangle_count & 1) { unsigned char code = *codes++; if (extra > bound) return NULL; state = decodeTriangleGroup(state, code, extra); unsigned int* tail = &triangles[triangle_count & ~1u]; #if defined(SIMD_SSE) __m128i r = _mm_shuffle_epi8(state, repack); *tail = unsigned(_mm_cvtsi128_si32(r)); #elif defined(SIMD_NEON) uint32x2_t r = vreinterpret_u32_u8(vqtbl1_u8(state, repack)); vst1_lane_u32(tail, r, 0); #endif } return extra; } SIMD_TARGET static const unsigned char* decodeTrianglesSimd(unsigned char* triangles, const unsigned char* codes, const unsigned char* extra, const unsigned char* bound, size_t triangle_count) { #if defined(SIMD_SSE) __m128i state = _mm_setzero_si128(); #elif defined(SIMD_NEON) uint8x16_t state = vdupq_n_u8(0); #endif // because the output buffer is guaranteed to have 32-bit aligned size available, we can optimize writes and tail processing // instead of processing triangles 2 at a time, we process 2 *pairs* at a time (12-byte write) followed by a tail pair, if present // if the number of triangles mod 4 is 3, we'd normally need to write 12k+9 bytes, but we can instead overwrite up to 3 bytes in the main loop size_t groups = (triangle_count + 1) / 4; // process all complete groups for (size_t i = 0; i < groups; ++i) { unsigned char code0 = *codes++; unsigned char code1 = *codes++; // each triangle pair reads <=6 bytes from extra, so two pairs need <=12 bytes and gap guarantees 16 byte of overread if (extra > bound) return NULL; state = decodeTriangleGroup(state, code0, extra); // write first decoded triangle and first index of second decoded triangle #if defined(SIMD_SSE) __m128i r0 = _mm_srli_si128(state, 9); *reinterpret_cast<unaligned_int*>(&triangles[i * 12]) = _mm_cvtsi128_si32(r0); #elif defined(SIMD_NEON) uint8x16_t r0 = vextq_u8(state, vdupq_n_u8(0), 9); vst1q_lane_u32(reinterpret_cast<unsigned int*>(&triangles[i * 12]), vreinterpretq_u32_u8(r0), 0); #endif state = decodeTriangleGroup(state, code1, extra); // write last two indices of second decoded triangle that we didn't write above plus two new ones // note that the second decoded triangle has shifted down to 6-8 bytes, hence shift by 7 #if defined(SIMD_SSE) __m128i r1 = _mm_srli_si128(state, 7); _mm_storel_epi64(reinterpret_cast<__m128i*>(&triangles[i * 12 + 4]), r1); #elif defined(SIMD_NEON) uint8x16_t r1 = vextq_u8(state, vdupq_n_u8(0), 7); vst1_u8(&triangles[i * 12 + 4], vget_low_u8(r1)); #endif } // process a 1-2 triangle tail; to maintain the memory safety guarantee we have to write 1-2 32-bit elements if (groups * 4 < triangle_count) { unsigned char code = *codes++; if (extra > bound) return NULL; state = decodeTriangleGroup(state, code, extra); unsigned char* tail = &triangles[(triangle_count & ~3u) * 3]; #if defined(SIMD_SSE) __m128i r = _mm_srli_si128(state, 9); *reinterpret_cast<unaligned_int*>(tail) = _mm_cvtsi128_si32(r); if ((triangle_count & 3) > 1) *reinterpret_cast<unaligned_int*>(tail + 4) = _mm_extract_epi32(r, 1); #elif defined(SIMD_NEON) uint8x16_t r = vextq_u8(state, vdupq_n_u8(0), 9); vst1q_lane_u32(reinterpret_cast<unsigned int*>(tail), vreinterpretq_u32_u8(r), 0); if ((triangle_count & 3) > 1) vst1q_lane_u32(reinterpret_cast<unsigned int*>(tail + 4), vreinterpretq_u32_u8(r), 1); #endif } return extra; } SIMD_TARGET static const unsigned char* decodeVerticesSimd(unsigned int* vertices, const unsigned char* ctrl, const unsigned char* data, const unsigned char* bound, size_t vertex_count) { #if defined(SIMD_SSE) __m128i last = _mm_set1_epi32(-1); #elif defined(SIMD_NEON) uint32x4_t last = vdupq_n_u32(~0u); #endif size_t groups = vertex_count / 4; // process all complete groups for (size_t i = 0; i < groups; ++i) { unsigned char code = *ctrl++; if (data > bound) return NULL; last = decodeVertexGroup(last, code, data); #if defined(SIMD_SSE) _mm_storeu_si128(reinterpret_cast<__m128i*>(&vertices[i * 4]), last); #elif defined(SIMD_NEON) vst1q_u32(&vertices[i * 4], last); #endif } // process a 1-3 vertex tail; to maintain the memory safety guarantee we have to write individual elements if (vertex_count & 3) { unsigned char code = *ctrl++; if (data > bound) return NULL; last = decodeVertexGroup(last, code, data); unsigned int* tail = &vertices[vertex_count & ~3u]; #if defined(SIMD_SSE) tail[0] = _mm_cvtsi128_si32(last); if ((vertex_count & 3) > 1) tail[1] = _mm_extract_epi32(last, 1); if ((vertex_count & 3) > 2) tail[2] = _mm_extract_epi32(last, 2); #elif defined(SIMD_NEON) vst1q_lane_u32(&tail[0], last, 0); if ((vertex_count & 3) > 1) vst1q_lane_u32(&tail[1], last, 1); if ((vertex_count & 3) > 2) vst1q_lane_u32(&tail[2], last, 2); #endif } return data; } SIMD_TARGET static const unsigned char* decodeVerticesSimd(unsigned short* vertices, const unsigned char* ctrl, const unsigned char* data, const unsigned char* bound, size_t vertex_count) { #if defined(SIMD_SSE) __m128i repack = _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0); __m128i last = _mm_set1_epi32(-1); #elif defined(SIMD_NEON) uint32x4_t last = vdupq_n_u32(~0u); #endif // because the output buffer is guaranteed to have 32-bit aligned size available, we can simplify tail processing // if the number of vertices mod 4 is 3, we'd normally need to write 8+6 bytes, but we can instead overwrite up to 2 bytes in the main loop size_t groups = (vertex_count + 1) / 4; // process all complete groups for (size_t i = 0; i < groups; ++i) { unsigned char code = *ctrl++; if (data > bound) return NULL; last = decodeVertexGroup(last, code, data); #if defined(SIMD_SSE) __m128i r = _mm_shuffle_epi8(last, repack); _mm_storel_epi64(reinterpret_cast<__m128i*>(&vertices[i * 4]), r); #elif defined(SIMD_NEON) uint16x4_t r = vmovn_u32(last); vst1_u16(&vertices[i * 4], r); #endif } // process a 1-2 vertex tail; to maintain the memory safety guarantee we have to write a 32-bit element if (groups * 4 < vertex_count) { unsigned char code = *ctrl++; if (data > bound) return NULL; last = decodeVertexGroup(last, code, data); unsigned short* tail = &vertices[vertex_count & ~3u]; #if defined(SIMD_SSE) __m128i r = _mm_shufflelo_epi16(last, 8); *reinterpret_cast<unaligned_int*>(tail) = _mm_cvtsi128_si32(r); #elif defined(SIMD_NEON) uint16x4_t r = vmovn_u32(last); vst1_lane_u32(reinterpret_cast<unsigned int*>(tail), vreinterpret_u32_u16(r), 0); #endif } return data; } template <int Raw> SIMD_TARGET SIMD_FLATTEN static int decodeMeshletSimd(void* vertices, void* triangles, const unsigned char* codes, const unsigned char* ctrl, const unsigned char* data, const unsigned char* bound, size_t vertex_count, size_t triangle_count, size_t vertex_size, size_t triangle_size) { assert(gDecodeTablesInitialized); (void)gDecodeTablesInitialized; #ifdef __clang__ // data is guaranteed to be non-null initially; if decode loops never hit bounds errors, it remains non-null __builtin_assume(data); #endif // decodes 4 vertices at a time with tail processing; writes up to align(vertex_size * vertex_count, 4) // raw decoding skips tail processing by rounding up vertex count; it's safe because output buffer is guaranteed to have extra space, and tail control data is 0 if (vertex_size == 4 || Raw) data = decodeVerticesSimd(static_cast<unsigned int*>(vertices), ctrl, data, bound, Raw ? (vertex_count + 3) & ~3 : vertex_count); else data = decodeVerticesSimd(static_cast<unsigned short*>(vertices), ctrl, data, bound, vertex_count); if (!data) return -2; // decodes 2/4 triangles at a time with tail processing; writes up to align(triangle_size * triangle_count, 4) // raw decoding skips tail processing by rounding up triangle count; it's safe because output buffer is guaranteed to have extra space, and tail code data is 0 if (triangle_size == 4 || Raw) data = decodeTrianglesSimd(static_cast<unsigned int*>(triangles), codes, data, bound, Raw ? (triangle_count + 1) & ~1 : triangle_count); else data = decodeTrianglesSimd(static_cast<unsigned char*>(triangles), codes, data, bound, triangle_count); if (!data) return -2; return (data == bound) ? 0 : -3; } #endif } // namespace meshopt size_t meshopt_encodeMeshletBound(size_t max_vertices, size_t max_triangles) { size_t codes_size = (max_triangles + 1) / 2; size_t extra_size = max_triangles * 3; size_t ctrl_size = (max_vertices + 3) / 4; size_t data_size = (max_vertices + 3) / 4 * 16; // worst case: 16 bytes per vertex group size_t gap_size = (codes_size + ctrl_size < 16) ? 16 - (codes_size + ctrl_size) : 0; return codes_size + extra_size + ctrl_size + data_size + gap_size; } size_t meshopt_encodeMeshlet(unsigned char* buffer, size_t buffer_size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count) { using namespace meshopt; assert(triangle_count <= 256 && vertex_count <= 256); // 4 bits per triangle + up to three bytes of extra data unsigned char codes[256 / 2]; unsigned char extra[256 * 3]; size_t codes_size = (triangle_count + 1) / 2; size_t extra_size = encodeTriangles(codes, extra, triangles, triangle_count); assert(extra_size <= sizeof(extra)); // 2 bits per vertex + up to 4 bytes of actual data unsigned char ctrl[256 / 4]; unsigned char data[256 * 4]; size_t ctrl_size = (vertex_count + 3) / 4; size_t data_size = encodeVertices(ctrl, data, vertices, vertex_count); assert(data_size <= sizeof(data)); // we need to ensure that up to 16 bytes after extra+data are available for SIMD decoding // to minimize overhead, we place fixed-size codes+control at the end of the buffer size_t gap_size = (codes_size + ctrl_size < 16) ? 16 - (codes_size + ctrl_size) : 0; size_t result = codes_size + extra_size + ctrl_size + data_size + gap_size; if (result > buffer_size) return 0; // variable-size data first memcpy(buffer, data, data_size); buffer += data_size; memcpy(buffer, extra, extra_size); buffer += extra_size; // gap (for accelerated decoding) separates variable-size and fixed-size data memset(buffer, 0, gap_size); buffer += gap_size; // fixed-size data last; it can be located from buffer end during decoding memcpy(buffer, ctrl, ctrl_size); buffer += ctrl_size; memcpy(buffer, codes, codes_size); buffer += codes_size; #if TRACE > 1 printf("extra:"); for (size_t i = 0; i < extra_size; ++i) printf(" %d", extra[i]); printf("\n"); unsigned int minv = ~0u; for (size_t i = 0; i < vertex_count; ++i) minv = minv < vertices[i] ? minv : vertices[i]; printf("vertices: [%d+]", minv); for (size_t i = 0; i < vertex_count; ++i) printf(" %d", vertices[i] - minv); printf("\n"); #endif #if TRACE printf("stats: %d vertices, %d triangles => %d bytes (triangles: %d codes, %d extra; vertices: %d control, %d data; %d gap)\n", int(vertex_count), int(triangle_count), int(result), int(codes_size), int(extra_size), int(ctrl_size), int(data_size), int(gap_size)); #endif return result; } int meshopt_decodeMeshlet(void* vertices, size_t vertex_count, size_t vertex_size, void* triangles, size_t triangle_count, size_t triangle_size, const unsigned char* buffer, size_t buffer_size) { using namespace meshopt; assert(triangle_count <= 256 && vertex_count <= 256); assert(vertex_size == 4 || vertex_size == 2); assert(triangle_size == 4 || triangle_size == 3); // layout must match encoding size_t codes_size = (triangle_count + 1) / 2; size_t ctrl_size = (vertex_count + 3) / 4; size_t gap_size = (codes_size + ctrl_size < 16) ? 16 - (codes_size + ctrl_size) : 0; if (buffer_size < codes_size + ctrl_size + gap_size) return -2; const unsigned char* end = buffer + buffer_size; const unsigned char* codes = end - codes_size; const unsigned char* ctrl = codes - ctrl_size; const unsigned char* data = buffer; // gap ensures we have at least 16 bytes available after bound; this allows SIMD decoders to over-read safely const unsigned char* bound = ctrl - gap_size; assert(bound >= buffer && bound + 16 <= buffer + buffer_size); #if defined(SIMD_FALLBACK) return (gDecodeTablesInitialized ? decodeMeshletSimd<0> : decodeMeshlet)(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, vertex_size, triangle_size); #elif defined(SIMD_SSE) || defined(SIMD_NEON) return decodeMeshletSimd<0>(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, vertex_size, triangle_size); #else return decodeMeshlet(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, vertex_size, triangle_size); #endif } int meshopt_decodeMeshletRaw(unsigned int* vertices, size_t vertex_count, unsigned int* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size) { using namespace meshopt; assert(triangle_count <= 256 && vertex_count <= 256); // layout must match encoding size_t codes_size = (triangle_count + 1) / 2; size_t ctrl_size = (vertex_count + 3) / 4; size_t gap_size = (codes_size + ctrl_size < 16) ? 16 - (codes_size + ctrl_size) : 0; if (buffer_size < codes_size + ctrl_size + gap_size) return -2; const unsigned char* end = buffer + buffer_size; const unsigned char* codes = end - codes_size; const unsigned char* ctrl = codes - ctrl_size; const unsigned char* data = buffer; // gap ensures we have at least 16 bytes available after bound; this allows SIMD decoders to over-read safely const unsigned char* bound = ctrl - gap_size; assert(bound >= buffer && bound + 16 <= buffer + buffer_size); #if defined(SIMD_FALLBACK) return (gDecodeTablesInitialized ? decodeMeshletSimd<1> : decodeMeshlet)(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, 4, 4); #elif defined(SIMD_SSE) || defined(SIMD_NEON) return decodeMeshletSimd<1>(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, 4, 4); #else return decodeMeshlet(vertices, triangles, codes, ctrl, data, bound, vertex_count, triangle_count, 4, 4); #endif } #undef SIMD_SSE #undef SIMD_NEON #undef SIMD_FALLBACK #undef SIMD_FLATTEN #undef SIMD_TARGET
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/meshoptimizer.h
C/C++ Header
/** * meshoptimizer - version 1.0 * * Copyright (C) 2016-2026, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com) * Report bugs and download new versions at https://github.com/zeux/meshoptimizer * * This library is distributed under the MIT License. See notice at the end of this file. */ #pragma once #include <assert.h> #include <stddef.h> /* Version macro; major * 1000 + minor * 10 + patch */ #define MESHOPTIMIZER_VERSION 1000 /* 1.0 */ /* If no API is defined, assume default */ #ifndef MESHOPTIMIZER_API #define MESHOPTIMIZER_API #endif /* Set the calling-convention for alloc/dealloc function pointers */ #ifndef MESHOPTIMIZER_ALLOC_CALLCONV #ifdef _MSC_VER #define MESHOPTIMIZER_ALLOC_CALLCONV __cdecl #else #define MESHOPTIMIZER_ALLOC_CALLCONV #endif #endif /* Experimental APIs have unstable interface and might have implementation that's not fully tested or optimized */ #ifndef MESHOPTIMIZER_EXPERIMENTAL #define MESHOPTIMIZER_EXPERIMENTAL MESHOPTIMIZER_API #endif /* C interface */ #ifdef __cplusplus extern "C" { #endif /** * Vertex attribute stream * Each element takes size bytes, beginning at data, with stride controlling the spacing between successive elements (stride >= size). */ struct meshopt_Stream { const void* data; size_t size; size_t stride; }; /** * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized. * * destination must contain enough space for the resulting remap table (vertex_count elements) * indices can be NULL if the input is unindexed */ MESHOPTIMIZER_API size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); /** * Generates a vertex remap table from multiple vertex streams and an optional index buffer and returns number of unique vertices * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. * To remap vertex buffers, you will need to call meshopt_remapVertexBuffer for each vertex stream. * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized. * * destination must contain enough space for the resulting remap table (vertex_count elements) * indices can be NULL if the input is unindexed * stream_count must be <= 16 */ MESHOPTIMIZER_API size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); /** * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices * As a result, all vertices that are equivalent map to the same (new) location, with no gaps in the resulting sequence. * Equivalence is checked in two steps: vertex positions are compared for equality, and then the user-specified equality function is called (if provided). * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer. * * destination must contain enough space for the resulting remap table (vertex_count elements) * indices can be NULL if the input is unindexed * vertex_positions should have float3 position in the first 12 bytes of each vertex * callback can be NULL if no additional equality check is needed; otherwise, it should return 1 if vertices with specified indices are equivalent and 0 if they are not */ MESHOPTIMIZER_API size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, int (*callback)(void*, unsigned int, unsigned int), void* context); /** * Generates vertex buffer from the source vertex buffer and remap table generated by meshopt_generateVertexRemap * * destination must contain enough space for the resulting vertex buffer (unique_vertex_count elements, returned by meshopt_generateVertexRemap) * vertex_count should be the initial vertex count and not the value returned by meshopt_generateVertexRemap */ MESHOPTIMIZER_API void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap); /** * Generate index buffer from the source index buffer and remap table generated by meshopt_generateVertexRemap * * destination must contain enough space for the resulting index buffer (index_count elements) * indices can be NULL if the input is unindexed */ MESHOPTIMIZER_API void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap); /** * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary * All vertices that are binary equivalent (wrt first vertex_size bytes) map to the first vertex in the original vertex buffer. * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering. * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized. * * destination must contain enough space for the resulting index buffer (index_count elements) */ MESHOPTIMIZER_API void meshopt_generateShadowIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); /** * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary * All vertices that are binary equivalent (wrt specified streams) map to the first vertex in the original vertex buffer. * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering. * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized. * * destination must contain enough space for the resulting index buffer (index_count elements) * stream_count must be <= 16 */ MESHOPTIMIZER_API void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count); /** * Generates a remap table that maps all vertices with the same position to the same (existing) index. * Similarly to meshopt_generateShadowIndexBuffer, this can be helpful to pre-process meshes for position-only rendering. * This can also be used to implement algorithms that require positional-only connectivity, such as hierarchical simplification. * * destination must contain enough space for the resulting remap table (vertex_count elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_generatePositionRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Generate index buffer that can be used as a geometry shader input with triangle adjacency topology * Each triangle is converted into a 6-vertex patch with the following layout: * - 0, 2, 4: original triangle vertices * - 1, 3, 5: vertices adjacent to edges 02, 24 and 40 * The resulting patch can be rendered with geometry shaders using e.g. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY. * This can be used to implement algorithms like silhouette detection/expansion and other forms of GS-driven rendering. * * destination must contain enough space for the resulting index buffer (index_count*2 elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_generateAdjacencyIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Generate index buffer that can be used for PN-AEN tessellation with crack-free displacement * Each triangle is converted into a 12-vertex patch with the following layout: * - 0, 1, 2: original triangle vertices * - 3, 4: opposing edge for edge 0, 1 * - 5, 6: opposing edge for edge 1, 2 * - 7, 8: opposing edge for edge 2, 0 * - 9, 10, 11: dominant vertices for corners 0, 1, 2 * The resulting patch can be rendered with hardware tessellation using PN-AEN and displacement mapping. * See "Tessellation on Any Budget" (John McDonald, GDC 2011) for implementation details. * * destination must contain enough space for the resulting index buffer (index_count*4 elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_generateTessellationIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Generate index buffer that can be used for visibility buffer rendering and returns the size of the reorder table * Each triangle's provoking vertex index is equal to primitive id; this allows passing it to the fragment shader using flat/nointerpolation attribute. * This is important for performance on hardware where primitive id can't be accessed efficiently in fragment shader. * The reorder table stores the original vertex id for each vertex in the new index buffer, and should be used in the vertex shader to load vertex data. * The provoking vertex is assumed to be the first vertex in the triangle; if this is not the case (OpenGL), rotate each triangle (abc -> bca) before rendering. * For maximum efficiency the input index buffer should be optimized for vertex cache first. * * destination must contain enough space for the resulting index buffer (index_count elements) * reorder must contain enough space for the worst case reorder table (vertex_count + index_count/3 elements) */ MESHOPTIMIZER_API size_t meshopt_generateProvokingIndexBuffer(unsigned int* destination, unsigned int* reorder, const unsigned int* indices, size_t index_count, size_t vertex_count); /** * Vertex transform cache optimizer * Reorders indices to reduce the number of GPU vertex shader invocations * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. * * destination must contain enough space for the resulting index buffer (index_count elements) */ MESHOPTIMIZER_API void meshopt_optimizeVertexCache(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); /** * Vertex transform cache optimizer for strip-like caches * Produces inferior results to meshopt_optimizeVertexCache from the GPU vertex cache perspective * However, the resulting index order is more optimal if the goal is to reduce the triangle strip length or improve compression efficiency * * destination must contain enough space for the resulting index buffer (index_count elements) */ MESHOPTIMIZER_API void meshopt_optimizeVertexCacheStrip(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); /** * Vertex transform cache optimizer for FIFO caches * Reorders indices to reduce the number of GPU vertex shader invocations * Generally takes ~3x less time to optimize meshes but produces inferior results compared to meshopt_optimizeVertexCache * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. * * destination must contain enough space for the resulting index buffer (index_count elements) * cache_size should be less than the actual GPU cache size to avoid cache thrashing */ MESHOPTIMIZER_API void meshopt_optimizeVertexCacheFifo(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size); /** * Overdraw optimizer * Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw * If index buffer contains multiple ranges for multiple draw calls, this function needs to be called on each range individually. * * destination must contain enough space for the resulting index buffer (index_count elements) * indices must contain index data that is the result of meshopt_optimizeVertexCache (*not* the original mesh indices!) * vertex_positions should have float3 position in the first 12 bytes of each vertex * threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently */ MESHOPTIMIZER_API void meshopt_optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold); /** * Vertex fetch cache optimizer * Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused * This function works for a single vertex stream; for multiple vertex streams, use meshopt_optimizeVertexFetchRemap + meshopt_remapVertexBuffer for each stream. * * destination must contain enough space for the resulting vertex buffer (vertex_count elements) * indices is used both as an input and as an output index buffer */ MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); /** * Vertex fetch cache optimizer * Generates vertex remap to reduce the amount of GPU memory fetches during vertex processing * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused * The resulting remap table should be used to reorder vertex/index buffers using meshopt_remapVertexBuffer/meshopt_remapIndexBuffer * * destination must contain enough space for the resulting remap table (vertex_count elements) */ MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count); /** * Index buffer encoder * Encodes index data into an array of bytes that is generally much smaller (<1.5 bytes/triangle) and compresses better (<1 bytes/triangle) compared to original. * Input index buffer must represent a triangle list. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space * For maximum efficiency the index buffer being encoded has to be optimized for vertex cache and vertex fetch first. * * buffer must contain enough space for the encoded index buffer (use meshopt_encodeIndexBufferBound to compute worst case size) */ MESHOPTIMIZER_API size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count); MESHOPTIMIZER_API size_t meshopt_encodeIndexBufferBound(size_t index_count, size_t vertex_count); /** * Set index encoder format version (defaults to 1) * * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.14+) */ MESHOPTIMIZER_API void meshopt_encodeIndexVersion(int version); /** * Index buffer decoder * Decodes index data from an array of bytes generated by meshopt_encodeIndexBuffer * Returns 0 if decoding was successful, and an error code otherwise * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices). * * destination must contain enough space for the resulting index buffer (index_count elements) */ MESHOPTIMIZER_API int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size); /** * Get encoded index format version * Returns format version of the encoded index buffer/sequence, or -1 if the buffer header is invalid * Note that a non-negative value doesn't guarantee that the buffer will be decoded correctly if the input is malformed. */ MESHOPTIMIZER_API int meshopt_decodeIndexVersion(const unsigned char* buffer, size_t buffer_size); /** * Index sequence encoder * Encodes index sequence into an array of bytes that is generally smaller and compresses better compared to original. * Input index sequence can represent arbitrary topology; for triangle lists meshopt_encodeIndexBuffer is likely to be better. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space * * buffer must contain enough space for the encoded index sequence (use meshopt_encodeIndexSequenceBound to compute worst case size) */ MESHOPTIMIZER_API size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count); MESHOPTIMIZER_API size_t meshopt_encodeIndexSequenceBound(size_t index_count, size_t vertex_count); /** * Index sequence decoder * Decodes index data from an array of bytes generated by meshopt_encodeIndexSequence * Returns 0 if decoding was successful, and an error code otherwise * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices). * * destination must contain enough space for the resulting index sequence (index_count elements) */ MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size); /** * Experimental: Meshlet encoder * Encodes meshlet data into an array of bytes that is generally smaller and compresses better compared to original. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space * This function encodes a single meshlet; when encoding multiple meshlets, additional headers may be necessary to store vertex/triangle count and encoded size. * For maximum efficiency the meshlet being encoded should be optimized using meshopt_optimizeMeshlet; additionally, vertex reference data should be optimized for locality (fetch). * * buffer must contain enough space for the encoded meshlet (use meshopt_encodeMeshletBound to compute worst case size) * vertices may be NULL, in which case vertex_count must be 0 and only triangle data is encoded * vertex_count and triangle_count must be <= 256. */ MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_encodeMeshlet(unsigned char* buffer, size_t buffer_size, const unsigned int* vertices, size_t vertex_count, const unsigned char* triangles, size_t triangle_count); MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_encodeMeshletBound(size_t max_vertices, size_t max_triangles); /** * Experimental: Meshlet decoder * Decodes meshlet data from an array of bytes generated by meshopt_encodeMeshlet * Returns 0 if decoding was successful, and an error code otherwise * The decoder is safe to use for untrusted input, but it may produce garbage data. * * vertices must contain enough space for the resulting vertex data, aligned to 4 bytes (align(vertex_count * vertex_size, 4) bytes) * vertex_size must be 2 (16-bit vertex references) or 4 (32-bit vertex references) * triangles must contain enough space for the resulting triangle data, aligned to 4 bytes (align(triangle_count * triangle_size, 4) bytes) * triangle_size must be 3 (8-bit triangle indices) or 4 (32-bit packed triangles, stored as (a) | (b << 8) | (c << 16)) * vertex_count, triangle_count match those used during encoding exactly; buffer_size must be equal to the encoded size returned by meshopt_encodeMeshlet. * vertices may be NULL, in which case vertex_count must be 0 and the meshlet must contain just triangle data * * When using "raw" decoding (meshopt_decodeMeshletRaw), both vertices and triangles should have available space further aligned to 16 bytes for efficient SIMD decoding. */ MESHOPTIMIZER_EXPERIMENTAL int meshopt_decodeMeshlet(void* vertices, size_t vertex_count, size_t vertex_size, void* triangles, size_t triangle_count, size_t triangle_size, const unsigned char* buffer, size_t buffer_size); MESHOPTIMIZER_EXPERIMENTAL int meshopt_decodeMeshletRaw(unsigned int* vertices, size_t vertex_count, unsigned int* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size); /** * Vertex buffer encoder * Encodes vertex data into an array of bytes that is generally smaller and compresses better compared to original. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space * This function works for a single vertex stream; for multiple vertex streams, call meshopt_encodeVertexBuffer for each stream. * Note that all vertex_size bytes of each vertex are encoded verbatim, including padding which should be zero-initialized. * For maximum efficiency the vertex buffer being encoded has to be quantized and optimized for locality of reference (cache/fetch) first. * * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size) * vertex_size must be a multiple of 4 (and <= 256) */ MESHOPTIMIZER_API size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size); MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size); /** * Vertex buffer encoder * Encodes vertex data just like meshopt_encodeVertexBuffer, but allows to override compression level. * For compression level to take effect, the vertex encoding version must be set to 1. * The default compression level implied by meshopt_encodeVertexBuffer is 2. * * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size) * vertex_size must be a multiple of 4 (and <= 256) * level should be in the range [0, 3] with 0 being the fastest and 3 being the slowest and producing the best compression ratio. * version should be -1 to use the default version (specified via meshopt_encodeVertexVersion), or 0/1 to override the version; per above, level won't take effect if version is 0. */ MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level, int version); /** * Set vertex encoder format version (defaults to 1) * * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.23+) */ MESHOPTIMIZER_API void meshopt_encodeVertexVersion(int version); /** * Vertex buffer decoder * Decodes vertex data from an array of bytes generated by meshopt_encodeVertexBuffer * Returns 0 if decoding was successful, and an error code otherwise * The decoder is safe to use for untrusted input, but it may produce garbage data. * * destination must contain enough space for the resulting vertex buffer (vertex_count * vertex_size bytes) * vertex_size must be a multiple of 4 (and <= 256) */ MESHOPTIMIZER_API int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t vertex_size, const unsigned char* buffer, size_t buffer_size); /** * Get encoded vertex format version * Returns format version of the encoded vertex buffer, or -1 if the buffer header is invalid * Note that a non-negative value doesn't guarantee that the buffer will be decoded correctly if the input is malformed. */ MESHOPTIMIZER_API int meshopt_decodeVertexVersion(const unsigned char* buffer, size_t buffer_size); /** * Vertex buffer filters * These functions can be used to filter output of meshopt_decodeVertexBuffer in-place. * * meshopt_decodeFilterOct decodes octahedral encoding of a unit vector with K-bit signed X/Y as an input; Z must store 1.0f. * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. W is preserved as is. * * meshopt_decodeFilterQuat decodes 3-component quaternion encoding with K-bit component encoding and a 2-bit component index indicating which component to reconstruct. * Each component is stored as an 16-bit integer; stride must be equal to 8. * * meshopt_decodeFilterExp decodes exponential encoding of floating-point data with 8-bit exponent and 24-bit integer mantissa as 2^E*M. * Each 32-bit component is decoded in isolation; stride must be divisible by 4. * * meshopt_decodeFilterColor decodes RGBA colors from YCoCg (+A) color encoding where RGB is converted to YCoCg space with K-bit component encoding, and A is stored using K-1 bits. * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. */ MESHOPTIMIZER_API void meshopt_decodeFilterOct(void* buffer, size_t count, size_t stride); MESHOPTIMIZER_API void meshopt_decodeFilterQuat(void* buffer, size_t count, size_t stride); MESHOPTIMIZER_API void meshopt_decodeFilterExp(void* buffer, size_t count, size_t stride); MESHOPTIMIZER_API void meshopt_decodeFilterColor(void* buffer, size_t count, size_t stride); /** * Vertex buffer filter encoders * These functions can be used to encode data in a format that meshopt_decodeFilter can decode * * meshopt_encodeFilterOct encodes unit vectors with K-bit (2 <= K <= 16) signed X/Y as an output. * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. Z will store 1.0f, W is preserved as is. * Input data must contain 4 floats for every vector (count*4 total). * * meshopt_encodeFilterQuat encodes unit quaternions with K-bit (4 <= K <= 16) component encoding. * Each component is stored as an 16-bit integer; stride must be equal to 8. * Input data must contain 4 floats for every quaternion (count*4 total). * * meshopt_encodeFilterExp encodes arbitrary (finite) floating-point data with 8-bit exponent and K-bit integer mantissa (1 <= K <= 24). * Exponent can be shared between all components of a given vector as defined by stride or all values of a given component; stride must be divisible by 4. * Input data must contain stride/4 floats for every vector (count*stride/4 total). * * meshopt_encodeFilterColor encodes RGBA color data by converting RGB to YCoCg color space with K-bit (2 <= K <= 16) component encoding; A is stored using K-1 bits. * Each component is stored as an 8-bit or 16-bit integer; stride must be equal to 4 or 8. * Input data must contain 4 floats for every color (count*4 total). */ enum meshopt_EncodeExpMode { /* When encoding exponents, use separate values for each component (maximum quality) */ meshopt_EncodeExpSeparate, /* When encoding exponents, use shared value for all components of each vector (better compression) */ meshopt_EncodeExpSharedVector, /* When encoding exponents, use shared value for each component of all vectors (best compression) */ meshopt_EncodeExpSharedComponent, /* When encoding exponents, use separate values for each component, but clamp to 0 (good quality if very small values are not important) */ meshopt_EncodeExpClamped, }; MESHOPTIMIZER_API void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data); MESHOPTIMIZER_API void meshopt_encodeFilterQuat(void* destination, size_t count, size_t stride, int bits, const float* data); MESHOPTIMIZER_API void meshopt_encodeFilterExp(void* destination, size_t count, size_t stride, int bits, const float* data, enum meshopt_EncodeExpMode mode); MESHOPTIMIZER_API void meshopt_encodeFilterColor(void* destination, size_t count, size_t stride, int bits, const float* data); /** * Simplification options */ enum { /* Do not move vertices that are located on the topological border (vertices on triangle edges that don't have a paired triangle). Useful for simplifying portions of the larger mesh. */ meshopt_SimplifyLockBorder = 1 << 0, /* Improve simplification performance assuming input indices are a sparse subset of the mesh. Note that error becomes relative to subset extents. */ meshopt_SimplifySparse = 1 << 1, /* Treat error limit and resulting error as absolute instead of relative to mesh extents. */ meshopt_SimplifyErrorAbsolute = 1 << 2, /* Remove disconnected parts of the mesh during simplification incrementally, regardless of the topological restrictions inside components. */ meshopt_SimplifyPrune = 1 << 3, /* Produce more regular triangle sizes and shapes during simplification, at some cost to geometric and attribute quality. */ meshopt_SimplifyRegularize = 1 << 4, /* Experimental: Allow collapses across attribute discontinuities, except for vertices that are tagged with meshopt_SimplifyVertex_Protect in vertex_lock. */ meshopt_SimplifyPermissive = 1 << 5, }; /** * Experimental: Simplification vertex flags/locks, for use in `vertex_lock` arrays in simplification APIs */ enum { /* Do not move this vertex. */ meshopt_SimplifyVertex_Lock = 1 << 0, /* Protect attribute discontinuity at this vertex; must be used together with meshopt_SimplifyPermissive option. */ meshopt_SimplifyVertex_Protect = 1 << 1, }; /** * Mesh simplifier * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. * Returns the number of indices after simplification, with destination containing new index data * * The resulting index buffer references vertices from the original vertex buffer. * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. * * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! * vertex_positions should have float3 position in the first 12 bytes of each vertex * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification */ MESHOPTIMIZER_API size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error); /** * Mesh simplifier with attribute metric * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible. * Similar to meshopt_simplify, but incorporates attribute values into the error metric used to prioritize simplification order. * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. * Returns the number of indices after simplification, with destination containing new index data * * The resulting index buffer references vertices from the original vertex buffer. * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. * Note that the number of attributes with non-zero weights affects memory requirements and running time. * * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! * vertex_positions should have float3 position in the first 12 bytes of each vertex * vertex_attributes should have attribute_count floats for each vertex * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position * attribute_count must be <= 32 * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; 1 denotes vertices that can't be moved * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification */ MESHOPTIMIZER_API size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error); /** * Mesh simplifier with position/attribute update * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible. * Similar to meshopt_simplifyWithAttributes, but destructively updates positions and attribute values for optimal appearance. * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error. * If not all attributes from the input mesh are needed, it's recommended to reindex the mesh without them prior to simplification. * Returns the number of indices after simplification, indices are destructively updated with new index data * * The updated index buffer references vertices from the original vertex buffer, however the vertex positions and attributes are updated in-place. * Creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended; if the original vertex data is needed, it should be copied before simplification. * Note that the number of attributes with non-zero weights affects memory requirements and running time. Attributes with zero weights are not updated. * * vertex_positions should have float3 position in the first 12 bytes of each vertex * vertex_attributes should have attribute_count floats for each vertex * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position * attribute_count must be <= 32 * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; 1 denotes vertices that can't be moved * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification */ MESHOPTIMIZER_API size_t meshopt_simplifyWithUpdate(unsigned int* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error); /** * Mesh simplifier (sloppy) * Reduces the number of triangles in the mesh, sacrificing mesh appearance for simplification performance * The algorithm doesn't preserve mesh topology but can stop short of the target goal based on target error. * Returns the number of indices after simplification, with destination containing new index data * The resulting index buffer references vertices from the original vertex buffer. * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. * * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)! * vertex_positions should have float3 position in the first 12 bytes of each vertex * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; vertices that can't be moved should set 1 consistently for all indices with the same position * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification */ MESHOPTIMIZER_API size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error); /** * Mesh simplifier (pruner) * Reduces the number of triangles in the mesh by removing small isolated parts of the mesh * Returns the number of indices after simplification, with destination containing new index data * The resulting index buffer references vertices from the original vertex buffer. * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. * * destination must contain enough space for the target index buffer, worst case is index_count elements * vertex_positions should have float3 position in the first 12 bytes of each vertex * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1] */ MESHOPTIMIZER_API size_t meshopt_simplifyPrune(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error); /** * Point cloud simplifier * Reduces the number of points in the cloud to reach the given target * Returns the number of points after simplification, with destination containing new index data * The resulting index buffer references vertices from the original vertex buffer. * If the original vertex data isn't needed, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended. * * destination must contain enough space for the target index buffer (target_vertex_count elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex * vertex_colors can be NULL; when it's not NULL, it should have float3 color in the first 12 bytes of each vertex * color_weight determines relative priority of color wrt position; 1.0 is a safe default */ MESHOPTIMIZER_API size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count); /** * Returns the error scaling factor used by the simplifier to convert between absolute and relative extents * * Absolute error must be *divided* by the scaling factor before passing it to meshopt_simplify as target_error * Relative error returned by meshopt_simplify via result_error must be *multiplied* by the scaling factor to get absolute error. */ MESHOPTIMIZER_API float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Mesh stripifier * Converts a previously vertex cache optimized triangle list to triangle strip, stitching strips using restart index or degenerate triangles * Returns the number of indices in the resulting strip, with destination containing new index data * For maximum efficiency the index buffer being converted has to be optimized for vertex cache first. * Using restart indices can result in ~10% smaller index buffers, but on some GPUs restart indices may result in decreased performance. * * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_stripifyBound * restart_index should be 0xffff or 0xffffffff depending on index size, or 0 to use degenerate triangles */ MESHOPTIMIZER_API size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index); MESHOPTIMIZER_API size_t meshopt_stripifyBound(size_t index_count); /** * Mesh unstripifier * Converts a triangle strip to a triangle list * Returns the number of indices in the resulting list, with destination containing new index data * * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_unstripifyBound */ MESHOPTIMIZER_API size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index); MESHOPTIMIZER_API size_t meshopt_unstripifyBound(size_t index_count); struct meshopt_VertexCacheStatistics { unsigned int vertices_transformed; unsigned int warps_executed; float acmr; /* transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology */ float atvr; /* transformed vertices / vertex count; best case 1.0, worst case 6.0, optimum is 1.0 (each vertex is transformed once) */ }; /** * Vertex transform cache analyzer * Returns cache hit statistics using a simplified FIFO model * Results may not match actual GPU performance */ MESHOPTIMIZER_API struct meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size); struct meshopt_VertexFetchStatistics { unsigned int bytes_fetched; float overfetch; /* fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) */ }; /** * Vertex fetch cache analyzer * Returns cache hit statistics using a simplified direct mapped model * Results may not match actual GPU performance */ MESHOPTIMIZER_API struct meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size); struct meshopt_OverdrawStatistics { unsigned int pixels_covered; unsigned int pixels_shaded; float overdraw; /* shaded pixels / covered pixels; best case 1.0 */ }; /** * Overdraw analyzer * Returns overdraw statistics using a software rasterizer * Results may not match actual GPU performance * * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API struct meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); struct meshopt_CoverageStatistics { float coverage[3]; float extent; /* viewport size in mesh coordinates */ }; /** * Coverage analyzer * Returns coverage statistics (ratio of viewport pixels covered from each axis) using a software rasterizer * * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API struct meshopt_CoverageStatistics meshopt_analyzeCoverage(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Meshlet is a small mesh cluster (subset) that consists of: * - triangles, an 8-bit micro triangle (index) buffer, that for each triangle specifies three local vertices to use; * - vertices, a 32-bit vertex indirection buffer, that for each local vertex specifies which mesh vertex to fetch vertex attributes from. * * For efficiency, meshlet triangles and vertices are packed into two large arrays; this structure contains offsets and counts to access the data. */ struct meshopt_Meshlet { /* offsets within meshlet_vertices and meshlet_triangles arrays with meshlet data */ unsigned int vertex_offset; unsigned int triangle_offset; /* number of vertices and triangles used in the meshlet; data is stored in consecutive range [offset..offset+count) for vertices and [offset..offset+count*3) for triangles */ unsigned int vertex_count; unsigned int triangle_count; }; /** * Meshlet builder * Splits the mesh into a set of meshlets where each meshlet has a micro index buffer indexing into meshlet vertices that refer to the original vertex buffer * The resulting data can be used to render meshes using NVidia programmable mesh shading pipeline, or in other cluster-based renderers. * When targeting mesh shading hardware, for maximum efficiency meshlets should be further optimized using meshopt_optimizeMeshlet. * When using buildMeshlets, vertex positions need to be provided to minimize the size of the resulting clusters. * When using buildMeshletsScan, for maximum efficiency the index buffer being converted has to be optimized for vertex cache first. * * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements * vertex_positions should have float3 position in the first 12 bytes of each vertex * max_vertices and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512) * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency */ MESHOPTIMIZER_API size_t meshopt_buildMeshlets(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight); MESHOPTIMIZER_API size_t meshopt_buildMeshletsScan(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles); MESHOPTIMIZER_API size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles); /** * Meshlet builder with flexible cluster sizes * Splits the mesh into a set of meshlets, similarly to meshopt_buildMeshlets, but allows to specify minimum and maximum number of triangles per meshlet. * Clusters between min and max triangle counts are split when the cluster size would have exceeded the expected cluster size by more than split_factor. * * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound using min_triangles (*not* max!) * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements * vertex_positions should have float3 position in the first 12 bytes of each vertex * max_vertices, min_triangles and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512; min_triangles <= max_triangles) * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency * split_factor should be set to a non-negative value; when greater than 0, clusters that have large bounds may be split unless they are under the min_triangles threshold */ MESHOPTIMIZER_API size_t meshopt_buildMeshletsFlex(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor); /** * Meshlet builder that produces clusters optimized for raytracing * Splits the mesh into a set of meshlets, similarly to meshopt_buildMeshlets, but optimizes cluster subdivision for raytracing and allows to specify minimum and maximum number of triangles per meshlet. * * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound using min_triangles (*not* max!) * meshlet_vertices must contain enough space for all meshlets, worst case is index_count elements (*not* vertex_count!) * meshlet_triangles must contain enough space for all meshlets, worst case is index_count elements * vertex_positions should have float3 position in the first 12 bytes of each vertex * max_vertices, min_triangles and max_triangles must not exceed implementation limits (max_vertices <= 256, max_triangles <= 512; min_triangles <= max_triangles) * fill_weight allows to prioritize clusters that are closer to maximum size at some cost to SAH quality; 0.5 is a safe default */ MESHOPTIMIZER_API size_t meshopt_buildMeshletsSpatial(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight); /** * Meshlet optimizer * Reorders meshlet vertices and triangles to maximize locality which can improve rasterizer throughput or ray tracing performance when using fast-build modes. * * meshlet_triangles and meshlet_vertices must refer to meshlet data; when buildMeshlets* is used, these need to be computed from meshlet's vertex_offset and triangle_offset * triangle_count and vertex_count must not exceed implementation limits (vertex_count <= 256, triangle_count <= 512) */ MESHOPTIMIZER_API void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count); struct meshopt_Bounds { /* bounding sphere, useful for frustum and occlusion culling */ float center[3]; float radius; /* normal cone, useful for backface culling */ float cone_apex[3]; float cone_axis[3]; float cone_cutoff; /* = cos(angle/2) */ /* normal cone axis and cutoff, stored in 8-bit SNORM format; decode using x/127.0 */ signed char cone_axis_s8[3]; signed char cone_cutoff_s8; }; /** * Cluster bounds generator * Creates bounding volumes that can be used for frustum, backface and occlusion culling. * * For backface culling with orthographic projection, use the following formula to reject backfacing clusters: * dot(view, cone_axis) >= cone_cutoff * * For perspective projection, you can use the formula that needs cone apex in addition to axis & cutoff: * dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff * * Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead: * dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position) * or an equivalent formula that doesn't have a singularity at center = camera_position: * dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius * * The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere * to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable (for derivation see * Real-Time Rendering 4th Edition, section 19.3). * * vertex_positions should have float3 position in the first 12 bytes of each vertex * vertex_count should specify the number of vertices in the entire mesh, not cluster or meshlet * index_count/3 and triangle_count must not exceed implementation limits (<= 512) */ MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Sphere bounds generator * Creates bounding sphere around a set of points or a set of spheres; returns the center and radius of the sphere, with other fields of the result set to 0. * * positions should have float3 position in the first 12 bytes of each element * radii can be NULL; when it's not NULL, it should have a non-negative float radius in the first 4 bytes of each element */ MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeSphereBounds(const float* positions, size_t count, size_t positions_stride, const float* radii, size_t radii_stride); /** * Cluster partitioner * Partitions clusters into groups of similar size, prioritizing grouping clusters that share vertices or are close to each other. * When vertex positions are not provided, only clusters that share vertices will be grouped together, which may result in small partitions for some inputs. * * destination must contain enough space for the resulting partition data (cluster_count elements) * destination[i] will contain the partition id for cluster i, with the total number of partitions returned by the function * cluster_indices should have the vertex indices referenced by each cluster, stored sequentially * cluster_index_counts should have the number of indices in each cluster; sum of all cluster_index_counts must be equal to total_index_count * vertex_positions can be NULL; when it's not NULL, it should have float3 position in the first 12 bytes of each vertex * target_partition_size is a target size for each partition, in clusters; the resulting partitions may be smaller or larger (up to target + target/3) */ MESHOPTIMIZER_API size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size); /** * Spatial sorter * Generates a remap table that can be used to reorder points for spatial locality. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer. * * destination must contain enough space for the resulting remap table (vertex_count elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Spatial sorter * Reorders triangles for spatial locality, and generates a new index buffer. The resulting index buffer can be used with other functions like optimizeVertexCache. * * destination must contain enough space for the resulting index buffer (index_count elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_spatialSortTriangles(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); /** * Spatial clusterizer * Reorders points into clusters optimized for spatial locality, and generates a new index buffer. * Ensures the output can be split into cluster_size chunks where each chunk has good positional locality. Only the last chunk will be smaller than cluster_size. * * destination must contain enough space for the resulting index buffer (vertex_count elements) * vertex_positions should have float3 position in the first 12 bytes of each vertex */ MESHOPTIMIZER_API void meshopt_spatialClusterPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t cluster_size); /** * Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest * Representable magnitude range: [6e-5; 65504] * Maximum relative reconstruction error: 5e-4 */ MESHOPTIMIZER_API unsigned short meshopt_quantizeHalf(float v); /** * Quantize a float into a floating point value with a limited number of significant mantissa bits, preserving the IEEE-754 fp32 binary representation * Preserves infinities/NaN, flushes denormals to zero, rounds to nearest * Assumes N is in a valid mantissa precision range, which is 1..23 */ MESHOPTIMIZER_API float meshopt_quantizeFloat(float v, int N); /** * Reverse quantization of a half-precision (as defined by IEEE-754 fp16) floating point value * Preserves Inf/NaN, flushes denormals to zero */ MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h); /** * Set allocation callbacks * These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library. * Note that all algorithms only allocate memory for temporary use. * allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first. */ MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*)); #ifdef __cplusplus } /* extern "C" */ #endif /* Quantization into fixed point normalized formats; these are only available as inline C++ functions */ #ifdef __cplusplus /** * Quantize a float in [0..1] range into an N-bit fixed point unorm value * Assumes reconstruction function (q / (2^N-1)), which is the case for fixed-function normalized fixed point conversion * Maximum reconstruction error: 1/2^(N+1) */ inline int meshopt_quantizeUnorm(float v, int N); /** * Quantize a float in [-1..1] range into an N-bit fixed point snorm value * Assumes reconstruction function (q / (2^(N-1)-1)), which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions) * Maximum reconstruction error: 1/2^N */ inline int meshopt_quantizeSnorm(float v, int N); #endif /** * C++ template interface * * These functions mirror the C interface the library provides, providing template-based overloads so that * the caller can use an arbitrary type for the index data, both for input and output. * When the supplied type is the same size as that of unsigned int, the wrappers are zero-cost; when it's not, * the wrappers end up allocating memory and copying index data to convert from one type to another. */ #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS) template <typename T> inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); template <typename T> inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count); template <typename F> inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback); template <typename T, typename F> inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback); template <typename T> inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap); template <typename T> inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride); template <typename T> inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count); template <typename T> inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); template <typename T> inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); template <typename T> inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count); template <typename T> inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count); template <typename T> inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count); template <typename T> inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size); template <typename T> inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold); template <typename T> inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count); template <typename T> inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size); template <typename T> inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count); template <typename T> inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size); template <typename T> inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count); template <typename T> inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size); template <typename V, typename T> inline int meshopt_decodeMeshlet(V* vertices, size_t vertex_count, T* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size); inline size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level); template <typename T> inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); template <typename T> inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); template <typename T> inline size_t meshopt_simplifyWithUpdate(T* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL); template <typename T> inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error = NULL); template <typename T> inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error = NULL); template <typename T> inline size_t meshopt_simplifyPrune(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error); template <typename T> inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index); template <typename T> inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index); template <typename T> inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size); template <typename T> inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size); template <typename T> inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); template <typename T> inline meshopt_CoverageStatistics meshopt_analyzeCoverage(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); template <typename T> inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight); template <typename T> inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles); template <typename T> inline size_t meshopt_buildMeshletsFlex(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor); template <typename T> inline size_t meshopt_buildMeshletsSpatial(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight); template <typename T> inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); template <typename T> inline size_t meshopt_partitionClusters(unsigned int* destination, const T* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size); template <typename T> inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride); #endif /* Inline implementation */ #ifdef __cplusplus inline int meshopt_quantizeUnorm(float v, int N) { const float scale = float((1 << N) - 1); v = (v >= 0) ? v : 0; v = (v <= 1) ? v : 1; return int(v * scale + 0.5f); } inline int meshopt_quantizeSnorm(float v, int N) { const float scale = float((1 << (N - 1)) - 1); float round = (v >= 0 ? 0.5f : -0.5f); v = (v >= -1) ? v : -1; v = (v <= +1) ? v : +1; return int(v * scale + round); } #endif /* Internal implementation helpers */ #ifdef __cplusplus class meshopt_Allocator { public: struct Storage { void* (MESHOPTIMIZER_ALLOC_CALLCONV* allocate)(size_t); void (MESHOPTIMIZER_ALLOC_CALLCONV* deallocate)(void*); }; #ifdef MESHOPTIMIZER_ALLOC_EXPORT MESHOPTIMIZER_API static Storage& storage(); #else static Storage& storage() { static Storage s = {::operator new, ::operator delete }; return s; } #endif meshopt_Allocator() : blocks() , count(0) { } ~meshopt_Allocator() { for (size_t i = count; i > 0; --i) storage().deallocate(blocks[i - 1]); } template <typename T> T* allocate(size_t size) { assert(count < sizeof(blocks) / sizeof(blocks[0])); T* result = static_cast<T*>(storage().allocate(size > size_t(-1) / sizeof(T) ? size_t(-1) : size * sizeof(T))); blocks[count++] = result; return result; } void deallocate(void* ptr) { assert(count > 0 && blocks[count - 1] == ptr); storage().deallocate(ptr); count--; } private: void* blocks[24]; size_t count; }; #endif /* Inline implementation for C++ templated wrappers */ #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS) template <typename T, bool ZeroCopy = sizeof(T) == sizeof(unsigned int)> struct meshopt_IndexAdapter; template <typename T> struct meshopt_IndexAdapter<T, false> { T* result; unsigned int* data; size_t count; meshopt_IndexAdapter(T* result_, const T* input, size_t count_) : result(result_) , data(NULL) , count(count_) { size_t size = count > size_t(-1) / sizeof(unsigned int) ? size_t(-1) : count * sizeof(unsigned int); data = static_cast<unsigned int*>(meshopt_Allocator::storage().allocate(size)); if (input) { for (size_t i = 0; i < count; ++i) data[i] = input[i]; } } ~meshopt_IndexAdapter() { if (result) { for (size_t i = 0; i < count; ++i) result[i] = T(data[i]); } meshopt_Allocator::storage().deallocate(data); } }; template <typename T> struct meshopt_IndexAdapter<T, true> { unsigned int* data; meshopt_IndexAdapter(T* result, const T* input, size_t) : data(reinterpret_cast<unsigned int*>(result ? result : const_cast<T*>(input))) { } }; template <typename T> inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) { meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0); return meshopt_generateVertexRemap(destination, indices ? in.data : NULL, index_count, vertices, vertex_count, vertex_size); } template <typename T> inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count) { meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0); return meshopt_generateVertexRemapMulti(destination, indices ? in.data : NULL, index_count, vertex_count, streams, stream_count); } template <typename F> inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback) { struct Call { static int compare(void* context, unsigned int lhs, unsigned int rhs) { return (*static_cast<F*>(context))(lhs, rhs) ? 1 : 0; } }; return meshopt_generateVertexRemapCustom(destination, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, &Call::compare, &callback); } template <typename T, typename F> inline size_t meshopt_generateVertexRemapCustom(unsigned int* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, F callback) { struct Call { static int compare(void* context, unsigned int lhs, unsigned int rhs) { return (*static_cast<F*>(context))(lhs, rhs) ? 1 : 0; } }; meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0); return meshopt_generateVertexRemapCustom(destination, indices ? in.data : NULL, index_count, vertex_positions, vertex_count, vertex_positions_stride, &Call::compare, &callback); } template <typename T> inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap) { meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0); meshopt_IndexAdapter<T> out(destination, 0, index_count); meshopt_remapIndexBuffer(out.data, indices ? in.data : NULL, index_count, remap); } template <typename T> inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_generateShadowIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride); } template <typename T> inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_generateShadowIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count); } template <typename T> inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count * 2); meshopt_generateAdjacencyIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } template <typename T> inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count * 4); meshopt_generateTessellationIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } template <typename T> inline size_t meshopt_generateProvokingIndexBuffer(T* destination, unsigned int* reorder, const T* indices, size_t index_count, size_t vertex_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); size_t bound = vertex_count + (index_count / 3); assert(size_t(T(bound - 1)) == bound - 1); // bound - 1 must fit in T (void)bound; return meshopt_generateProvokingIndexBuffer(out.data, reorder, in.data, index_count, vertex_count); } template <typename T> inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_optimizeVertexCache(out.data, in.data, index_count, vertex_count); } template <typename T> inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_optimizeVertexCacheStrip(out.data, in.data, index_count, vertex_count); } template <typename T> inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_optimizeVertexCacheFifo(out.data, in.data, index_count, vertex_count, cache_size); } template <typename T> inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_optimizeOverdraw(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, threshold); } template <typename T> inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_optimizeVertexFetchRemap(destination, in.data, index_count, vertex_count); } template <typename T> inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) { meshopt_IndexAdapter<T> inout(indices, indices, index_count); return meshopt_optimizeVertexFetch(destination, inout.data, index_count, vertices, vertex_count, vertex_size); } template <typename T> inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_encodeIndexBuffer(buffer, buffer_size, in.data, index_count); } template <typename T> inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size) { char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1]; (void)index_size_valid; return meshopt_decodeIndexBuffer(destination, index_count, sizeof(T), buffer, buffer_size); } template <typename T> inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_encodeIndexSequence(buffer, buffer_size, in.data, index_count); } template <typename T> inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size) { char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1]; (void)index_size_valid; return meshopt_decodeIndexSequence(destination, index_count, sizeof(T), buffer, buffer_size); } template <typename V, typename T> inline int meshopt_decodeMeshlet(V* vertices, size_t vertex_count, T* triangles, size_t triangle_count, const unsigned char* buffer, size_t buffer_size) { char types_valid[(sizeof(V) == 2 || sizeof(V) == 4) && (sizeof(T) == 1 || sizeof(T) == 4) ? 1 : -1]; (void)types_valid; return meshopt_decodeMeshlet(vertices, vertex_count, sizeof(V), triangles, triangle_count, sizeof(T) == 1 ? 3 : 4, buffer, buffer_size); } inline size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level) { return meshopt_encodeVertexBufferLevel(buffer, buffer_size, vertices, vertex_count, vertex_size, level, -1); } template <typename T> inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); return meshopt_simplify(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options, result_error); } template <typename T> inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); return meshopt_simplifyWithAttributes(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error); } template <typename T> inline size_t meshopt_simplifyWithUpdate(T* indices, size_t index_count, float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error) { meshopt_IndexAdapter<T> inout(indices, indices, index_count); return meshopt_simplifyWithUpdate(inout.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error); } template <typename T> inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, NULL, target_index_count, target_error, result_error); } template <typename T> inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* result_error) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_lock, target_index_count, target_error, result_error); } template <typename T> inline size_t meshopt_simplifyPrune(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float target_error) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); return meshopt_simplifyPrune(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_error); } template <typename T> inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, (index_count / 3) * 5); return meshopt_stripify(out.data, in.data, index_count, vertex_count, unsigned(restart_index)); } template <typename T> inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, (index_count - 2) * 3); return meshopt_unstripify(out.data, in.data, index_count, unsigned(restart_index)); } template <typename T> inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_analyzeVertexCache(in.data, index_count, vertex_count, cache_size, warp_size, primgroup_size); } template <typename T> inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_analyzeVertexFetch(in.data, index_count, vertex_count, vertex_size); } template <typename T> inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_analyzeOverdraw(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } template <typename T> inline meshopt_CoverageStatistics meshopt_analyzeCoverage(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_analyzeCoverage(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } template <typename T> inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_buildMeshlets(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, max_triangles, cone_weight); } template <typename T> inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_buildMeshletsScan(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_count, max_vertices, max_triangles); } template <typename T> inline size_t meshopt_buildMeshletsFlex(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float cone_weight, float split_factor) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_buildMeshletsFlex(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, min_triangles, max_triangles, cone_weight, split_factor); } template <typename T> inline size_t meshopt_buildMeshletsSpatial(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t min_triangles, size_t max_triangles, float fill_weight) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_buildMeshletsSpatial(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, min_triangles, max_triangles, fill_weight); } template <typename T> inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); return meshopt_computeClusterBounds(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } template <typename T> inline size_t meshopt_partitionClusters(unsigned int* destination, const T* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size) { meshopt_IndexAdapter<T> in(NULL, cluster_indices, total_index_count); return meshopt_partitionClusters(destination, in.data, total_index_count, cluster_index_counts, cluster_count, vertex_positions, vertex_count, vertex_positions_stride, target_partition_size); } template <typename T> inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { meshopt_IndexAdapter<T> in(NULL, indices, index_count); meshopt_IndexAdapter<T> out(destination, NULL, index_count); meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride); } #endif /** * Copyright (c) 2016-2026 Arseny Kapoulkine * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/overdrawoptimizer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <math.h> #include <string.h> // This work is based on: // Pedro Sander, Diego Nehab and Joshua Barczak. Fast Triangle Reordering for Vertex Locality and Reduced Overdraw. 2007 namespace meshopt { static void calculateSortData(float* sort_data, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* clusters, size_t cluster_count) { size_t vertex_stride_float = vertex_positions_stride / sizeof(float); float mesh_centroid[3] = {}; for (size_t i = 0; i < vertex_count; ++i) { const float* p = vertex_positions + vertex_stride_float * i; mesh_centroid[0] += p[0]; mesh_centroid[1] += p[1]; mesh_centroid[2] += p[2]; } mesh_centroid[0] /= float(vertex_count); mesh_centroid[1] /= float(vertex_count); mesh_centroid[2] /= float(vertex_count); for (size_t cluster = 0; cluster < cluster_count; ++cluster) { size_t cluster_begin = clusters[cluster] * 3; size_t cluster_end = (cluster + 1 < cluster_count) ? clusters[cluster + 1] * 3 : index_count; assert(cluster_begin < cluster_end); float cluster_area = 0; float cluster_centroid[3] = {}; float cluster_normal[3] = {}; for (size_t i = cluster_begin; i < cluster_end; i += 3) { const float* p0 = vertex_positions + vertex_stride_float * indices[i + 0]; const float* p1 = vertex_positions + vertex_stride_float * indices[i + 1]; const float* p2 = vertex_positions + vertex_stride_float * indices[i + 2]; float p10[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]}; float p20[3] = {p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]}; float normalx = p10[1] * p20[2] - p10[2] * p20[1]; float normaly = p10[2] * p20[0] - p10[0] * p20[2]; float normalz = p10[0] * p20[1] - p10[1] * p20[0]; float area = sqrtf(normalx * normalx + normaly * normaly + normalz * normalz); cluster_centroid[0] += (p0[0] + p1[0] + p2[0]) * (area / 3); cluster_centroid[1] += (p0[1] + p1[1] + p2[1]) * (area / 3); cluster_centroid[2] += (p0[2] + p1[2] + p2[2]) * (area / 3); cluster_normal[0] += normalx; cluster_normal[1] += normaly; cluster_normal[2] += normalz; cluster_area += area; } float inv_cluster_area = cluster_area == 0 ? 0 : 1 / cluster_area; cluster_centroid[0] *= inv_cluster_area; cluster_centroid[1] *= inv_cluster_area; cluster_centroid[2] *= inv_cluster_area; float cluster_normal_length = sqrtf(cluster_normal[0] * cluster_normal[0] + cluster_normal[1] * cluster_normal[1] + cluster_normal[2] * cluster_normal[2]); float inv_cluster_normal_length = cluster_normal_length == 0 ? 0 : 1 / cluster_normal_length; cluster_normal[0] *= inv_cluster_normal_length; cluster_normal[1] *= inv_cluster_normal_length; cluster_normal[2] *= inv_cluster_normal_length; float centroid_vector[3] = {cluster_centroid[0] - mesh_centroid[0], cluster_centroid[1] - mesh_centroid[1], cluster_centroid[2] - mesh_centroid[2]}; sort_data[cluster] = centroid_vector[0] * cluster_normal[0] + centroid_vector[1] * cluster_normal[1] + centroid_vector[2] * cluster_normal[2]; } } static void calculateSortOrderRadix(unsigned int* sort_order, const float* sort_data, unsigned short* sort_keys, size_t cluster_count) { // compute sort data bounds and renormalize, using fixed point snorm float sort_data_max = 1e-3f; for (size_t i = 0; i < cluster_count; ++i) { float dpa = fabsf(sort_data[i]); sort_data_max = (sort_data_max < dpa) ? dpa : sort_data_max; } const int sort_bits = 11; for (size_t i = 0; i < cluster_count; ++i) { // note that we flip distribution since high dot product should come first float sort_key = 0.5f - 0.5f * (sort_data[i] / sort_data_max); sort_keys[i] = meshopt_quantizeUnorm(sort_key, sort_bits) & ((1 << sort_bits) - 1); } // fill histogram for counting sort unsigned int histogram[1 << sort_bits]; memset(histogram, 0, sizeof(histogram)); for (size_t i = 0; i < cluster_count; ++i) { histogram[sort_keys[i]]++; } // compute offsets based on histogram data size_t histogram_sum = 0; for (size_t i = 0; i < 1 << sort_bits; ++i) { size_t count = histogram[i]; histogram[i] = unsigned(histogram_sum); histogram_sum += count; } assert(histogram_sum == cluster_count); // compute sort order based on offsets for (size_t i = 0; i < cluster_count; ++i) { sort_order[histogram[sort_keys[i]]++] = unsigned(i); } } static unsigned int updateCache(unsigned int a, unsigned int b, unsigned int c, unsigned int cache_size, unsigned int* cache_timestamps, unsigned int& timestamp) { unsigned int cache_misses = 0; // if vertex is not in cache, put it in cache if (timestamp - cache_timestamps[a] > cache_size) { cache_timestamps[a] = timestamp++; cache_misses++; } if (timestamp - cache_timestamps[b] > cache_size) { cache_timestamps[b] = timestamp++; cache_misses++; } if (timestamp - cache_timestamps[c] > cache_size) { cache_timestamps[c] = timestamp++; cache_misses++; } return cache_misses; } static size_t generateHardBoundaries(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int* cache_timestamps) { memset(cache_timestamps, 0, vertex_count * sizeof(unsigned int)); unsigned int timestamp = cache_size + 1; size_t face_count = index_count / 3; size_t result = 0; for (size_t i = 0; i < face_count; ++i) { unsigned int m = updateCache(indices[i * 3 + 0], indices[i * 3 + 1], indices[i * 3 + 2], cache_size, &cache_timestamps[0], timestamp); // when all three vertices are not in the cache it's usually relatively safe to assume that this is a new patch in the mesh // that is disjoint from previous vertices; sometimes it might come back to reference existing vertices but that frequently // suggests an inefficiency in the vertex cache optimization algorithm // usually the first triangle has 3 misses unless it's degenerate - thus we make sure the first cluster always starts with 0 if (i == 0 || m == 3) { destination[result++] = unsigned(i); } } assert(result <= index_count / 3); return result; } static size_t generateSoftBoundaries(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* clusters, size_t cluster_count, unsigned int cache_size, float threshold, unsigned int* cache_timestamps) { memset(cache_timestamps, 0, vertex_count * sizeof(unsigned int)); unsigned int timestamp = 0; size_t result = 0; for (size_t it = 0; it < cluster_count; ++it) { size_t start = clusters[it]; size_t end = (it + 1 < cluster_count) ? clusters[it + 1] : index_count / 3; assert(start < end); // reset cache timestamp += cache_size + 1; // measure cluster ACMR unsigned int cluster_misses = 0; for (size_t i = start; i < end; ++i) { unsigned int m = updateCache(indices[i * 3 + 0], indices[i * 3 + 1], indices[i * 3 + 2], cache_size, &cache_timestamps[0], timestamp); cluster_misses += m; } float cluster_threshold = threshold * (float(cluster_misses) / float(end - start)); // first cluster always starts from the hard cluster boundary destination[result++] = unsigned(start); // reset cache timestamp += cache_size + 1; unsigned int running_misses = 0; unsigned int running_faces = 0; for (size_t i = start; i < end; ++i) { unsigned int m = updateCache(indices[i * 3 + 0], indices[i * 3 + 1], indices[i * 3 + 2], cache_size, &cache_timestamps[0], timestamp); running_misses += m; running_faces += 1; if (float(running_misses) / float(running_faces) <= cluster_threshold) { // we have reached the target ACMR with the current triangle so we need to start a new cluster on the next one // note that this may mean that we add 'end` to destination for the last triangle, which will imply that the last // cluster is empty; however, the 'pop_back' after the loop will clean it up destination[result++] = unsigned(i + 1); // reset cache timestamp += cache_size + 1; running_misses = 0; running_faces = 0; } } // each time we reach the target ACMR we flush the cluster // this means that the last cluster is by definition not very good - there are frequent cases where we are left with a few triangles // in the last cluster, producing a very bad ACMR and significantly penalizing the overall results // thus we remove the last cluster boundary, merging the last complete cluster with the last incomplete one // there are sometimes cases when the last cluster is actually good enough - in which case the code above would have added 'end' // to the cluster boundary array which we need to remove anyway - this code will do that automatically if (destination[result - 1] != start) { result--; } } assert(result >= cluster_count); assert(result <= index_count / 3); return result; } } // namespace meshopt void meshopt_optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; // guard for empty meshes if (index_count == 0 || vertex_count == 0) return; // support in-place optimization if (destination == indices) { unsigned int* indices_copy = allocator.allocate<unsigned int>(index_count); memcpy(indices_copy, indices, index_count * sizeof(unsigned int)); indices = indices_copy; } unsigned int cache_size = 16; unsigned int* cache_timestamps = allocator.allocate<unsigned int>(vertex_count); // generate hard boundaries from full-triangle cache misses unsigned int* hard_clusters = allocator.allocate<unsigned int>(index_count / 3); size_t hard_cluster_count = generateHardBoundaries(hard_clusters, indices, index_count, vertex_count, cache_size, cache_timestamps); // generate soft boundaries unsigned int* soft_clusters = allocator.allocate<unsigned int>(index_count / 3 + 1); size_t soft_cluster_count = generateSoftBoundaries(soft_clusters, indices, index_count, vertex_count, hard_clusters, hard_cluster_count, cache_size, threshold, cache_timestamps); const unsigned int* clusters = soft_clusters; size_t cluster_count = soft_cluster_count; // fill sort data float* sort_data = allocator.allocate<float>(cluster_count); calculateSortData(sort_data, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride, clusters, cluster_count); // sort clusters using sort data unsigned short* sort_keys = allocator.allocate<unsigned short>(cluster_count); unsigned int* sort_order = allocator.allocate<unsigned int>(cluster_count); calculateSortOrderRadix(sort_order, sort_data, sort_keys, cluster_count); // fill output buffer size_t offset = 0; for (size_t it = 0; it < cluster_count; ++it) { unsigned int cluster = sort_order[it]; assert(cluster < cluster_count); size_t cluster_begin = clusters[cluster] * 3; size_t cluster_end = (cluster + 1 < cluster_count) ? clusters[cluster + 1] * 3 : index_count; assert(cluster_begin < cluster_end); memcpy(destination + offset, indices + cluster_begin, (cluster_end - cluster_begin) * sizeof(unsigned int)); offset += cluster_end - cluster_begin; } assert(offset == index_count); }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/partition.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <math.h> #include <string.h> // This work is based on: // Takio Kurita. An efficient agglomerative clustering algorithm using a heap. 1991 namespace meshopt { // To avoid excessive recursion for malformed inputs, we switch to bisection after some depth const int kMergeDepthCutoff = 40; struct ClusterAdjacency { unsigned int* offsets; unsigned int* clusters; unsigned int* shared; }; static void filterClusterIndices(unsigned int* data, unsigned int* offsets, const unsigned int* cluster_indices, const unsigned int* cluster_index_counts, size_t cluster_count, unsigned char* used, size_t vertex_count, size_t total_index_count) { (void)vertex_count; (void)total_index_count; size_t cluster_start = 0; size_t cluster_write = 0; for (size_t i = 0; i < cluster_count; ++i) { offsets[i] = unsigned(cluster_write); // copy cluster indices, skipping duplicates for (size_t j = 0; j < cluster_index_counts[i]; ++j) { unsigned int v = cluster_indices[cluster_start + j]; assert(v < vertex_count); data[cluster_write] = v; cluster_write += 1 - used[v]; used[v] = 1; } // reset used flags for the next cluster for (size_t j = offsets[i]; j < cluster_write; ++j) used[data[j]] = 0; cluster_start += cluster_index_counts[i]; } assert(cluster_start == total_index_count); assert(cluster_write <= total_index_count); offsets[cluster_count] = unsigned(cluster_write); } static float computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_positions_stride, float* out_center) { size_t vertex_stride_float = vertex_positions_stride / sizeof(float); float center[3] = {0, 0, 0}; // approximate center of the cluster by averaging all vertex positions for (size_t j = 0; j < index_count; ++j) { const float* p = vertex_positions + indices[j] * vertex_stride_float; center[0] += p[0]; center[1] += p[1]; center[2] += p[2]; } // note: technically clusters can't be empty per meshopt_partitionCluster but we check for a division by zero in case that changes if (index_count) { center[0] /= float(index_count); center[1] /= float(index_count); center[2] /= float(index_count); } // compute radius of the bounding sphere for each cluster float radiussq = 0; for (size_t j = 0; j < index_count; ++j) { const float* p = vertex_positions + indices[j] * vertex_stride_float; float d2 = (p[0] - center[0]) * (p[0] - center[0]) + (p[1] - center[1]) * (p[1] - center[1]) + (p[2] - center[2]) * (p[2] - center[2]); radiussq = radiussq < d2 ? d2 : radiussq; } memcpy(out_center, center, sizeof(center)); return sqrtf(radiussq); } static void buildClusterAdjacency(ClusterAdjacency& adjacency, const unsigned int* cluster_indices, const unsigned int* cluster_offsets, size_t cluster_count, size_t vertex_count, meshopt_Allocator& allocator) { unsigned int* ref_offsets = allocator.allocate<unsigned int>(vertex_count + 1); // compute number of clusters referenced by each vertex memset(ref_offsets, 0, vertex_count * sizeof(unsigned int)); for (size_t i = 0; i < cluster_count; ++i) { for (size_t j = cluster_offsets[i]; j < cluster_offsets[i + 1]; ++j) ref_offsets[cluster_indices[j]]++; } // compute (worst-case) number of adjacent clusters for each cluster size_t total_adjacency = 0; for (size_t i = 0; i < cluster_count; ++i) { size_t count = 0; // worst case is every vertex has a disjoint cluster list for (size_t j = cluster_offsets[i]; j < cluster_offsets[i + 1]; ++j) count += ref_offsets[cluster_indices[j]] - 1; // ... but only every other cluster can be adjacent in the end total_adjacency += count < cluster_count - 1 ? count : cluster_count - 1; } // we can now allocate adjacency buffers adjacency.offsets = allocator.allocate<unsigned int>(cluster_count + 1); adjacency.clusters = allocator.allocate<unsigned int>(total_adjacency); adjacency.shared = allocator.allocate<unsigned int>(total_adjacency); // convert ref counts to offsets size_t total_refs = 0; for (size_t i = 0; i < vertex_count; ++i) { size_t count = ref_offsets[i]; ref_offsets[i] = unsigned(total_refs); total_refs += count; } unsigned int* ref_data = allocator.allocate<unsigned int>(total_refs); // fill cluster refs for each vertex for (size_t i = 0; i < cluster_count; ++i) { for (size_t j = cluster_offsets[i]; j < cluster_offsets[i + 1]; ++j) ref_data[ref_offsets[cluster_indices[j]]++] = unsigned(i); } // after the previous pass, ref_offsets contain the end of the data for each vertex; shift it forward to get the start memmove(ref_offsets + 1, ref_offsets, vertex_count * sizeof(unsigned int)); ref_offsets[0] = 0; // fill cluster adjacency for each cluster... adjacency.offsets[0] = 0; for (size_t i = 0; i < cluster_count; ++i) { unsigned int* adj = adjacency.clusters + adjacency.offsets[i]; unsigned int* shd = adjacency.shared + adjacency.offsets[i]; size_t count = 0; for (size_t j = cluster_offsets[i]; j < cluster_offsets[i + 1]; ++j) { unsigned int v = cluster_indices[j]; // merge the entire cluster list of each vertex into current list for (size_t k = ref_offsets[v]; k < ref_offsets[v + 1]; ++k) { unsigned int c = ref_data[k]; assert(c < cluster_count); if (c == unsigned(i)) continue; // if the cluster is already in the list, increment the shared count bool found = false; for (size_t l = 0; l < count; ++l) if (adj[l] == c) { found = true; shd[l]++; break; } // .. or append a new cluster if (!found) { adj[count] = c; shd[count] = 1; count++; } } } // mark the end of the adjacency list; the next cluster will start there as well adjacency.offsets[i + 1] = adjacency.offsets[i] + unsigned(count); } assert(adjacency.offsets[cluster_count] <= total_adjacency); // ref_offsets can't be deallocated as it was allocated before adjacency allocator.deallocate(ref_data); } struct ClusterGroup { int group; int next; unsigned int size; // 0 unless root unsigned int vertices; float center[3]; float radius; }; struct GroupOrder { unsigned int id; int order; }; static void heapPush(GroupOrder* heap, size_t size, GroupOrder item) { // insert a new element at the end (breaks heap invariant) heap[size++] = item; // bubble up the new element to its correct position size_t i = size - 1; while (i > 0 && heap[i].order < heap[(i - 1) / 2].order) { size_t p = (i - 1) / 2; GroupOrder temp = heap[i]; heap[i] = heap[p]; heap[p] = temp; i = p; } } static GroupOrder heapPop(GroupOrder* heap, size_t size) { assert(size > 0); GroupOrder top = heap[0]; // move the last element to the top (breaks heap invariant) heap[0] = heap[--size]; // bubble down the new top element to its correct position size_t i = 0; while (i * 2 + 1 < size) { // find the smallest child size_t j = i * 2 + 1; j += (j + 1 < size && heap[j + 1].order < heap[j].order); // if the parent is already smaller than both children, we're done if (heap[j].order >= heap[i].order) break; // otherwise, swap the parent and child and continue GroupOrder temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; i = j; } return top; } static unsigned int countShared(const ClusterGroup* groups, int group1, int group2, const ClusterAdjacency& adjacency) { unsigned int total = 0; for (int i1 = group1; i1 >= 0; i1 = groups[i1].next) for (int i2 = group2; i2 >= 0; i2 = groups[i2].next) { for (unsigned int adj = adjacency.offsets[i1]; adj < adjacency.offsets[i1 + 1]; ++adj) if (adjacency.clusters[adj] == unsigned(i2)) { total += adjacency.shared[adj]; break; } } return total; } static void mergeBounds(ClusterGroup& target, const ClusterGroup& source) { float r1 = target.radius, r2 = source.radius; float dx = source.center[0] - target.center[0], dy = source.center[1] - target.center[1], dz = source.center[2] - target.center[2]; float d = sqrtf(dx * dx + dy * dy + dz * dz); if (d + r1 < r2) { target.center[0] = source.center[0]; target.center[1] = source.center[1]; target.center[2] = source.center[2]; target.radius = source.radius; return; } if (d + r2 > r1) { float k = d > 0 ? (d + r2 - r1) / (2 * d) : 0.f; target.center[0] += dx * k; target.center[1] += dy * k; target.center[2] += dz * k; target.radius = (d + r2 + r1) / 2; } } static float boundsScore(const ClusterGroup& target, const ClusterGroup& source) { float r1 = target.radius, r2 = source.radius; float dx = source.center[0] - target.center[0], dy = source.center[1] - target.center[1], dz = source.center[2] - target.center[2]; float d = sqrtf(dx * dx + dy * dy + dz * dz); float mr = d + r1 < r2 ? r2 : (d + r2 < r1 ? r1 : (d + r2 + r1) / 2); return mr > 0 ? r1 / mr : 0.f; } static int pickGroupToMerge(const ClusterGroup* groups, int id, const ClusterAdjacency& adjacency, size_t max_partition_size, bool use_bounds) { assert(groups[id].size > 0); float group_rsqrt = 1.f / sqrtf(float(int(groups[id].vertices))); int best_group = -1; float best_score = 0; for (int ci = id; ci >= 0; ci = groups[ci].next) { for (unsigned int adj = adjacency.offsets[ci]; adj != adjacency.offsets[ci + 1]; ++adj) { int other = groups[adjacency.clusters[adj]].group; if (other < 0) continue; assert(groups[other].size > 0); if (groups[id].size + groups[other].size > max_partition_size) continue; unsigned int shared = countShared(groups, id, other, adjacency); float other_rsqrt = 1.f / sqrtf(float(int(groups[other].vertices))); // normalize shared count by the expected boundary of each group (+ keeps scoring symmetric) float score = float(int(shared)) * (group_rsqrt + other_rsqrt); // incorporate spatial score to favor merging nearby groups if (use_bounds) score *= 1.f + 0.4f * boundsScore(groups[id], groups[other]); if (score > best_score) { best_group = other; best_score = score; } } } return best_group; } static void mergeLeaf(ClusterGroup* groups, unsigned int* order, size_t count, size_t target_partition_size, size_t max_partition_size) { for (size_t i = 0; i < count; ++i) { unsigned int id = order[i]; if (groups[id].size == 0 || groups[id].size >= target_partition_size) continue; float best_score = -1.f; int best_group = -1; for (size_t j = 0; j < count; ++j) { unsigned int other = order[j]; if (id == other || groups[other].size == 0) continue; if (groups[id].size + groups[other].size > max_partition_size) continue; // favor merging nearby groups float score = boundsScore(groups[id], groups[other]); if (score > best_score) { best_score = score; best_group = other; } } // merge id *into* best_group; that way, we may merge more groups into the same best_group, maximizing the chance of reaching target if (best_group != -1) { // combine groups by linking them together unsigned int tail = best_group; while (groups[tail].next >= 0) tail = groups[tail].next; groups[tail].next = id; // update group sizes; note, we omit vertices update for simplicity as it's not used for spatial merge groups[best_group].size += groups[id].size; groups[id].size = 0; // merge bounding spheres mergeBounds(groups[best_group], groups[id]); groups[id].radius = 0.f; } } } static size_t mergePartition(unsigned int* order, size_t count, const ClusterGroup* groups, int axis, float pivot) { size_t m = 0; // invariant: elements in range [0, m) are < pivot, elements in range [m, i) are >= pivot for (size_t i = 0; i < count; ++i) { float v = groups[order[i]].center[axis]; // swap(m, i) unconditionally unsigned int t = order[m]; order[m] = order[i]; order[i] = t; // when v >= pivot, we swap i with m without advancing it, preserving invariants m += v < pivot; } return m; } static void mergeSpatial(ClusterGroup* groups, unsigned int* order, size_t count, size_t target_partition_size, size_t max_partition_size, size_t leaf_size, int depth) { size_t total = 0; for (size_t i = 0; i < count; ++i) total += groups[order[i]].size; if (total <= max_partition_size || count <= leaf_size) return mergeLeaf(groups, order, count, target_partition_size, max_partition_size); float mean[3] = {}; float vars[3] = {}; float runc = 1, runs = 1; // gather statistics on the points in the subtree using Welford's algorithm for (size_t i = 0; i < count; ++i, runc += 1.f, runs = 1.f / runc) { const float* point = groups[order[i]].center; for (int k = 0; k < 3; ++k) { float delta = point[k] - mean[k]; mean[k] += delta * runs; vars[k] += delta * (point[k] - mean[k]); } } // split axis is one where the variance is largest int axis = (vars[0] >= vars[1] && vars[0] >= vars[2]) ? 0 : (vars[1] >= vars[2] ? 1 : 2); float split = mean[axis]; size_t middle = mergePartition(order, count, groups, axis, split); // enforce balance for degenerate partitions // this also ensures recursion depth is bounded on pathological inputs if (middle <= leaf_size / 2 || count - middle <= leaf_size / 2 || depth >= kMergeDepthCutoff) middle = count / 2; // recursion depth is logarithmic and bounded due to max depth check above mergeSpatial(groups, order, middle, target_partition_size, max_partition_size, leaf_size, depth + 1); mergeSpatial(groups, order + middle, count - middle, target_partition_size, max_partition_size, leaf_size, depth + 1); } } // namespace meshopt size_t meshopt_partitionClusters(unsigned int* destination, const unsigned int* cluster_indices, size_t total_index_count, const unsigned int* cluster_index_counts, size_t cluster_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_partition_size) { using namespace meshopt; assert((vertex_positions == NULL || vertex_positions_stride >= 12) && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(target_partition_size > 0); size_t max_partition_size = target_partition_size + target_partition_size / 3; meshopt_Allocator allocator; unsigned char* used = allocator.allocate<unsigned char>(vertex_count); memset(used, 0, vertex_count); unsigned int* cluster_newindices = allocator.allocate<unsigned int>(total_index_count); unsigned int* cluster_offsets = allocator.allocate<unsigned int>(cluster_count + 1); // make new cluster index list that filters out duplicate indices filterClusterIndices(cluster_newindices, cluster_offsets, cluster_indices, cluster_index_counts, cluster_count, used, vertex_count, total_index_count); cluster_indices = cluster_newindices; // build cluster adjacency along with edge weights (shared vertex count) ClusterAdjacency adjacency = {}; buildClusterAdjacency(adjacency, cluster_indices, cluster_offsets, cluster_count, vertex_count, allocator); ClusterGroup* groups = allocator.allocate<ClusterGroup>(cluster_count); memset(groups, 0, sizeof(ClusterGroup) * cluster_count); GroupOrder* order = allocator.allocate<GroupOrder>(cluster_count); size_t pending = 0; // create a singleton group for each cluster and order them by priority for (size_t i = 0; i < cluster_count; ++i) { groups[i].group = int(i); groups[i].next = -1; groups[i].size = 1; groups[i].vertices = cluster_offsets[i + 1] - cluster_offsets[i]; assert(groups[i].vertices > 0); // compute bounding sphere for each cluster if positions are provided if (vertex_positions) groups[i].radius = computeClusterBounds(cluster_indices + cluster_offsets[i], cluster_offsets[i + 1] - cluster_offsets[i], vertex_positions, vertex_positions_stride, groups[i].center); GroupOrder item = {}; item.id = unsigned(i); item.order = groups[i].vertices; heapPush(order, pending++, item); } // iteratively merge the smallest group with the best group while (pending) { GroupOrder top = heapPop(order, pending--); // this group was merged into another group earlier if (groups[top.id].size == 0) continue; // disassociate clusters from the group to prevent them from being merged again; we will re-associate them if the group is reinserted for (int i = top.id; i >= 0; i = groups[i].next) { assert(groups[i].group == int(top.id)); groups[i].group = -1; } // the group is large enough, emit as is if (groups[top.id].size >= target_partition_size) continue; int best_group = pickGroupToMerge(groups, top.id, adjacency, max_partition_size, /* use_bounds= */ vertex_positions); // we can't grow the group any more, emit as is if (best_group == -1) continue; // compute shared vertices to adjust the total vertices estimate after merging unsigned int shared = countShared(groups, top.id, best_group, adjacency); // combine groups by linking them together unsigned int tail = top.id; while (groups[tail].next >= 0) tail = groups[tail].next; groups[tail].next = best_group; // update group sizes; note, the vertex update is a O(1) approximation which avoids recomputing the true size groups[top.id].size += groups[best_group].size; groups[top.id].vertices += groups[best_group].vertices; groups[top.id].vertices = (groups[top.id].vertices > shared) ? groups[top.id].vertices - shared : 1; groups[best_group].size = 0; groups[best_group].vertices = 0; // merge bounding spheres if bounds are available if (vertex_positions) { mergeBounds(groups[top.id], groups[best_group]); groups[best_group].radius = 0; } // re-associate all clusters back to the merged group for (int i = top.id; i >= 0; i = groups[i].next) groups[i].group = int(top.id); top.order = groups[top.id].vertices; heapPush(order, pending++, top); } // if vertex positions are provided, we do a final pass to see if we can merge small groups based on spatial locality alone if (vertex_positions) { unsigned int* merge_order = reinterpret_cast<unsigned int*>(order); size_t merge_offset = 0; for (size_t i = 0; i < cluster_count; ++i) if (groups[i].size) merge_order[merge_offset++] = unsigned(i); mergeSpatial(groups, merge_order, merge_offset, target_partition_size, max_partition_size, /* leaf_size= */ 8, 0); } // output each remaining group size_t next_group = 0; for (size_t i = 0; i < cluster_count; ++i) { if (groups[i].size == 0) continue; for (int j = int(i); j >= 0; j = groups[j].next) destination[j] = unsigned(next_group); next_group++; } assert(next_group <= cluster_count); return next_group; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/quantization.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> union FloatBits { float f; unsigned int ui; }; unsigned short meshopt_quantizeHalf(float v) { FloatBits u = {v}; unsigned int ui = u.ui; int s = (ui >> 16) & 0x8000; int em = ui & 0x7fffffff; // bias exponent and round to nearest; 112 is relative exponent bias (127-15) int h = (em - (112 << 23) + (1 << 12)) >> 13; // underflow: flush to zero; 113 encodes exponent -14 h = (em < (113 << 23)) ? 0 : h; // overflow: infinity; 143 encodes exponent 16 h = (em >= (143 << 23)) ? 0x7c00 : h; // NaN; note that we convert all types of NaN to qNaN h = (em > (255 << 23)) ? 0x7e00 : h; return (unsigned short)(s | h); } float meshopt_quantizeFloat(float v, int N) { assert(N >= 0 && N <= 23); FloatBits u = {v}; unsigned int ui = u.ui; const int mask = (1 << (23 - N)) - 1; const int round = (1 << (23 - N)) >> 1; int e = ui & 0x7f800000; unsigned int rui = (ui + round) & ~mask; // round all numbers except inf/nan; this is important to make sure nan doesn't overflow into -0 ui = e == 0x7f800000 ? ui : rui; // flush denormals to zero ui = e == 0 ? 0 : ui; u.ui = ui; return u.f; } float meshopt_dequantizeHalf(unsigned short h) { unsigned int s = unsigned(h & 0x8000) << 16; int em = h & 0x7fff; // bias exponent and pad mantissa with 0; 112 is relative exponent bias (127-15) int r = (em + (112 << 10)) << 13; // denormal: flush to zero r = (em < (1 << 10)) ? 0 : r; // infinity/NaN; note that we preserve NaN payload as a byproduct of unifying inf/nan cases // 112 is an exponent bias fixup; since we already applied it once, applying it twice converts 31 to 255 r += (em >= (31 << 10)) ? (112 << 23) : 0; FloatBits u; u.ui = s | r; return u.f; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/rasterizer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <string.h> // This work is based on: // Nicolas Capens. Advanced Rasterization. 2004 namespace meshopt { const int kViewport = 256; struct OverdrawBuffer { float z[kViewport][kViewport][2]; unsigned int overdraw[kViewport][kViewport][2]; }; static float computeDepthGradients(float& dzdx, float& dzdy, float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3) { // z2 = z1 + dzdx * (x2 - x1) + dzdy * (y2 - y1) // z3 = z1 + dzdx * (x3 - x1) + dzdy * (y3 - y1) // (x2-x1 y2-y1)(dzdx) = (z2-z1) // (x3-x1 y3-y1)(dzdy) (z3-z1) // we'll solve it with Cramer's rule float det = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1); float invdet = (det == 0) ? 0 : 1 / det; dzdx = ((z2 - z1) * (y3 - y1) - (y2 - y1) * (z3 - z1)) * invdet; dzdy = ((x2 - x1) * (z3 - z1) - (z2 - z1) * (x3 - x1)) * invdet; return det; } // half-space fixed point triangle rasterizer static void rasterize(OverdrawBuffer* buffer, float v1x, float v1y, float v1z, float v2x, float v2y, float v2z, float v3x, float v3y, float v3z) { // compute depth gradients float DZx, DZy; float det = computeDepthGradients(DZx, DZy, v1x, v1y, v1z, v2x, v2y, v2z, v3x, v3y, v3z); int sign = det > 0; // flip backfacing triangles to simplify rasterization logic if (sign) { // flipping v2 & v3 preserves depth gradients since they're based on v1; only v1z is used below float t; t = v2x, v2x = v3x, v3x = t; t = v2y, v2y = v3y, v3y = t; // flip depth since we rasterize backfacing triangles to second buffer with reverse Z; only v1z is used below v1z = kViewport - v1z; DZx = -DZx; DZy = -DZy; } // coordinates, 28.4 fixed point int X1 = int(16.0f * v1x + 0.5f); int X2 = int(16.0f * v2x + 0.5f); int X3 = int(16.0f * v3x + 0.5f); int Y1 = int(16.0f * v1y + 0.5f); int Y2 = int(16.0f * v2y + 0.5f); int Y3 = int(16.0f * v3y + 0.5f); // bounding rectangle, clipped against viewport // since we rasterize pixels with covered centers, min >0.5 should round up // as for max, due to top-left filling convention we will never rasterize right/bottom edges // so max >= 0.5 should round down for inclusive bounds, and up for exclusive (in our case) int minx = X1 < X2 ? X1 : X2; minx = minx < X3 ? minx : X3; minx = (minx + 7) >> 4; minx = minx < 0 ? 0 : minx; int miny = Y1 < Y2 ? Y1 : Y2; miny = miny < Y3 ? miny : Y3; miny = (miny + 7) >> 4; miny = miny < 0 ? 0 : miny; int maxx = X1 > X2 ? X1 : X2; maxx = maxx > X3 ? maxx : X3; maxx = (maxx + 7) >> 4; maxx = maxx > kViewport ? kViewport : maxx; int maxy = Y1 > Y2 ? Y1 : Y2; maxy = maxy > Y3 ? maxy : Y3; maxy = (maxy + 7) >> 4; maxy = maxy > kViewport ? kViewport : maxy; // deltas, 28.4 fixed point int DX12 = X1 - X2; int DX23 = X2 - X3; int DX31 = X3 - X1; int DY12 = Y1 - Y2; int DY23 = Y2 - Y3; int DY31 = Y3 - Y1; // fill convention correction int TL1 = DY12 < 0 || (DY12 == 0 && DX12 > 0); int TL2 = DY23 < 0 || (DY23 == 0 && DX23 > 0); int TL3 = DY31 < 0 || (DY31 == 0 && DX31 > 0); // half edge equations, 24.8 fixed point // note that we offset minx/miny by half pixel since we want to rasterize pixels with covered centers int FX = (minx << 4) + 8; int FY = (miny << 4) + 8; int CY1 = DX12 * (FY - Y1) - DY12 * (FX - X1) + TL1 - 1; int CY2 = DX23 * (FY - Y2) - DY23 * (FX - X2) + TL2 - 1; int CY3 = DX31 * (FY - Y3) - DY31 * (FX - X3) + TL3 - 1; float ZY = v1z + (DZx * float(FX - X1) + DZy * float(FY - Y1)) * (1 / 16.f); for (int y = miny; y < maxy; y++) { int CX1 = CY1; int CX2 = CY2; int CX3 = CY3; float ZX = ZY; for (int x = minx; x < maxx; x++) { // check if all CXn are non-negative if ((CX1 | CX2 | CX3) >= 0) { if (ZX >= buffer->z[y][x][sign]) { buffer->z[y][x][sign] = ZX; buffer->overdraw[y][x][sign]++; } } // signed left shift is UB for negative numbers so use unsigned-signed casts CX1 -= int(unsigned(DY12) << 4); CX2 -= int(unsigned(DY23) << 4); CX3 -= int(unsigned(DY31) << 4); ZX += DZx; } // signed left shift is UB for negative numbers so use unsigned-signed casts CY1 += int(unsigned(DX12) << 4); CY2 += int(unsigned(DX23) << 4); CY3 += int(unsigned(DX31) << 4); ZY += DZy; } } static float transformTriangles(float* triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { size_t vertex_stride_float = vertex_positions_stride / sizeof(float); float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { float vj = v[j]; minv[j] = minv[j] > vj ? vj : minv[j]; maxv[j] = maxv[j] < vj ? vj : maxv[j]; } } float extent = 0.f; extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]); extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]); extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]); float scale = kViewport / extent; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); const float* v = vertex_positions + index * vertex_stride_float; triangles[i * 3 + 0] = (v[0] - minv[0]) * scale; triangles[i * 3 + 1] = (v[1] - minv[1]) * scale; triangles[i * 3 + 2] = (v[2] - minv[2]) * scale; } return extent; } static void rasterizeTriangles(OverdrawBuffer* buffer, const float* triangles, size_t index_count, int axis) { for (size_t i = 0; i < index_count; i += 3) { const float* vn0 = &triangles[3 * (i + 0)]; const float* vn1 = &triangles[3 * (i + 1)]; const float* vn2 = &triangles[3 * (i + 2)]; switch (axis) { case 0: rasterize(buffer, vn0[2], vn0[1], vn0[0], vn1[2], vn1[1], vn1[0], vn2[2], vn2[1], vn2[0]); break; case 1: rasterize(buffer, vn0[0], vn0[2], vn0[1], vn1[0], vn1[2], vn1[1], vn2[0], vn2[2], vn2[1]); break; case 2: rasterize(buffer, vn0[1], vn0[0], vn0[2], vn1[1], vn1[0], vn1[2], vn2[1], vn2[0], vn2[2]); break; } } } } // namespace meshopt meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; meshopt_OverdrawStatistics result = {}; float* triangles = allocator.allocate<float>(index_count * 3); transformTriangles(triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride); OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); rasterizeTriangles(buffer, triangles, index_count, axis); for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) for (int s = 0; s < 2; ++s) { unsigned int overdraw = buffer->overdraw[y][x][s]; result.pixels_covered += overdraw > 0; result.pixels_shaded += overdraw; } } result.overdraw = result.pixels_covered ? float(result.pixels_shaded) / float(result.pixels_covered) : 0.f; return result; } meshopt_CoverageStatistics meshopt_analyzeCoverage(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; meshopt_CoverageStatistics result = {}; float* triangles = allocator.allocate<float>(index_count * 3); float extent = transformTriangles(triangles, indices, index_count, vertex_positions, vertex_count, vertex_positions_stride); OverdrawBuffer* buffer = allocator.allocate<OverdrawBuffer>(1); for (int axis = 0; axis < 3; ++axis) { memset(buffer, 0, sizeof(OverdrawBuffer)); rasterizeTriangles(buffer, triangles, index_count, axis); unsigned int covered = 0; for (int y = 0; y < kViewport; ++y) for (int x = 0; x < kViewport; ++x) covered += (buffer->overdraw[y][x][0] | buffer->overdraw[y][x][1]) > 0; result.coverage[axis] = float(covered) / float(kViewport * kViewport); } result.extent = extent; return result; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/simplifier.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <math.h> #include <string.h> #ifndef TRACE #define TRACE 0 #endif #if TRACE #include <stdio.h> #endif #if TRACE #define TRACESTATS(i) stats[i]++; #else #define TRACESTATS(i) (void)0 #endif // This work is based on: // Michael Garland and Paul S. Heckbert. Surface simplification using quadric error metrics. 1997 // Michael Garland. Quadric-based polygonal surface simplification. 1999 // Peter Lindstrom. Out-of-Core Simplification of Large Polygonal Models. 2000 // Matthias Teschner, Bruno Heidelberger, Matthias Mueller, Danat Pomeranets, Markus Gross. Optimized Spatial Hashing for Collision Detection of Deformable Objects. 2003 // Peter Van Sandt, Yannis Chronis, Jignesh M. Patel. Efficiently Searching In-Memory Sorted Arrays: Revenge of the Interpolation Search? 2019 // Hugues Hoppe. New Quadric Metric for Simplifying Meshes with Appearance Attributes. 1999 // Hugues Hoppe, Steve Marschner. Efficient Minimization of New Quadric Metric for Simplifying Meshes with Appearance Attributes. 2000 namespace meshopt { struct EdgeAdjacency { struct Edge { unsigned int next; unsigned int prev; }; unsigned int* offsets; Edge* data; }; static void prepareEdgeAdjacency(EdgeAdjacency& adjacency, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator) { adjacency.offsets = allocator.allocate<unsigned int>(vertex_count + 1); adjacency.data = allocator.allocate<EdgeAdjacency::Edge>(index_count); } static void updateEdgeAdjacency(EdgeAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, const unsigned int* remap) { size_t face_count = index_count / 3; unsigned int* offsets = adjacency.offsets + 1; EdgeAdjacency::Edge* data = adjacency.data; // fill edge counts memset(offsets, 0, vertex_count * sizeof(unsigned int)); for (size_t i = 0; i < index_count; ++i) { unsigned int v = remap ? remap[indices[i]] : indices[i]; assert(v < vertex_count); offsets[v]++; } // fill offset table unsigned int offset = 0; for (size_t i = 0; i < vertex_count; ++i) { unsigned int count = offsets[i]; offsets[i] = offset; offset += count; } assert(offset == index_count); // fill edge data for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; if (remap) { a = remap[a]; b = remap[b]; c = remap[c]; } data[offsets[a]].next = b; data[offsets[a]].prev = c; offsets[a]++; data[offsets[b]].next = c; data[offsets[b]].prev = a; offsets[b]++; data[offsets[c]].next = a; data[offsets[c]].prev = b; offsets[c]++; } // finalize offsets adjacency.offsets[0] = 0; assert(adjacency.offsets[vertex_count] == index_count); } struct PositionHasher { const float* vertex_positions; size_t vertex_stride_float; const unsigned int* sparse_remap; size_t hash(unsigned int index) const { unsigned int ri = sparse_remap ? sparse_remap[index] : index; const unsigned int* key = reinterpret_cast<const unsigned int*>(vertex_positions + ri * vertex_stride_float); unsigned int x = key[0], y = key[1], z = key[2]; // replace negative zero with zero x = (x == 0x80000000) ? 0 : x; y = (y == 0x80000000) ? 0 : y; z = (z == 0x80000000) ? 0 : z; // scramble bits to make sure that integer coordinates have entropy in lower bits x ^= x >> 17; y ^= y >> 17; z ^= z >> 17; // Optimized Spatial Hashing for Collision Detection of Deformable Objects return (x * 73856093) ^ (y * 19349663) ^ (z * 83492791); } bool equal(unsigned int lhs, unsigned int rhs) const { unsigned int li = sparse_remap ? sparse_remap[lhs] : lhs; unsigned int ri = sparse_remap ? sparse_remap[rhs] : rhs; const float* lv = vertex_positions + li * vertex_stride_float; const float* rv = vertex_positions + ri * vertex_stride_float; return lv[0] == rv[0] && lv[1] == rv[1] && lv[2] == rv[2]; } }; struct RemapHasher { unsigned int* remap; size_t hash(unsigned int id) const { return id * 0x5bd1e995; } bool equal(unsigned int lhs, unsigned int rhs) const { return remap[lhs] == rhs; } }; static size_t hashBuckets2(size_t count) { size_t buckets = 1; while (buckets < count + count / 4) buckets *= 2; return buckets; } template <typename T, typename Hash> static T* hashLookup2(T* table, size_t buckets, const Hash& hash, const T& key, const T& empty) { assert(buckets > 0); assert((buckets & (buckets - 1)) == 0); size_t hashmod = buckets - 1; size_t bucket = hash.hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { T& item = table[bucket]; if (item == empty) return &item; if (hash.equal(item, key)) return &item; // hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } assert(false && "Hash table is full"); // unreachable return NULL; } static void buildPositionRemap(unsigned int* remap, unsigned int* wedge, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap, meshopt_Allocator& allocator) { PositionHasher hasher = {vertex_positions_data, vertex_positions_stride / sizeof(float), sparse_remap}; size_t table_size = hashBuckets2(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); memset(table, -1, table_size * sizeof(unsigned int)); // build forward remap: for each vertex, which other (canonical) vertex does it map to? // we use position equivalence for this, and remap vertices to other existing vertices for (size_t i = 0; i < vertex_count; ++i) { unsigned int index = unsigned(i); unsigned int* entry = hashLookup2(table, table_size, hasher, index, ~0u); if (*entry == ~0u) *entry = index; remap[index] = *entry; } allocator.deallocate(table); if (!wedge) return; // build wedge table: for each vertex, which other vertex is the next wedge that also maps to the same vertex? // entries in table form a (cyclic) wedge loop per vertex; for manifold vertices, wedge[i] == remap[i] == i for (size_t i = 0; i < vertex_count; ++i) wedge[i] = unsigned(i); for (size_t i = 0; i < vertex_count; ++i) if (remap[i] != i) { unsigned int r = remap[i]; wedge[i] = wedge[r]; wedge[r] = unsigned(i); } } static unsigned int* buildSparseRemap(unsigned int* indices, size_t index_count, size_t vertex_count, size_t* out_vertex_count, meshopt_Allocator& allocator) { // use a bit set to compute the precise number of unique vertices unsigned char* filter = allocator.allocate<unsigned char>((vertex_count + 7) / 8); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); filter[index / 8] = 0; } size_t unique = 0; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; unique += (filter[index / 8] & (1 << (index % 8))) == 0; filter[index / 8] |= 1 << (index % 8); } unsigned int* remap = allocator.allocate<unsigned int>(unique); size_t offset = 0; // temporary map dense => sparse; we allocate it last so that we can deallocate it size_t revremap_size = hashBuckets2(unique); unsigned int* revremap = allocator.allocate<unsigned int>(revremap_size); memset(revremap, -1, revremap_size * sizeof(unsigned int)); // fill remap, using revremap as a helper, and rewrite indices in the same pass RemapHasher hasher = {remap}; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; unsigned int* entry = hashLookup2(revremap, revremap_size, hasher, index, ~0u); if (*entry == ~0u) { remap[offset] = index; *entry = unsigned(offset); offset++; } indices[i] = *entry; } allocator.deallocate(revremap); assert(offset == unique); *out_vertex_count = unique; return remap; } enum VertexKind { Kind_Manifold, // not on an attribute seam, not on any boundary Kind_Border, // not on an attribute seam, has exactly two open edges Kind_Seam, // on an attribute seam with exactly two attribute seam edges Kind_Complex, // none of the above; these vertices can move as long as all wedges move to the target vertex Kind_Locked, // none of the above; these vertices can't move Kind_Count }; // manifold vertices can collapse onto anything // border/seam vertices can collapse onto border/seam respectively, or locked // complex vertices can collapse onto complex/locked // a rule of thumb is that collapsing kind A into kind B preserves the kind B in the target vertex // for example, while we could collapse Complex into Manifold, this would mean the target vertex isn't Manifold anymore const unsigned char kCanCollapse[Kind_Count][Kind_Count] = { {1, 1, 1, 1, 1}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, }; // if a vertex is manifold or seam, adjoining edges are guaranteed to have an opposite edge // note that for seam edges, the opposite edge isn't present in the attribute-based topology // but is present if you consider a position-only mesh variant // while many complex collapses have the opposite edge, since complex vertices collapse to the // same wedge, keeping opposite edges separate improves the quality by considering both targets const unsigned char kHasOpposite[Kind_Count][Kind_Count] = { {1, 1, 1, 1, 1}, {1, 0, 1, 0, 0}, {1, 1, 1, 0, 1}, {1, 0, 0, 0, 0}, {1, 0, 1, 0, 0}, }; static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b) { unsigned int count = adjacency.offsets[a + 1] - adjacency.offsets[a]; const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[a]; for (size_t i = 0; i < count; ++i) if (edges[i].next == b) return true; return false; } static bool hasEdge(const EdgeAdjacency& adjacency, unsigned int a, unsigned int b, const unsigned int* remap, const unsigned int* wedge) { unsigned int v = a; do { unsigned int count = adjacency.offsets[v + 1] - adjacency.offsets[v]; const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[v]; for (size_t i = 0; i < count; ++i) if (remap[edges[i].next] == remap[b]) return true; v = wedge[v]; } while (v != a); return false; } static void classifyVertices(unsigned char* result, unsigned int* loop, unsigned int* loopback, size_t vertex_count, const EdgeAdjacency& adjacency, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_lock, const unsigned int* sparse_remap, unsigned int options) { memset(loop, -1, vertex_count * sizeof(unsigned int)); memset(loopback, -1, vertex_count * sizeof(unsigned int)); // incoming & outgoing open edges: ~0u if no open edges, i if there are more than 1 // note that this is the same data as required in loop[] arrays; loop[] data is only used for border/seam by default // in permissive mode we also use it to guide complex-complex collapses, so we fill it for all vertices unsigned int* openinc = loopback; unsigned int* openout = loop; for (size_t i = 0; i < vertex_count; ++i) { unsigned int vertex = unsigned(i); unsigned int count = adjacency.offsets[vertex + 1] - adjacency.offsets[vertex]; const EdgeAdjacency::Edge* edges = adjacency.data + adjacency.offsets[vertex]; for (size_t j = 0; j < count; ++j) { unsigned int target = edges[j].next; if (target == vertex) { // degenerate triangles have two distinct edges instead of three, and the self edge // is bi-directional by definition; this can break border/seam classification by "closing" // the open edge from another triangle and falsely marking the vertex as manifold // instead we mark the vertex as having >1 open edges which turns it into locked/complex openinc[vertex] = openout[vertex] = vertex; } else if (!hasEdge(adjacency, target, vertex)) { openinc[target] = (openinc[target] == ~0u) ? vertex : target; openout[vertex] = (openout[vertex] == ~0u) ? target : vertex; } } } #if TRACE size_t stats[4] = {}; #endif for (size_t i = 0; i < vertex_count; ++i) { if (remap[i] == i) { if (wedge[i] == i) { // no attribute seam, need to check if it's manifold unsigned int openi = openinc[i], openo = openout[i]; // note: we classify any vertices with no open edges as manifold // this is technically incorrect - if 4 triangles share an edge, we'll classify vertices as manifold // it's unclear if this is a problem in practice if (openi == ~0u && openo == ~0u) { result[i] = Kind_Manifold; } else if (openi != ~0u && openo != ~0u && remap[openi] == remap[openo] && openi != i) { // classify half-seams as seams (the branch below would mis-classify them as borders) // half-seam is a single vertex that connects to both vertices of a potential seam // treating these as seams allows collapsing the "full" seam vertex onto them result[i] = Kind_Seam; } else if (openi != i && openo != i) { result[i] = Kind_Border; } else { result[i] = Kind_Locked; TRACESTATS(0); } } else if (wedge[wedge[i]] == i) { // attribute seam; need to distinguish between Seam and Locked unsigned int w = wedge[i]; unsigned int openiv = openinc[i], openov = openout[i]; unsigned int openiw = openinc[w], openow = openout[w]; // seam should have one open half-edge for each vertex, and the edges need to "connect" - point to the same vertex post-remap if (openiv != ~0u && openiv != i && openov != ~0u && openov != i && openiw != ~0u && openiw != w && openow != ~0u && openow != w) { if (remap[openiv] == remap[openow] && remap[openov] == remap[openiw] && remap[openiv] != remap[openov]) { result[i] = Kind_Seam; } else { result[i] = Kind_Locked; TRACESTATS(1); } } else { result[i] = Kind_Locked; TRACESTATS(2); } } else { // more than one vertex maps to this one; we don't have classification available result[i] = Kind_Locked; TRACESTATS(3); } } else { assert(remap[i] < i); result[i] = result[remap[i]]; } } if (options & meshopt_SimplifyPermissive) for (size_t i = 0; i < vertex_count; ++i) if (result[i] == Kind_Seam || result[i] == Kind_Locked) { if (remap[i] != i) { // only process primary vertices; wedges will be updated to match the primary vertex result[i] = result[remap[i]]; continue; } bool protect = false; // vertex_lock may protect any wedge, not just the primary vertex, so we switch to complex only if no wedges are protected unsigned int v = unsigned(i); do { unsigned int rv = sparse_remap ? sparse_remap[v] : v; protect |= vertex_lock && (vertex_lock[rv] & meshopt_SimplifyVertex_Protect) != 0; v = wedge[v]; } while (v != i); // protect if any adjoining edge doesn't have an opposite edge (indicating vertex is on the border) do { const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[v]]; size_t count = adjacency.offsets[v + 1] - adjacency.offsets[v]; for (size_t j = 0; j < count; ++j) protect |= !hasEdge(adjacency, edges[j].next, v, remap, wedge); v = wedge[v]; } while (v != i); result[i] = protect ? result[i] : int(Kind_Complex); } if (vertex_lock) { // vertex_lock may lock any wedge, not just the primary vertex, so we need to lock the primary vertex and relock any wedges for (size_t i = 0; i < vertex_count; ++i) { unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i); if (vertex_lock[ri] & meshopt_SimplifyVertex_Lock) result[remap[i]] = Kind_Locked; } for (size_t i = 0; i < vertex_count; ++i) if (result[remap[i]] == Kind_Locked) result[i] = Kind_Locked; } if (options & meshopt_SimplifyLockBorder) for (size_t i = 0; i < vertex_count; ++i) if (result[i] == Kind_Border) result[i] = Kind_Locked; #if TRACE printf("locked: many open edges %d, disconnected seam %d, many seam edges %d, many wedges %d\n", int(stats[0]), int(stats[1]), int(stats[2]), int(stats[3])); #endif } struct Vector3 { float x, y, z; }; static float rescalePositions(Vector3* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned int* sparse_remap = NULL, float* out_offset = NULL) { size_t vertex_stride_float = vertex_positions_stride / sizeof(float); float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i); const float* v = vertex_positions_data + ri * vertex_stride_float; if (result) { result[i].x = v[0]; result[i].y = v[1]; result[i].z = v[2]; } for (int j = 0; j < 3; ++j) { float vj = v[j]; minv[j] = minv[j] > vj ? vj : minv[j]; maxv[j] = maxv[j] < vj ? vj : maxv[j]; } } float extent = 0.f; extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]); extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]); extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]); if (result) { float scale = extent == 0 ? 0.f : 1.f / extent; for (size_t i = 0; i < vertex_count; ++i) { result[i].x = (result[i].x - minv[0]) * scale; result[i].y = (result[i].y - minv[1]) * scale; result[i].z = (result[i].z - minv[2]) * scale; } } if (out_offset) { out_offset[0] = minv[0]; out_offset[1] = minv[1]; out_offset[2] = minv[2]; } return extent; } static void rescaleAttributes(float* result, const float* vertex_attributes_data, size_t vertex_count, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned int* attribute_remap, const unsigned int* sparse_remap) { size_t vertex_attributes_stride_float = vertex_attributes_stride / sizeof(float); for (size_t i = 0; i < vertex_count; ++i) { unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i); for (size_t k = 0; k < attribute_count; ++k) { unsigned int rk = attribute_remap[k]; float a = vertex_attributes_data[ri * vertex_attributes_stride_float + rk]; result[i * attribute_count + k] = a * attribute_weights[rk]; } } } static void finalizeVertices(float* vertex_positions_data, size_t vertex_positions_stride, float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, size_t vertex_count, const Vector3* vertex_positions, const float* vertex_attributes, const unsigned int* sparse_remap, const unsigned int* attribute_remap, float vertex_scale, const float* vertex_offset, const unsigned char* vertex_kind, const unsigned char* vertex_update, const unsigned char* vertex_lock) { size_t vertex_positions_stride_float = vertex_positions_stride / sizeof(float); size_t vertex_attributes_stride_float = vertex_attributes_stride / sizeof(float); for (size_t i = 0; i < vertex_count; ++i) { if (!vertex_update[i]) continue; unsigned int ri = sparse_remap ? sparse_remap[i] : unsigned(i); // updating externally locked vertices is not allowed if (vertex_lock && (vertex_lock[ri] & meshopt_SimplifyVertex_Lock) != 0) continue; // moving locked vertices may result in floating point drift if (vertex_kind[i] != Kind_Locked) { const Vector3& p = vertex_positions[i]; float* v = vertex_positions_data + ri * vertex_positions_stride_float; v[0] = p.x * vertex_scale + vertex_offset[0]; v[1] = p.y * vertex_scale + vertex_offset[1]; v[2] = p.z * vertex_scale + vertex_offset[2]; } if (attribute_count) { const float* sa = vertex_attributes + i * attribute_count; float* va = vertex_attributes_data + ri * vertex_attributes_stride_float; for (size_t k = 0; k < attribute_count; ++k) { unsigned int rk = attribute_remap[k]; va[rk] = sa[k] / attribute_weights[rk]; } } } } static const size_t kMaxAttributes = 32; struct Quadric { // a00*x^2 + a11*y^2 + a22*z^2 + 2*a10*xy + 2*a20*xz + 2*a21*yz + 2*b0*x + 2*b1*y + 2*b2*z + c float a00, a11, a22; float a10, a20, a21; float b0, b1, b2, c; float w; }; struct QuadricGrad { // gx*x + gy*y + gz*z + gw float gx, gy, gz, gw; }; struct Reservoir { float x, y, z; float r, g, b; float w; }; struct Collapse { unsigned int v0; unsigned int v1; union { unsigned int bidi; float error; unsigned int errorui; }; }; static float normalize(Vector3& v) { float length = sqrtf(v.x * v.x + v.y * v.y + v.z * v.z); if (length > 0) { v.x /= length; v.y /= length; v.z /= length; } return length; } static void quadricAdd(Quadric& Q, const Quadric& R) { Q.a00 += R.a00; Q.a11 += R.a11; Q.a22 += R.a22; Q.a10 += R.a10; Q.a20 += R.a20; Q.a21 += R.a21; Q.b0 += R.b0; Q.b1 += R.b1; Q.b2 += R.b2; Q.c += R.c; Q.w += R.w; } static void quadricAdd(QuadricGrad& G, const QuadricGrad& R) { G.gx += R.gx; G.gy += R.gy; G.gz += R.gz; G.gw += R.gw; } static void quadricAdd(QuadricGrad* G, const QuadricGrad* R, size_t attribute_count) { for (size_t k = 0; k < attribute_count; ++k) { G[k].gx += R[k].gx; G[k].gy += R[k].gy; G[k].gz += R[k].gz; G[k].gw += R[k].gw; } } static float quadricEval(const Quadric& Q, const Vector3& v) { float rx = Q.b0; float ry = Q.b1; float rz = Q.b2; rx += Q.a10 * v.y; ry += Q.a21 * v.z; rz += Q.a20 * v.x; rx *= 2; ry *= 2; rz *= 2; rx += Q.a00 * v.x; ry += Q.a11 * v.y; rz += Q.a22 * v.z; float r = Q.c; r += rx * v.x; r += ry * v.y; r += rz * v.z; return r; } static float quadricError(const Quadric& Q, const Vector3& v) { float r = quadricEval(Q, v); float s = Q.w == 0.f ? 0.f : 1.f / Q.w; return fabsf(r) * s; } static float quadricError(const Quadric& Q, const QuadricGrad* G, size_t attribute_count, const Vector3& v, const float* va) { float r = quadricEval(Q, v); // see quadricFromAttributes for general derivation; here we need to add the parts of (eval(pos) - attr)^2 that depend on attr for (size_t k = 0; k < attribute_count; ++k) { float a = va[k]; float g = v.x * G[k].gx + v.y * G[k].gy + v.z * G[k].gz + G[k].gw; r += a * (a * Q.w - 2 * g); } // note: unlike position error, we do not normalize by Q.w to retain edge scaling as described in quadricFromAttributes return fabsf(r); } static void quadricFromPlane(Quadric& Q, float a, float b, float c, float d, float w) { float aw = a * w; float bw = b * w; float cw = c * w; float dw = d * w; Q.a00 = a * aw; Q.a11 = b * bw; Q.a22 = c * cw; Q.a10 = a * bw; Q.a20 = a * cw; Q.a21 = b * cw; Q.b0 = a * dw; Q.b1 = b * dw; Q.b2 = c * dw; Q.c = d * dw; Q.w = w; } static void quadricFromPoint(Quadric& Q, float x, float y, float z, float w) { Q.a00 = Q.a11 = Q.a22 = w; Q.a10 = Q.a20 = Q.a21 = 0; Q.b0 = -x * w; Q.b1 = -y * w; Q.b2 = -z * w; Q.c = (x * x + y * y + z * z) * w; Q.w = w; } static void quadricFromTriangle(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight) { Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z}; Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z}; // normal = cross(p1 - p0, p2 - p0) Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x}; float area = normalize(normal); float distance = normal.x * p0.x + normal.y * p0.y + normal.z * p0.z; // we use sqrtf(area) so that the error is scaled linearly; this tends to improve silhouettes quadricFromPlane(Q, normal.x, normal.y, normal.z, -distance, sqrtf(area) * weight); } static void quadricFromTriangleEdge(Quadric& Q, const Vector3& p0, const Vector3& p1, const Vector3& p2, float weight) { Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z}; // edge length; keep squared length around for projection correction float lengthsq = p10.x * p10.x + p10.y * p10.y + p10.z * p10.z; float length = sqrtf(lengthsq); // p20p = length of projection of p2-p0 onto p1-p0; note that p10 is unnormalized so we need to correct it later Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z}; float p20p = p20.x * p10.x + p20.y * p10.y + p20.z * p10.z; // perp = perpendicular vector from p2 to line segment p1-p0 // note: since p10 is unnormalized we need to correct the projection; we scale p20 instead to take advantage of normalize below Vector3 perp = {p20.x * lengthsq - p10.x * p20p, p20.y * lengthsq - p10.y * p20p, p20.z * lengthsq - p10.z * p20p}; normalize(perp); float distance = perp.x * p0.x + perp.y * p0.y + perp.z * p0.z; // note: the weight is scaled linearly with edge length; this has to match the triangle weight quadricFromPlane(Q, perp.x, perp.y, perp.z, -distance, length * weight); } static void quadricFromAttributes(Quadric& Q, QuadricGrad* G, const Vector3& p0, const Vector3& p1, const Vector3& p2, const float* va0, const float* va1, const float* va2, size_t attribute_count) { // for each attribute we want to encode the following function into the quadric: // (eval(pos) - attr)^2 // where eval(pos) interpolates attribute across the triangle like so: // eval(pos) = pos.x * gx + pos.y * gy + pos.z * gz + gw // where gx/gy/gz/gw are gradients Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z}; Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z}; // normal = cross(p1 - p0, p2 - p0) Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x}; float area = sqrtf(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z) * 0.5f; // quadric is weighted with the square of edge length (= area) // this equalizes the units with the positional error (which, after normalization, is a square of distance) // as a result, a change in weighted attribute of 1 along distance d is approximately equivalent to a change in position of d float w = area; // we compute gradients using barycentric coordinates; barycentric coordinates can be computed as follows: // v = (d11 * d20 - d01 * d21) / denom // w = (d00 * d21 - d01 * d20) / denom // u = 1 - v - w // here v0, v1 are triangle edge vectors, v2 is a vector from point to triangle corner, and dij = dot(vi, vj) // note: v2 and d20/d21 can not be evaluated here as v2 is effectively an unknown variable; we need these only as variables for derivation of gradients const Vector3& v0 = p10; const Vector3& v1 = p20; float d00 = v0.x * v0.x + v0.y * v0.y + v0.z * v0.z; float d01 = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z; float d11 = v1.x * v1.x + v1.y * v1.y + v1.z * v1.z; float denom = d00 * d11 - d01 * d01; float denomr = denom == 0 ? 0.f : 1.f / denom; // precompute gradient factors // these are derived by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w and factoring out expressions that are shared between attributes float gx1 = (d11 * v0.x - d01 * v1.x) * denomr; float gx2 = (d00 * v1.x - d01 * v0.x) * denomr; float gy1 = (d11 * v0.y - d01 * v1.y) * denomr; float gy2 = (d00 * v1.y - d01 * v0.y) * denomr; float gz1 = (d11 * v0.z - d01 * v1.z) * denomr; float gz2 = (d00 * v1.z - d01 * v0.z) * denomr; memset(&Q, 0, sizeof(Quadric)); Q.w = w; for (size_t k = 0; k < attribute_count; ++k) { float a0 = va0[k], a1 = va1[k], a2 = va2[k]; // compute gradient of eval(pos) for x/y/z/w // the formulas below are obtained by directly computing derivative of eval(pos) = a0 * u + a1 * v + a2 * w float gx = gx1 * (a1 - a0) + gx2 * (a2 - a0); float gy = gy1 * (a1 - a0) + gy2 * (a2 - a0); float gz = gz1 * (a1 - a0) + gz2 * (a2 - a0); float gw = a0 - p0.x * gx - p0.y * gy - p0.z * gz; // quadric encodes (eval(pos)-attr)^2; this means that the resulting expansion needs to compute, for example, pos.x * pos.y * K // since quadrics already encode factors for pos.x * pos.y, we can accumulate almost everything in basic quadric fields // note: for simplicity we scale all factors by weight here instead of outside the loop Q.a00 += w * (gx * gx); Q.a11 += w * (gy * gy); Q.a22 += w * (gz * gz); Q.a10 += w * (gy * gx); Q.a20 += w * (gz * gx); Q.a21 += w * (gz * gy); Q.b0 += w * (gx * gw); Q.b1 += w * (gy * gw); Q.b2 += w * (gz * gw); Q.c += w * (gw * gw); // the only remaining sum components are ones that depend on attr; these will be addded during error evaluation, see quadricError G[k].gx = w * gx; G[k].gy = w * gy; G[k].gz = w * gz; G[k].gw = w * gw; } } static void quadricVolumeGradient(QuadricGrad& G, const Vector3& p0, const Vector3& p1, const Vector3& p2) { Vector3 p10 = {p1.x - p0.x, p1.y - p0.y, p1.z - p0.z}; Vector3 p20 = {p2.x - p0.x, p2.y - p0.y, p2.z - p0.z}; // normal = cross(p1 - p0, p2 - p0) Vector3 normal = {p10.y * p20.z - p10.z * p20.y, p10.z * p20.x - p10.x * p20.z, p10.x * p20.y - p10.y * p20.x}; float area = normalize(normal) * 0.5f; G.gx = normal.x * area; G.gy = normal.y * area; G.gz = normal.z * area; G.gw = (-p0.x * normal.x - p0.y * normal.y - p0.z * normal.z) * area; } static bool quadricSolve(Vector3& p, const Quadric& Q, const QuadricGrad& GV) { // solve A*p = -b where A is the quadric matrix and b is the linear term float a00 = Q.a00, a11 = Q.a11, a22 = Q.a22; float a10 = Q.a10, a20 = Q.a20, a21 = Q.a21; float x0 = -Q.b0, x1 = -Q.b1, x2 = -Q.b2; float eps = 1e-6f * Q.w; // LDL decomposition: A = LDL^T float d0 = a00; float l10 = a10 / d0; float l20 = a20 / d0; float d1 = a11 - a10 * l10; float dl21 = a21 - a20 * l10; float l21 = dl21 / d1; float d2 = a22 - a20 * l20 - dl21 * l21; // solve L*y = x float y0 = x0; float y1 = x1 - l10 * y0; float y2 = x2 - l20 * y0 - l21 * y1; // solve D*z = y float z0 = y0 / d0; float z1 = y1 / d1; float z2 = y2 / d2; // augment system with linear constraint GV using Lagrange multiplier float a30 = GV.gx, a31 = GV.gy, a32 = GV.gz; float x3 = -GV.gw; float l30 = a30 / d0; float dl31 = a31 - a30 * l10; float l31 = dl31 / d1; float dl32 = a32 - a30 * l20 - dl31 * l21; float l32 = dl32 / d2; float d3 = 0.f - a30 * l30 - dl31 * l31 - dl32 * l32; float y3 = x3 - l30 * y0 - l31 * y1 - l32 * y2; float z3 = fabsf(d3) > eps ? y3 / d3 : 0.f; // if d3 is zero, we can ignore the constraint // substitute L^T*p = z float lambda = z3; float pz = z2 - l32 * lambda; float py = z1 - l21 * pz - l31 * lambda; float px = z0 - l10 * py - l20 * pz - l30 * lambda; p.x = px; p.y = py; p.z = pz; return fabsf(d0) > eps && fabsf(d1) > eps && fabsf(d2) > eps; } static void quadricReduceAttributes(Quadric& Q, const Quadric& A, const QuadricGrad* G, size_t attribute_count) { // update vertex quadric with attribute quadric; multiply by vertex weight to minimize normalized error Q.a00 += A.a00 * Q.w; Q.a11 += A.a11 * Q.w; Q.a22 += A.a22 * Q.w; Q.a10 += A.a10 * Q.w; Q.a20 += A.a20 * Q.w; Q.a21 += A.a21 * Q.w; Q.b0 += A.b0 * Q.w; Q.b1 += A.b1 * Q.w; Q.b2 += A.b2 * Q.w; float iaw = A.w == 0 ? 0.f : Q.w / A.w; // update linear system based on attribute gradients (BB^T/a) for (size_t k = 0; k < attribute_count; ++k) { const QuadricGrad& g = G[k]; Q.a00 -= (g.gx * g.gx) * iaw; Q.a11 -= (g.gy * g.gy) * iaw; Q.a22 -= (g.gz * g.gz) * iaw; Q.a10 -= (g.gx * g.gy) * iaw; Q.a20 -= (g.gx * g.gz) * iaw; Q.a21 -= (g.gy * g.gz) * iaw; Q.b0 -= (g.gx * g.gw) * iaw; Q.b1 -= (g.gy * g.gw) * iaw; Q.b2 -= (g.gz * g.gw) * iaw; } } static void fillFaceQuadrics(Quadric* vertex_quadrics, QuadricGrad* volume_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap) { for (size_t i = 0; i < index_count; i += 3) { unsigned int i0 = indices[i + 0]; unsigned int i1 = indices[i + 1]; unsigned int i2 = indices[i + 2]; Quadric Q; quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], 1.f); quadricAdd(vertex_quadrics[remap[i0]], Q); quadricAdd(vertex_quadrics[remap[i1]], Q); quadricAdd(vertex_quadrics[remap[i2]], Q); if (volume_gradients) { QuadricGrad GV; quadricVolumeGradient(GV, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2]); quadricAdd(volume_gradients[remap[i0]], GV); quadricAdd(volume_gradients[remap[i1]], GV); quadricAdd(volume_gradients[remap[i2]], GV); } } } static void fillVertexQuadrics(Quadric* vertex_quadrics, const Vector3* vertex_positions, size_t vertex_count, const unsigned int* remap, unsigned int options) { // by default, we use a very small weight to improve triangulation and numerical stability without affecting the shape or error float factor = (options & meshopt_SimplifyRegularize) ? 1e-1f : 1e-7f; for (size_t i = 0; i < vertex_count; ++i) { if (remap[i] != i) continue; const Vector3& p = vertex_positions[i]; float w = vertex_quadrics[i].w * factor; Quadric Q; quadricFromPoint(Q, p.x, p.y, p.z, w); quadricAdd(vertex_quadrics[i], Q); } } static void fillEdgeQuadrics(Quadric* vertex_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback) { for (size_t i = 0; i < index_count; i += 3) { static const int next[4] = {1, 2, 0, 1}; for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; unsigned char k0 = vertex_kind[i0]; unsigned char k1 = vertex_kind[i1]; // check that either i0 or i1 are border/seam and are on the same edge loop // note that we need to add the error even for edged that connect e.g. border & locked // if we don't do that, the adjacent border->border edge won't have correct errors for corners if (k0 != Kind_Border && k0 != Kind_Seam && k1 != Kind_Border && k1 != Kind_Seam) continue; if ((k0 == Kind_Border || k0 == Kind_Seam) && loop[i0] != i1) continue; if ((k1 == Kind_Border || k1 == Kind_Seam) && loopback[i1] != i0) continue; unsigned int i2 = indices[i + next[e + 1]]; // we try hard to maintain border edge geometry; seam edges can move more freely // due to topological restrictions on collapses, seam quadrics slightly improves collapse structure but aren't critical const float kEdgeWeightSeam = 0.5f; // applied twice due to opposite edges const float kEdgeWeightBorder = 10.f; float edgeWeight = (k0 == Kind_Border || k1 == Kind_Border) ? kEdgeWeightBorder : kEdgeWeightSeam; Quadric Q; quadricFromTriangleEdge(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight); Quadric QT; quadricFromTriangle(QT, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], edgeWeight); // mix edge quadric with triangle quadric to stabilize collapses in both directions; both quadrics inherit edge weight so that their error is added QT.w = 0; quadricAdd(Q, QT); quadricAdd(vertex_quadrics[remap[i0]], Q); quadricAdd(vertex_quadrics[remap[i1]], Q); } } } static void fillAttributeQuadrics(Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const float* vertex_attributes, size_t attribute_count) { for (size_t i = 0; i < index_count; i += 3) { unsigned int i0 = indices[i + 0]; unsigned int i1 = indices[i + 1]; unsigned int i2 = indices[i + 2]; Quadric QA; QuadricGrad G[kMaxAttributes]; quadricFromAttributes(QA, G, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], &vertex_attributes[i0 * attribute_count], &vertex_attributes[i1 * attribute_count], &vertex_attributes[i2 * attribute_count], attribute_count); quadricAdd(attribute_quadrics[i0], QA); quadricAdd(attribute_quadrics[i1], QA); quadricAdd(attribute_quadrics[i2], QA); quadricAdd(&attribute_gradients[i0 * attribute_count], G, attribute_count); quadricAdd(&attribute_gradients[i1 * attribute_count], G, attribute_count); quadricAdd(&attribute_gradients[i2 * attribute_count], G, attribute_count); } } // does triangle ABC flip when C is replaced with D? static bool hasTriangleFlip(const Vector3& a, const Vector3& b, const Vector3& c, const Vector3& d) { Vector3 eb = {b.x - a.x, b.y - a.y, b.z - a.z}; Vector3 ec = {c.x - a.x, c.y - a.y, c.z - a.z}; Vector3 ed = {d.x - a.x, d.y - a.y, d.z - a.z}; Vector3 nbc = {eb.y * ec.z - eb.z * ec.y, eb.z * ec.x - eb.x * ec.z, eb.x * ec.y - eb.y * ec.x}; Vector3 nbd = {eb.y * ed.z - eb.z * ed.y, eb.z * ed.x - eb.x * ed.z, eb.x * ed.y - eb.y * ed.x}; float ndp = nbc.x * nbd.x + nbc.y * nbd.y + nbc.z * nbd.z; float abc = nbc.x * nbc.x + nbc.y * nbc.y + nbc.z * nbc.z; float abd = nbd.x * nbd.x + nbd.y * nbd.y + nbd.z * nbd.z; // scale is cos(angle); somewhat arbitrarily set to ~75 degrees // note that the "pure" check is ndp <= 0 (90 degree cutoff) but that allows flipping through a series of close-to-90 collapses return ndp <= 0.25f * sqrtf(abc * abd); } static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, const unsigned int* collapse_remap, unsigned int i0, unsigned int i1) { assert(collapse_remap[i0] == i0); assert(collapse_remap[i1] == i1); const Vector3& v0 = vertex_positions[i0]; const Vector3& v1 = vertex_positions[i1]; const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]]; size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0]; for (size_t i = 0; i < count; ++i) { unsigned int a = collapse_remap[edges[i].next]; unsigned int b = collapse_remap[edges[i].prev]; // skip triangles that will get collapsed by i0->i1 collapse or already got collapsed previously if (a == i1 || b == i1 || a == b) continue; // early-out when at least one triangle flips due to a collapse if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1)) { #if TRACE >= 2 printf("edge block %d -> %d: flip welded %d %d %d\n", i0, i1, a, i0, b); #endif return true; } } return false; } static bool hasTriangleFlips(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, unsigned int i0, const Vector3& v1) { const Vector3& v0 = vertex_positions[i0]; const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]]; size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0]; for (size_t i = 0; i < count; ++i) { unsigned int a = edges[i].next, b = edges[i].prev; if (hasTriangleFlip(vertex_positions[a], vertex_positions[b], v0, v1)) return true; } return false; } static float getNeighborhoodRadius(const EdgeAdjacency& adjacency, const Vector3* vertex_positions, unsigned int i0) { const Vector3& v0 = vertex_positions[i0]; const EdgeAdjacency::Edge* edges = &adjacency.data[adjacency.offsets[i0]]; size_t count = adjacency.offsets[i0 + 1] - adjacency.offsets[i0]; float result = 0.f; for (size_t i = 0; i < count; ++i) { unsigned int a = edges[i].next, b = edges[i].prev; const Vector3& va = vertex_positions[a]; const Vector3& vb = vertex_positions[b]; float da = (va.x - v0.x) * (va.x - v0.x) + (va.y - v0.y) * (va.y - v0.y) + (va.z - v0.z) * (va.z - v0.z); float db = (vb.x - v0.x) * (vb.x - v0.x) + (vb.y - v0.y) * (vb.y - v0.y) + (vb.z - v0.z) * (vb.z - v0.z); result = result < da ? da : result; result = result < db ? db : result; } return sqrtf(result); } static unsigned int getComplexTarget(unsigned int v, unsigned int target, const unsigned int* remap, const unsigned int* loop, const unsigned int* loopback) { unsigned int r = remap[target]; // use loop metadata to guide complex collapses towards the correct wedge // this works for edges on attribute discontinuities because loop/loopback track the single half-edge without a pair, similar to seams if (loop[v] != ~0u && remap[loop[v]] == r) return loop[v]; else if (loopback[v] != ~0u && remap[loopback[v]] == r) return loopback[v]; else return target; } static size_t boundEdgeCollapses(const EdgeAdjacency& adjacency, size_t vertex_count, size_t index_count, unsigned char* vertex_kind) { size_t dual_count = 0; for (size_t i = 0; i < vertex_count; ++i) { unsigned char k = vertex_kind[i]; unsigned int e = adjacency.offsets[i + 1] - adjacency.offsets[i]; dual_count += (k == Kind_Manifold || k == Kind_Seam) ? e : 0; } assert(dual_count <= index_count); // pad capacity by 3 so that we can check for overflow once per triangle instead of once per edge return (index_count - dual_count / 2) + 3; } static size_t pickEdgeCollapses(Collapse* collapses, size_t collapse_capacity, const unsigned int* indices, size_t index_count, const unsigned int* remap, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback) { size_t collapse_count = 0; for (size_t i = 0; i < index_count; i += 3) { static const int next[3] = {1, 2, 0}; // this should never happen as boundEdgeCollapses should give an upper bound for the collapse count, but in an unlikely event it does we can just drop extra collapses if (collapse_count + 3 > collapse_capacity) break; for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; // this can happen either when input has a zero-length edge, or when we perform collapses for complex // topology w/seams and collapse a manifold vertex that connects to both wedges onto one of them // we leave edges like this alone since they may be important for preserving mesh integrity if (remap[i0] == remap[i1]) continue; unsigned char k0 = vertex_kind[i0]; unsigned char k1 = vertex_kind[i1]; // the edge has to be collapsible in at least one direction if (!(kCanCollapse[k0][k1] | kCanCollapse[k1][k0])) continue; // manifold and seam edges should occur twice (i0->i1 and i1->i0) - skip redundant edges if (kHasOpposite[k0][k1] && remap[i1] > remap[i0]) continue; // two vertices are on a border or a seam, but there's no direct edge between them // this indicates that they belong to two different edge loops and we should not collapse this edge // loop[] and loopback[] track half edges so we only need to check one of them if ((k0 == Kind_Border || k0 == Kind_Seam) && k1 != Kind_Manifold && loop[i0] != i1) continue; if ((k1 == Kind_Border || k1 == Kind_Seam) && k0 != Kind_Manifold && loopback[i1] != i0) continue; // edge can be collapsed in either direction - we will pick the one with minimum error // note: we evaluate error later during collapse ranking, here we just tag the edge as bidirectional if (kCanCollapse[k0][k1] & kCanCollapse[k1][k0]) { Collapse c = {i0, i1, {/* bidi= */ 1}}; collapses[collapse_count++] = c; } else { // edge can only be collapsed in one direction unsigned int e0 = kCanCollapse[k0][k1] ? i0 : i1; unsigned int e1 = kCanCollapse[k0][k1] ? i1 : i0; Collapse c = {e0, e1, {/* bidi= */ 0}}; collapses[collapse_count++] = c; } } } return collapse_count; } static void rankEdgeCollapses(Collapse* collapses, size_t collapse_count, const Vector3* vertex_positions, const float* vertex_attributes, const Quadric* vertex_quadrics, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback) { for (size_t i = 0; i < collapse_count; ++i) { Collapse& c = collapses[i]; unsigned int i0 = c.v0; unsigned int i1 = c.v1; bool bidi = c.bidi; float ei = quadricError(vertex_quadrics[remap[i0]], vertex_positions[i1]); float ej = bidi ? quadricError(vertex_quadrics[remap[i1]], vertex_positions[i0]) : FLT_MAX; #if TRACE >= 3 float di = ei, dj = ej; #endif if (attribute_count) { ei += quadricError(attribute_quadrics[i0], &attribute_gradients[i0 * attribute_count], attribute_count, vertex_positions[i1], &vertex_attributes[i1 * attribute_count]); ej += bidi ? quadricError(attribute_quadrics[i1], &attribute_gradients[i1 * attribute_count], attribute_count, vertex_positions[i0], &vertex_attributes[i0 * attribute_count]) : 0; // seam edges need to aggregate attribute errors between primary and secondary edges, as attribute quadrics are separate if (vertex_kind[i0] == Kind_Seam) { // for seam collapses we need to find the seam pair; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges) unsigned int s0 = wedge[i0]; unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0]; assert(wedge[s0] == i0); // s0 may be equal to i0 for half-seams assert(s1 != ~0u && remap[s1] == remap[i1]); // note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe s1 = (s1 != ~0u) ? s1 : wedge[i1]; ei += quadricError(attribute_quadrics[s0], &attribute_gradients[s0 * attribute_count], attribute_count, vertex_positions[s1], &vertex_attributes[s1 * attribute_count]); ej += bidi ? quadricError(attribute_quadrics[s1], &attribute_gradients[s1 * attribute_count], attribute_count, vertex_positions[s0], &vertex_attributes[s0 * attribute_count]) : 0; } else { // complex edges can have multiple wedges, so we need to aggregate errors for all wedges based on the selected target if (vertex_kind[i0] == Kind_Complex) for (unsigned int v = wedge[i0]; v != i0; v = wedge[v]) { unsigned int t = getComplexTarget(v, i1, remap, loop, loopback); ei += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]); } if (vertex_kind[i1] == Kind_Complex && bidi) for (unsigned int v = wedge[i1]; v != i1; v = wedge[v]) { unsigned int t = getComplexTarget(v, i0, remap, loop, loopback); ej += quadricError(attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count, vertex_positions[t], &vertex_attributes[t * attribute_count]); } } } // pick edge direction with minimal error (branchless) bool rev = bidi & (ej < ei); c.v0 = rev ? i1 : i0; c.v1 = rev ? i0 : i1; c.error = ej < ei ? ej : ei; #if TRACE >= 3 if (bidi) printf("edge eval %d -> %d: error %f (pos %f, attr %f); reverse %f (pos %f, attr %f)\n", rev ? i1 : i0, rev ? i0 : i1, sqrtf(rev ? ej : ei), sqrtf(rev ? dj : di), sqrtf(rev ? ej - dj : ei - di), sqrtf(rev ? ei : ej), sqrtf(rev ? di : dj), sqrtf(rev ? ei - di : ej - dj)); else printf("edge eval %d -> %d: error %f (pos %f, attr %f)\n", i0, i1, sqrtf(c.error), sqrtf(di), sqrtf(ei - di)); #endif } } static void sortEdgeCollapses(unsigned int* sort_order, const Collapse* collapses, size_t collapse_count) { // we use counting sort to order collapses by error; since the exact sort order is not as critical, // only top 12 bits of exponent+mantissa (8 bits of exponent and 4 bits of mantissa) are used. // to avoid excessive stack usage, we clamp the exponent range as collapses with errors much higher than 1 are not useful. const unsigned int sort_bits = 12; const unsigned int sort_bins = 2048 + 512; // exponent range [-127, 32) // fill histogram for counting sort unsigned int histogram[sort_bins]; memset(histogram, 0, sizeof(histogram)); for (size_t i = 0; i < collapse_count; ++i) { // skip sign bit since error is non-negative unsigned int error = collapses[i].errorui; unsigned int key = (error << 1) >> (32 - sort_bits); key = key < sort_bins ? key : sort_bins - 1; histogram[key]++; } // compute offsets based on histogram data size_t histogram_sum = 0; for (size_t i = 0; i < sort_bins; ++i) { size_t count = histogram[i]; histogram[i] = unsigned(histogram_sum); histogram_sum += count; } assert(histogram_sum == collapse_count); // compute sort order based on offsets for (size_t i = 0; i < collapse_count; ++i) { // skip sign bit since error is non-negative unsigned int error = collapses[i].errorui; unsigned int key = (error << 1) >> (32 - sort_bits); key = key < sort_bins ? key : sort_bins - 1; sort_order[histogram[key]++] = unsigned(i); } } static size_t performEdgeCollapses(unsigned int* collapse_remap, unsigned char* collapse_locked, const Collapse* collapses, size_t collapse_count, const unsigned int* collapse_order, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned int* loop, const unsigned int* loopback, const Vector3* vertex_positions, const EdgeAdjacency& adjacency, size_t triangle_collapse_goal, float error_limit, float& result_error) { size_t edge_collapses = 0; size_t triangle_collapses = 0; // most collapses remove 2 triangles; use this to establish a bound on the pass in terms of error limit // note that edge_collapse_goal is an estimate; triangle_collapse_goal will be used to actually limit collapses size_t edge_collapse_goal = triangle_collapse_goal / 2; #if TRACE size_t stats[7] = {}; #endif for (size_t i = 0; i < collapse_count; ++i) { const Collapse& c = collapses[collapse_order[i]]; TRACESTATS(0); if (c.error > error_limit) { TRACESTATS(4); break; } if (triangle_collapses >= triangle_collapse_goal) { TRACESTATS(5); break; } // we limit the error in each pass based on the error of optimal last collapse; since many collapses will be locked // as they will share vertices with other successfull collapses, we need to increase the acceptable error by some factor float error_goal = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX; // on average, each collapse is expected to lock 6 other collapses; to avoid degenerate passes on meshes with odd // topology, we only abort if we got over 1/6 collapses accordingly. if (c.error > error_goal && c.error > result_error && triangle_collapses > triangle_collapse_goal / 6) { TRACESTATS(6); break; } unsigned int i0 = c.v0; unsigned int i1 = c.v1; unsigned int r0 = remap[i0]; unsigned int r1 = remap[i1]; unsigned char kind = vertex_kind[i0]; // we don't collapse vertices that had source or target vertex involved in a collapse // it's important to not move the vertices twice since it complicates the tracking/remapping logic // it's important to not move other vertices towards a moved vertex to preserve error since we don't re-rank collapses mid-pass if (collapse_locked[r0] | collapse_locked[r1]) { TRACESTATS(1); continue; } if (hasTriangleFlips(adjacency, vertex_positions, collapse_remap, r0, r1)) { // adjust collapse goal since this collapse is invalid and shouldn't factor into error goal edge_collapse_goal++; TRACESTATS(2); continue; } #if TRACE >= 2 printf("edge commit %d -> %d: kind %d->%d, error %f\n", i0, i1, vertex_kind[i0], vertex_kind[i1], sqrtf(c.error)); #endif assert(collapse_remap[r0] == r0); assert(collapse_remap[r1] == r1); if (kind == Kind_Complex) { // remap all vertices in the complex to the target vertex unsigned int v = i0; do { unsigned int t = getComplexTarget(v, i1, remap, loop, loopback); collapse_remap[v] = t; v = wedge[v]; } while (v != i0); } else if (kind == Kind_Seam) { // for seam collapses we need to move the seam pair together; this is a bit tricky since we need to rely on edge loops as target vertex may be locked (and thus have more than two wedges) unsigned int s0 = wedge[i0]; unsigned int s1 = loop[i0] == i1 ? loopback[s0] : loop[s0]; assert(wedge[s0] == i0); // s0 may be equal to i0 for half-seams assert(s1 != ~0u && remap[s1] == r1); // additional asserts to verify that the seam pair is consistent assert(kind != vertex_kind[i1] || s1 == wedge[i1]); assert(loop[i0] == i1 || loopback[i0] == i1); assert(loop[s0] == s1 || loopback[s0] == s1); // note: this should never happen due to the assertion above, but when disabled if we ever hit this case we'll get a memory safety issue; for now play it safe s1 = (s1 != ~0u) ? s1 : wedge[i1]; collapse_remap[i0] = i1; collapse_remap[s0] = s1; } else { assert(wedge[i0] == i0); collapse_remap[i0] = i1; } // note: we technically don't need to lock r1 if it's a locked vertex, as it can't move and its quadric won't be used // however, this results in slightly worse error on some meshes because the locked collapses get an unfair advantage wrt scheduling collapse_locked[r0] = 1; collapse_locked[r1] = 1; // border edges collapse 1 triangle, other edges collapse 2 or more triangle_collapses += (kind == Kind_Border) ? 1 : 2; edge_collapses++; result_error = result_error < c.error ? c.error : result_error; } #if TRACE float error_goal_last = edge_collapse_goal < collapse_count ? 1.5f * collapses[collapse_order[edge_collapse_goal]].error : FLT_MAX; float error_goal_limit = error_goal_last < error_limit ? error_goal_last : error_limit; printf("removed %d triangles, error %e (goal %e); evaluated %d/%d collapses (done %d, skipped %d, invalid %d); %s\n", int(triangle_collapses), sqrtf(result_error), sqrtf(error_goal_limit), int(stats[0]), int(collapse_count), int(edge_collapses), int(stats[1]), int(stats[2]), stats[4] ? "error limit" : (stats[5] ? "count limit" : (stats[6] ? "error goal" : "out of collapses"))); #endif return edge_collapses; } static void updateQuadrics(const unsigned int* collapse_remap, size_t vertex_count, Quadric* vertex_quadrics, QuadricGrad* volume_gradients, Quadric* attribute_quadrics, QuadricGrad* attribute_gradients, size_t attribute_count, const Vector3* vertex_positions, const unsigned int* remap, float& vertex_error) { for (size_t i = 0; i < vertex_count; ++i) { if (collapse_remap[i] == i) continue; unsigned int i0 = unsigned(i); unsigned int i1 = collapse_remap[i]; unsigned int r0 = remap[i0]; unsigned int r1 = remap[i1]; // ensure we only update vertex_quadrics once: primary vertex must be moved if any wedge is moved if (i0 == r0) { quadricAdd(vertex_quadrics[r1], vertex_quadrics[r0]); if (volume_gradients) quadricAdd(volume_gradients[r1], volume_gradients[r0]); } if (attribute_count) { quadricAdd(attribute_quadrics[i1], attribute_quadrics[i0]); quadricAdd(&attribute_gradients[i1 * attribute_count], &attribute_gradients[i0 * attribute_count], attribute_count); if (i0 == r0) { // when attributes are used, distance error needs to be recomputed as collapses don't track it; it is safe to do this after the quadric adjustment float derr = quadricError(vertex_quadrics[r0], vertex_positions[r1]); vertex_error = vertex_error < derr ? derr : vertex_error; } } } } static void solvePositions(Vector3* vertex_positions, size_t vertex_count, const Quadric* vertex_quadrics, const QuadricGrad* volume_gradients, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const EdgeAdjacency& adjacency, const unsigned char* vertex_kind, const unsigned char* vertex_update) { #if TRACE size_t stats[6] = {}; #endif for (size_t i = 0; i < vertex_count; ++i) { if (!vertex_update[i]) continue; // moving vertices on an attribute discontinuity may result in extrapolating UV outside of the chart bounds // moving vertices on a border requires a stronger edge quadric to preserve the border geometry if (vertex_kind[i] == Kind_Locked || vertex_kind[i] == Kind_Seam || vertex_kind[i] == Kind_Border) continue; if (remap[i] != i) { vertex_positions[i] = vertex_positions[remap[i]]; continue; } TRACESTATS(0); const Vector3& vp = vertex_positions[i]; Quadric Q = vertex_quadrics[i]; QuadricGrad GV = {}; // add a point quadric for regularization to stabilize the solution Quadric R; quadricFromPoint(R, vp.x, vp.y, vp.z, Q.w * 1e-4f); quadricAdd(Q, R); if (attribute_count) { // optimal point simultaneously minimizes attribute quadrics for all wedges unsigned int v = unsigned(i); do { quadricReduceAttributes(Q, attribute_quadrics[v], &attribute_gradients[v * attribute_count], attribute_count); v = wedge[v]; } while (v != i); // minimizing attribute quadrics results in volume loss so we incorporate volume gradient as a constraint if (volume_gradients) GV = volume_gradients[i]; } Vector3 p; if (!quadricSolve(p, Q, GV)) { TRACESTATS(2); continue; } // reject updates that move the vertex too far from its neighborhood // this detects and fixes most cases when the quadric is not well-defined float nr = getNeighborhoodRadius(adjacency, vertex_positions, unsigned(i)); float dp = (p.x - vp.x) * (p.x - vp.x) + (p.y - vp.y) * (p.y - vp.y) + (p.z - vp.z) * (p.z - vp.z); if (dp > nr * nr) { TRACESTATS(3); continue; } // reject updates that would flip a neighboring triangle, as we do for edge collapse if (hasTriangleFlips(adjacency, vertex_positions, unsigned(i), p)) { TRACESTATS(4); continue; } // reject updates that increase positional error too much; allow some tolerance to improve attribute quality if (quadricError(vertex_quadrics[i], p) > quadricError(vertex_quadrics[i], vp) * 1.5f + 1e-6f) { TRACESTATS(5); continue; } TRACESTATS(1); vertex_positions[i] = p; } #if TRACE printf("updated %d/%d positions; failed solve %d bounds %d flip %d error %d\n", int(stats[1]), int(stats[0]), int(stats[2]), int(stats[3]), int(stats[4]), int(stats[5])); #endif } static void solveAttributes(Vector3* vertex_positions, float* vertex_attributes, size_t vertex_count, const Quadric* attribute_quadrics, const QuadricGrad* attribute_gradients, size_t attribute_count, const unsigned int* remap, const unsigned int* wedge, const unsigned char* vertex_kind, const unsigned char* vertex_update) { for (size_t i = 0; i < vertex_count; ++i) { if (!vertex_update[i]) continue; if (remap[i] != i) continue; for (size_t k = 0; k < attribute_count; ++k) { unsigned int shared = ~0u; // for complex vertices, preserve attribute continuity and use highest weight wedge if values were shared if (vertex_kind[i] == Kind_Complex) { shared = unsigned(i); for (unsigned int v = wedge[i]; v != i; v = wedge[v]) if (vertex_attributes[v * attribute_count + k] != vertex_attributes[i * attribute_count + k]) shared = ~0u; else if (shared != ~0u && attribute_quadrics[v].w > attribute_quadrics[shared].w) shared = v; } // update attributes for all wedges unsigned int v = unsigned(i); do { unsigned int r = (shared == ~0u) ? v : shared; const Vector3& p = vertex_positions[i]; // same for all wedges const Quadric& A = attribute_quadrics[r]; const QuadricGrad& G = attribute_gradients[r * attribute_count + k]; float iw = A.w == 0 ? 0.f : 1.f / A.w; float av = (G.gx * p.x + G.gy * p.y + G.gz * p.z + G.gw) * iw; vertex_attributes[v * attribute_count + k] = av; v = wedge[v]; } while (v != i); } } } static size_t remapIndexBuffer(unsigned int* indices, size_t index_count, const unsigned int* collapse_remap, const unsigned int* remap) { size_t write = 0; for (size_t i = 0; i < index_count; i += 3) { unsigned int v0 = collapse_remap[indices[i + 0]]; unsigned int v1 = collapse_remap[indices[i + 1]]; unsigned int v2 = collapse_remap[indices[i + 2]]; // we never move the vertex twice during a single pass assert(collapse_remap[v0] == v0); assert(collapse_remap[v1] == v1); assert(collapse_remap[v2] == v2); // collapse zero area triangles even if they are not topologically degenerate // this is required to cleanup manifold->seam collapses when a vertex is collapsed onto a seam pair // as well as complex collapses and some other cases where cross wedge collapses are performed unsigned int r0 = remap[v0]; unsigned int r1 = remap[v1]; unsigned int r2 = remap[v2]; if (r0 != r1 && r0 != r2 && r1 != r2) { indices[write + 0] = v0; indices[write + 1] = v1; indices[write + 2] = v2; write += 3; } } return write; } static void remapEdgeLoops(unsigned int* loop, size_t vertex_count, const unsigned int* collapse_remap) { for (size_t i = 0; i < vertex_count; ++i) { // note: this is a no-op for vertices that were remapped // ideally we would clear the loop entries for those for consistency, even though they aren't going to be used // however, the remapping process needs loop information for remapped vertices, so this would require a separate pass if (loop[i] != ~0u) { unsigned int l = loop[i]; unsigned int r = collapse_remap[l]; // i == r is a special case when the seam edge is collapsed in a direction opposite to where loop goes if (i == r) loop[i] = (loop[l] != ~0u) ? collapse_remap[loop[l]] : ~0u; else loop[i] = r; } } } static unsigned int follow(unsigned int* parents, unsigned int index) { while (index != parents[index]) { unsigned int parent = parents[index]; parents[index] = parents[parent]; index = parent; } return index; } static size_t buildComponents(unsigned int* components, size_t vertex_count, const unsigned int* indices, size_t index_count, const unsigned int* remap) { for (size_t i = 0; i < vertex_count; ++i) components[i] = unsigned(i); // compute a unique (but not sequential!) index for each component via union-find for (size_t i = 0; i < index_count; i += 3) { static const int next[4] = {1, 2, 0, 1}; for (int e = 0; e < 3; ++e) { unsigned int i0 = indices[i + e]; unsigned int i1 = indices[i + next[e]]; unsigned int r0 = remap[i0]; unsigned int r1 = remap[i1]; r0 = follow(components, r0); r1 = follow(components, r1); // merge components with larger indices into components with smaller indices // this guarantees that the root of the component is always the one with the smallest index if (r0 != r1) components[r0 < r1 ? r1 : r0] = r0 < r1 ? r0 : r1; } } // make sure each element points to the component root *before* we renumber the components for (size_t i = 0; i < vertex_count; ++i) if (remap[i] == i) components[i] = follow(components, unsigned(i)); unsigned int next_component = 0; // renumber components using sequential indices // a sequential pass is sufficient because component root always has the smallest index // note: it is unsafe to use follow() in this pass because we're replacing component links with sequential indices inplace for (size_t i = 0; i < vertex_count; ++i) { if (remap[i] == i) { unsigned int root = components[i]; assert(root <= i); // make sure we already computed the component for non-roots components[i] = (root == i) ? next_component++ : components[root]; } else { assert(remap[i] < i); // make sure we already computed the component components[i] = components[remap[i]]; } } return next_component; } static void measureComponents(float* component_errors, size_t component_count, const unsigned int* components, const Vector3* vertex_positions, size_t vertex_count) { memset(component_errors, 0, component_count * 4 * sizeof(float)); // compute approximate sphere center for each component as an average for (size_t i = 0; i < vertex_count; ++i) { unsigned int c = components[i]; assert(components[i] < component_count); Vector3 v = vertex_positions[i]; // copy avoids aliasing issues component_errors[c * 4 + 0] += v.x; component_errors[c * 4 + 1] += v.y; component_errors[c * 4 + 2] += v.z; component_errors[c * 4 + 3] += 1; // weight } // complete the center computation, and reinitialize [3] as a radius for (size_t i = 0; i < component_count; ++i) { float w = component_errors[i * 4 + 3]; float iw = w == 0.f ? 0.f : 1.f / w; component_errors[i * 4 + 0] *= iw; component_errors[i * 4 + 1] *= iw; component_errors[i * 4 + 2] *= iw; component_errors[i * 4 + 3] = 0; // radius } // compute squared radius for each component for (size_t i = 0; i < vertex_count; ++i) { unsigned int c = components[i]; float dx = vertex_positions[i].x - component_errors[c * 4 + 0]; float dy = vertex_positions[i].y - component_errors[c * 4 + 1]; float dz = vertex_positions[i].z - component_errors[c * 4 + 2]; float r = dx * dx + dy * dy + dz * dz; component_errors[c * 4 + 3] = component_errors[c * 4 + 3] < r ? r : component_errors[c * 4 + 3]; } // we've used the output buffer as scratch space, so we need to move the results to proper indices for (size_t i = 0; i < component_count; ++i) { #if TRACE >= 2 printf("component %d: center %f %f %f, error %e\n", int(i), component_errors[i * 4 + 0], component_errors[i * 4 + 1], component_errors[i * 4 + 2], sqrtf(component_errors[i * 4 + 3])); #endif // note: we keep the squared error to make it match quadric error metric component_errors[i] = component_errors[i * 4 + 3]; } } static size_t pruneComponents(unsigned int* indices, size_t index_count, const unsigned int* components, const float* component_errors, size_t component_count, float error_cutoff, float& nexterror) { (void)component_count; size_t write = 0; float min_error = FLT_MAX; for (size_t i = 0; i < index_count; i += 3) { unsigned int v0 = indices[i + 0], v1 = indices[i + 1], v2 = indices[i + 2]; unsigned int c = components[v0]; assert(c == components[v1] && c == components[v2]); if (component_errors[c] > error_cutoff) { min_error = min_error > component_errors[c] ? component_errors[c] : min_error; indices[write + 0] = v0; indices[write + 1] = v1; indices[write + 2] = v2; write += 3; } } #if TRACE size_t pruned_components = 0; for (size_t i = 0; i < component_count; ++i) pruned_components += (component_errors[i] >= nexterror && component_errors[i] <= error_cutoff); printf("pruned %d triangles in %d components (goal %e); next %e\n", int((index_count - write) / 3), int(pruned_components), sqrtf(error_cutoff), min_error < FLT_MAX ? sqrtf(min_error) : min_error * 2); #endif // update next error with the smallest error of the remaining components nexterror = min_error; return write; } struct CellHasher { const unsigned int* vertex_ids; size_t hash(unsigned int i) const { unsigned int h = vertex_ids[i]; // MurmurHash2 finalizer h ^= h >> 13; h *= 0x5bd1e995; h ^= h >> 15; return h; } bool equal(unsigned int lhs, unsigned int rhs) const { return vertex_ids[lhs] == vertex_ids[rhs]; } }; struct IdHasher { size_t hash(unsigned int id) const { unsigned int h = id; // MurmurHash2 finalizer h ^= h >> 13; h *= 0x5bd1e995; h ^= h >> 15; return h; } bool equal(unsigned int lhs, unsigned int rhs) const { return lhs == rhs; } }; struct TriangleHasher { const unsigned int* indices; size_t hash(unsigned int i) const { const unsigned int* tri = indices + i * 3; // Optimized Spatial Hashing for Collision Detection of Deformable Objects return (tri[0] * 73856093) ^ (tri[1] * 19349663) ^ (tri[2] * 83492791); } bool equal(unsigned int lhs, unsigned int rhs) const { const unsigned int* lt = indices + lhs * 3; const unsigned int* rt = indices + rhs * 3; return lt[0] == rt[0] && lt[1] == rt[1] && lt[2] == rt[2]; } }; static void computeVertexIds(unsigned int* vertex_ids, const Vector3* vertex_positions, const unsigned char* vertex_lock, size_t vertex_count, int grid_size) { assert(grid_size >= 1 && grid_size <= 1024); float cell_scale = float(grid_size - 1); for (size_t i = 0; i < vertex_count; ++i) { const Vector3& v = vertex_positions[i]; int xi = int(v.x * cell_scale + 0.5f); int yi = int(v.y * cell_scale + 0.5f); int zi = int(v.z * cell_scale + 0.5f); if (vertex_lock && (vertex_lock[i] & meshopt_SimplifyVertex_Lock)) vertex_ids[i] = (1 << 30) | unsigned(i); else vertex_ids[i] = (xi << 20) | (yi << 10) | zi; } } static size_t countTriangles(const unsigned int* vertex_ids, const unsigned int* indices, size_t index_count) { size_t result = 0; for (size_t i = 0; i < index_count; i += 3) { unsigned int id0 = vertex_ids[indices[i + 0]]; unsigned int id1 = vertex_ids[indices[i + 1]]; unsigned int id2 = vertex_ids[indices[i + 2]]; result += (id0 != id1) & (id0 != id2) & (id1 != id2); } return result; } static size_t fillVertexCells(unsigned int* table, size_t table_size, unsigned int* vertex_cells, const unsigned int* vertex_ids, size_t vertex_count) { CellHasher hasher = {vertex_ids}; memset(table, -1, table_size * sizeof(unsigned int)); size_t result = 0; for (size_t i = 0; i < vertex_count; ++i) { unsigned int* entry = hashLookup2(table, table_size, hasher, unsigned(i), ~0u); if (*entry == ~0u) { *entry = unsigned(i); vertex_cells[i] = unsigned(result++); } else { vertex_cells[i] = vertex_cells[*entry]; } } return result; } static size_t countVertexCells(unsigned int* table, size_t table_size, const unsigned int* vertex_ids, size_t vertex_count) { IdHasher hasher; memset(table, -1, table_size * sizeof(unsigned int)); size_t result = 0; for (size_t i = 0; i < vertex_count; ++i) { unsigned int id = vertex_ids[i]; unsigned int* entry = hashLookup2(table, table_size, hasher, id, ~0u); result += (*entry == ~0u); *entry = id; } return result; } static void fillCellQuadrics(Quadric* cell_quadrics, const unsigned int* indices, size_t index_count, const Vector3* vertex_positions, const unsigned int* vertex_cells) { for (size_t i = 0; i < index_count; i += 3) { unsigned int i0 = indices[i + 0]; unsigned int i1 = indices[i + 1]; unsigned int i2 = indices[i + 2]; unsigned int c0 = vertex_cells[i0]; unsigned int c1 = vertex_cells[i1]; unsigned int c2 = vertex_cells[i2]; int single_cell = (c0 == c1) & (c0 == c2); Quadric Q; quadricFromTriangle(Q, vertex_positions[i0], vertex_positions[i1], vertex_positions[i2], single_cell ? 3.f : 1.f); if (single_cell) { quadricAdd(cell_quadrics[c0], Q); } else { quadricAdd(cell_quadrics[c0], Q); quadricAdd(cell_quadrics[c1], Q); quadricAdd(cell_quadrics[c2], Q); } } } static void fillCellReservoirs(Reservoir* cell_reservoirs, size_t cell_count, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, size_t vertex_count, const unsigned int* vertex_cells) { static const float dummy_color[] = {0.f, 0.f, 0.f}; size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float); for (size_t i = 0; i < vertex_count; ++i) { unsigned int cell = vertex_cells[i]; const Vector3& v = vertex_positions[i]; Reservoir& r = cell_reservoirs[cell]; const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color; r.x += v.x; r.y += v.y; r.z += v.z; r.r += color[0]; r.g += color[1]; r.b += color[2]; r.w += 1.f; } for (size_t i = 0; i < cell_count; ++i) { Reservoir& r = cell_reservoirs[i]; float iw = r.w == 0.f ? 0.f : 1.f / r.w; r.x *= iw; r.y *= iw; r.z *= iw; r.r *= iw; r.g *= iw; r.b *= iw; } } static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Quadric* cell_quadrics, const Vector3* vertex_positions, size_t vertex_count) { memset(cell_remap, -1, cell_count * sizeof(unsigned int)); for (size_t i = 0; i < vertex_count; ++i) { unsigned int cell = vertex_cells[i]; float error = quadricError(cell_quadrics[cell], vertex_positions[i]); if (cell_remap[cell] == ~0u || cell_errors[cell] > error) { cell_remap[cell] = unsigned(i); cell_errors[cell] = error; } } } static void fillCellRemap(unsigned int* cell_remap, float* cell_errors, size_t cell_count, const unsigned int* vertex_cells, const Reservoir* cell_reservoirs, const Vector3* vertex_positions, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t vertex_count) { static const float dummy_color[] = {0.f, 0.f, 0.f}; size_t vertex_colors_stride_float = vertex_colors_stride / sizeof(float); memset(cell_remap, -1, cell_count * sizeof(unsigned int)); for (size_t i = 0; i < vertex_count; ++i) { unsigned int cell = vertex_cells[i]; const Vector3& v = vertex_positions[i]; const Reservoir& r = cell_reservoirs[cell]; const float* color = vertex_colors ? &vertex_colors[i * vertex_colors_stride_float] : dummy_color; float pos_error = (v.x - r.x) * (v.x - r.x) + (v.y - r.y) * (v.y - r.y) + (v.z - r.z) * (v.z - r.z); float col_error = (color[0] - r.r) * (color[0] - r.r) + (color[1] - r.g) * (color[1] - r.g) + (color[2] - r.b) * (color[2] - r.b); float error = pos_error + color_weight * col_error; if (cell_remap[cell] == ~0u || cell_errors[cell] > error) { cell_remap[cell] = unsigned(i); cell_errors[cell] = error; } } } static size_t filterTriangles(unsigned int* destination, unsigned int* tritable, size_t tritable_size, const unsigned int* indices, size_t index_count, const unsigned int* vertex_cells, const unsigned int* cell_remap) { TriangleHasher hasher = {destination}; memset(tritable, -1, tritable_size * sizeof(unsigned int)); size_t result = 0; for (size_t i = 0; i < index_count; i += 3) { unsigned int c0 = vertex_cells[indices[i + 0]]; unsigned int c1 = vertex_cells[indices[i + 1]]; unsigned int c2 = vertex_cells[indices[i + 2]]; if (c0 != c1 && c0 != c2 && c1 != c2) { unsigned int a = cell_remap[c0]; unsigned int b = cell_remap[c1]; unsigned int c = cell_remap[c2]; if (b < a && b < c) { unsigned int t = a; a = b, b = c, c = t; } else if (c < a && c < b) { unsigned int t = c; c = b, b = a, a = t; } destination[result * 3 + 0] = a; destination[result * 3 + 1] = b; destination[result * 3 + 2] = c; unsigned int* entry = hashLookup2(tritable, tritable_size, hasher, unsigned(result), ~0u); if (*entry == ~0u) *entry = unsigned(result++); } } return result * 3; } static float interpolate(float y, float x0, float y0, float x1, float y1, float x2, float y2) { // three point interpolation from "revenge of interpolation search" paper float num = (y1 - y) * (x1 - x2) * (x1 - x0) * (y2 - y0); float den = (y2 - y) * (x1 - x2) * (y0 - y1) + (y0 - y) * (x1 - x0) * (y1 - y2); return x1 + (den == 0.f ? 0.f : num / den); } } // namespace meshopt // Note: this is only exposed for development purposes; do *not* use enum { meshopt_SimplifyInternalSolve = 1 << 29, meshopt_SimplifyInternalDebug = 1 << 30 }; size_t meshopt_simplifyEdge(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(target_index_count <= index_count); assert(target_error >= 0); assert((options & ~(meshopt_SimplifyLockBorder | meshopt_SimplifySparse | meshopt_SimplifyErrorAbsolute | meshopt_SimplifyPrune | meshopt_SimplifyRegularize | meshopt_SimplifyPermissive | meshopt_SimplifyInternalSolve | meshopt_SimplifyInternalDebug)) == 0); assert(vertex_attributes_stride >= attribute_count * sizeof(float) && vertex_attributes_stride <= 256); assert(vertex_attributes_stride % sizeof(float) == 0); assert(attribute_count <= kMaxAttributes); for (size_t i = 0; i < attribute_count; ++i) assert(attribute_weights[i] >= 0); meshopt_Allocator allocator; unsigned int* result = destination; if (result != indices) memcpy(result, indices, index_count * sizeof(unsigned int)); // build an index remap and update indices/vertex_count to minimize the subsequent work // note: as a consequence, errors will be computed relative to the subset extent unsigned int* sparse_remap = NULL; if (options & meshopt_SimplifySparse) sparse_remap = buildSparseRemap(result, index_count, vertex_count, &vertex_count, allocator); // build adjacency information EdgeAdjacency adjacency = {}; prepareEdgeAdjacency(adjacency, index_count, vertex_count, allocator); updateEdgeAdjacency(adjacency, result, index_count, vertex_count, NULL); // build position remap that maps each vertex to the one with identical position // wedge table stores next vertex with identical position for each vertex unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); unsigned int* wedge = allocator.allocate<unsigned int>(vertex_count); buildPositionRemap(remap, wedge, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap, allocator); // classify vertices; vertex kind determines collapse rules, see kCanCollapse unsigned char* vertex_kind = allocator.allocate<unsigned char>(vertex_count); unsigned int* loop = allocator.allocate<unsigned int>(vertex_count); unsigned int* loopback = allocator.allocate<unsigned int>(vertex_count); classifyVertices(vertex_kind, loop, loopback, vertex_count, adjacency, remap, wedge, vertex_lock, sparse_remap, options); #if TRACE size_t unique_positions = 0; for (size_t i = 0; i < vertex_count; ++i) unique_positions += remap[i] == i; printf("position remap: %d vertices => %d positions\n", int(vertex_count), int(unique_positions)); size_t kinds[Kind_Count] = {}; for (size_t i = 0; i < vertex_count; ++i) kinds[vertex_kind[i]] += remap[i] == i; printf("kinds: manifold %d, border %d, seam %d, complex %d, locked %d\n", int(kinds[Kind_Manifold]), int(kinds[Kind_Border]), int(kinds[Kind_Seam]), int(kinds[Kind_Complex]), int(kinds[Kind_Locked])); #endif Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count); float vertex_offset[3] = {}; float vertex_scale = rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, sparse_remap, vertex_offset); float* vertex_attributes = NULL; unsigned int attribute_remap[kMaxAttributes]; if (attribute_count) { // remap attributes to only include ones with weight > 0 to minimize memory/compute overhead for quadrics size_t attributes_used = 0; for (size_t i = 0; i < attribute_count; ++i) if (attribute_weights[i] > 0) attribute_remap[attributes_used++] = unsigned(i); attribute_count = attributes_used; vertex_attributes = allocator.allocate<float>(vertex_count * attribute_count); rescaleAttributes(vertex_attributes, vertex_attributes_data, vertex_count, vertex_attributes_stride, attribute_weights, attribute_count, attribute_remap, sparse_remap); } Quadric* vertex_quadrics = allocator.allocate<Quadric>(vertex_count); memset(vertex_quadrics, 0, vertex_count * sizeof(Quadric)); Quadric* attribute_quadrics = NULL; QuadricGrad* attribute_gradients = NULL; QuadricGrad* volume_gradients = NULL; if (attribute_count) { attribute_quadrics = allocator.allocate<Quadric>(vertex_count); memset(attribute_quadrics, 0, vertex_count * sizeof(Quadric)); attribute_gradients = allocator.allocate<QuadricGrad>(vertex_count * attribute_count); memset(attribute_gradients, 0, vertex_count * attribute_count * sizeof(QuadricGrad)); if (options & meshopt_SimplifyInternalSolve) { volume_gradients = allocator.allocate<QuadricGrad>(vertex_count); memset(volume_gradients, 0, vertex_count * sizeof(QuadricGrad)); } } fillFaceQuadrics(vertex_quadrics, volume_gradients, result, index_count, vertex_positions, remap); fillVertexQuadrics(vertex_quadrics, vertex_positions, vertex_count, remap, options); fillEdgeQuadrics(vertex_quadrics, result, index_count, vertex_positions, remap, vertex_kind, loop, loopback); if (attribute_count) fillAttributeQuadrics(attribute_quadrics, attribute_gradients, result, index_count, vertex_positions, vertex_attributes, attribute_count); unsigned int* components = NULL; float* component_errors = NULL; size_t component_count = 0; float component_nexterror = 0; if (options & meshopt_SimplifyPrune) { components = allocator.allocate<unsigned int>(vertex_count); component_count = buildComponents(components, vertex_count, result, index_count, remap); component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents measureComponents(component_errors, component_count, components, vertex_positions, vertex_count); component_nexterror = FLT_MAX; for (size_t i = 0; i < component_count; ++i) component_nexterror = component_nexterror > component_errors[i] ? component_errors[i] : component_nexterror; #if TRACE printf("components: %d (min error %e)\n", int(component_count), sqrtf(component_nexterror)); #endif } #if TRACE size_t pass_count = 0; #endif size_t collapse_capacity = boundEdgeCollapses(adjacency, vertex_count, index_count, vertex_kind); Collapse* edge_collapses = allocator.allocate<Collapse>(collapse_capacity); unsigned int* collapse_order = allocator.allocate<unsigned int>(collapse_capacity); unsigned int* collapse_remap = allocator.allocate<unsigned int>(vertex_count); unsigned char* collapse_locked = allocator.allocate<unsigned char>(vertex_count); size_t result_count = index_count; float result_error = 0; float vertex_error = 0; // target_error input is linear; we need to adjust it to match quadricError units float error_scale = (options & meshopt_SimplifyErrorAbsolute) ? vertex_scale : 1.f; float error_limit = (target_error * target_error) / (error_scale * error_scale); while (result_count > target_index_count) { // note: throughout the simplification process adjacency structure reflects welded topology for result-in-progress updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap); size_t edge_collapse_count = pickEdgeCollapses(edge_collapses, collapse_capacity, result, result_count, remap, vertex_kind, loop, loopback); assert(edge_collapse_count <= collapse_capacity); // no edges can be collapsed any more due to topology restrictions if (edge_collapse_count == 0) break; #if TRACE printf("pass %d:%c", int(pass_count++), TRACE >= 2 ? '\n' : ' '); #endif rankEdgeCollapses(edge_collapses, edge_collapse_count, vertex_positions, vertex_attributes, vertex_quadrics, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, loop, loopback); sortEdgeCollapses(collapse_order, edge_collapses, edge_collapse_count); size_t triangle_collapse_goal = (result_count - target_index_count) / 3; for (size_t i = 0; i < vertex_count; ++i) collapse_remap[i] = unsigned(i); memset(collapse_locked, 0, vertex_count); size_t collapses = performEdgeCollapses(collapse_remap, collapse_locked, edge_collapses, edge_collapse_count, collapse_order, remap, wedge, vertex_kind, loop, loopback, vertex_positions, adjacency, triangle_collapse_goal, error_limit, result_error); // no edges can be collapsed any more due to hitting the error limit or triangle collapse limit if (collapses == 0) break; updateQuadrics(collapse_remap, vertex_count, vertex_quadrics, volume_gradients, attribute_quadrics, attribute_gradients, attribute_count, vertex_positions, remap, vertex_error); // updateQuadrics will update vertex error if we use attributes, but if we don't then result_error and vertex_error are equivalent vertex_error = attribute_count == 0 ? result_error : vertex_error; // note: we update loops following edge collapses, but after this we might still have stale loop data // this can happen when a triangle with a loop edge gets collapsed along a non-loop edge // that works since a loop that points to a vertex that is no longer connected is not affecting collapse logic remapEdgeLoops(loop, vertex_count, collapse_remap); remapEdgeLoops(loopback, vertex_count, collapse_remap); result_count = remapIndexBuffer(result, result_count, collapse_remap, remap); if ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= vertex_error) result_count = pruneComponents(result, result_count, components, component_errors, component_count, vertex_error, component_nexterror); } // at this point, component_nexterror might be stale: component it references may have been removed through a series of edge collapses bool component_nextstale = true; // we're done with the regular simplification but we're still short of the target; try pruning more aggressively towards error_limit while ((options & meshopt_SimplifyPrune) && result_count > target_index_count && component_nexterror <= error_limit) { #if TRACE printf("pass %d: cleanup; ", int(pass_count++)); #endif float component_cutoff = component_nexterror * 1.5f < error_limit ? component_nexterror * 1.5f : error_limit; // track maximum error in eligible components as we are increasing resulting error float component_maxerror = 0; for (size_t i = 0; i < component_count; ++i) if (component_errors[i] > component_maxerror && component_errors[i] <= component_cutoff) component_maxerror = component_errors[i]; size_t new_count = pruneComponents(result, result_count, components, component_errors, component_count, component_cutoff, component_nexterror); if (new_count == result_count && !component_nextstale) break; component_nextstale = false; // pruneComponents guarantees next error is up to date result_count = new_count; result_error = result_error < component_maxerror ? component_maxerror : result_error; vertex_error = vertex_error < component_maxerror ? component_maxerror : vertex_error; } #if TRACE printf("result: %d triangles, error: %e (pos %.3e); total %d passes\n", int(result_count / 3), sqrtf(result_error), sqrtf(vertex_error), int(pass_count)); #endif // if solve is requested, update input buffers destructively from internal data if (options & meshopt_SimplifyInternalSolve) { unsigned char* vertex_update = collapse_locked; // reuse as scratch space memset(vertex_update, 0, vertex_count); // limit quadric solve to vertices that are still used in the result for (size_t i = 0; i < result_count; ++i) { unsigned int v = result[i]; // mark the vertex for finalizeVertices and root vertex for solve* vertex_update[remap[v]] = vertex_update[v] = 1; } // edge adjacency may be stale as we haven't updated it after last series of edge collapses updateEdgeAdjacency(adjacency, result, result_count, vertex_count, remap); solvePositions(vertex_positions, vertex_count, vertex_quadrics, volume_gradients, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, adjacency, vertex_kind, vertex_update); if (attribute_count) solveAttributes(vertex_positions, vertex_attributes, vertex_count, attribute_quadrics, attribute_gradients, attribute_count, remap, wedge, vertex_kind, vertex_update); finalizeVertices(const_cast<float*>(vertex_positions_data), vertex_positions_stride, const_cast<float*>(vertex_attributes_data), vertex_attributes_stride, attribute_weights, attribute_count, vertex_count, vertex_positions, vertex_attributes, sparse_remap, attribute_remap, vertex_scale, vertex_offset, vertex_kind, vertex_update, vertex_lock); } // if debug visualization data is requested, fill it instead of index data; for simplicity, this doesn't work with sparsity if ((options & meshopt_SimplifyInternalDebug) && !sparse_remap) { assert(Kind_Count <= 8 && vertex_count < (1 << 28)); // 3 bit kind, 1 bit loop for (size_t i = 0; i < result_count; i += 3) { unsigned int a = result[i + 0], b = result[i + 1], c = result[i + 2]; result[i + 0] |= (vertex_kind[a] << 28) | (unsigned(loop[a] == b || loopback[b] == a) << 31); result[i + 1] |= (vertex_kind[b] << 28) | (unsigned(loop[b] == c || loopback[c] == b) << 31); result[i + 2] |= (vertex_kind[c] << 28) | (unsigned(loop[c] == a || loopback[a] == c) << 31); } } // convert resulting indices back into the dense space of the larger mesh if (sparse_remap) for (size_t i = 0; i < result_count; ++i) result[i] = sparse_remap[result[i]]; // result_error is quadratic; we need to remap it back to linear if (out_result_error) *out_result_error = sqrtf(result_error) * error_scale; return result_count; } size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* out_result_error) { assert((options & meshopt_SimplifyInternalSolve) == 0); // use meshopt_simplifyWithUpdate instead return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, 0, NULL, 0, NULL, target_index_count, target_error, options, out_result_error); } size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error) { assert((options & meshopt_SimplifyInternalSolve) == 0); // use meshopt_simplifyWithUpdate instead return meshopt_simplifyEdge(destination, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, vertex_attributes_data, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, out_result_error); } size_t meshopt_simplifyWithUpdate(unsigned int* indices, size_t index_count, float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, float* vertex_attributes_data, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* out_result_error) { return meshopt_simplifyEdge(indices, indices, index_count, vertex_positions_data, vertex_count, vertex_positions_stride, vertex_attributes_data, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options | meshopt_SimplifyInternalSolve, out_result_error); } size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const unsigned char* vertex_lock, size_t target_index_count, float target_error, float* out_result_error) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(target_index_count <= index_count); // we expect to get ~2 triangles/vertex in the output size_t target_cell_count = target_index_count / 6; meshopt_Allocator allocator; Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count); rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride); // find the optimal grid size using guided binary search #if TRACE printf("source: %d vertices, %d triangles\n", int(vertex_count), int(index_count / 3)); printf("target: %d cells, %d triangles\n", int(target_cell_count), int(target_index_count / 3)); #endif unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count); const int kInterpolationPasses = 5; // invariant: # of triangles in min_grid <= target_count int min_grid = int(1.f / (target_error < 1e-3f ? 1e-3f : (target_error < 1.f ? target_error : 1.f))); int max_grid = 1025; size_t min_triangles = 0; size_t max_triangles = index_count / 3; // when we're error-limited, we compute the triangle count for the min. size; this accelerates convergence and provides the correct answer when we can't use a larger grid if (min_grid > 1 || vertex_lock) { computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, min_grid); min_triangles = countTriangles(vertex_ids, indices, index_count); } // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size... int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f); for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass) { if (min_triangles >= target_index_count / 3 || max_grid - min_grid <= 1) break; // we clamp the prediction of the grid size to make sure that the search converges int grid_size = next_grid_size; grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size); computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, grid_size); size_t triangles = countTriangles(vertex_ids, indices, index_count); #if TRACE printf("pass %d (%s): grid size %d, triangles %d, %s\n", pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"), grid_size, int(triangles), (triangles <= target_index_count / 3) ? "under" : "over"); #endif float tip = interpolate(float(size_t(target_index_count / 3)), float(min_grid), float(min_triangles), float(grid_size), float(triangles), float(max_grid), float(max_triangles)); if (triangles <= target_index_count / 3) { min_grid = grid_size; min_triangles = triangles; } else { max_grid = grid_size; max_triangles = triangles; } // we start by using interpolation search - it usually converges faster // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN) next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2; } if (min_triangles == 0) { if (out_result_error) *out_result_error = 1.f; return 0; } // build vertex->cell association by mapping all vertices with the same quantized position to the same cell size_t table_size = hashBuckets2(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count); computeVertexIds(vertex_ids, vertex_positions, vertex_lock, vertex_count, min_grid); size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count); // build a quadric for each target cell Quadric* cell_quadrics = allocator.allocate<Quadric>(cell_count); memset(cell_quadrics, 0, cell_count * sizeof(Quadric)); fillCellQuadrics(cell_quadrics, indices, index_count, vertex_positions, vertex_cells); // for each target cell, find the vertex with the minimal error unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count); float* cell_errors = allocator.allocate<float>(cell_count); fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_quadrics, vertex_positions, vertex_count); // compute error float result_error = 0.f; for (size_t i = 0; i < cell_count; ++i) result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error; // vertex collapses often result in duplicate triangles; we need a table to filter them out size_t tritable_size = hashBuckets2(min_triangles); unsigned int* tritable = allocator.allocate<unsigned int>(tritable_size); // note: this is the first and last write to destination, which allows aliasing destination with indices size_t write = filterTriangles(destination, tritable, tritable_size, indices, index_count, vertex_cells, cell_remap); #if TRACE printf("result: grid size %d, %d cells, %d triangles (%d unfiltered), error %e\n", min_grid, int(cell_count), int(write / 3), int(min_triangles), sqrtf(result_error)); #endif if (out_result_error) *out_result_error = sqrtf(result_error); return write; } size_t meshopt_simplifyPrune(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, float target_error) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(target_error >= 0); meshopt_Allocator allocator; unsigned int* result = destination; if (result != indices) memcpy(result, indices, index_count * sizeof(unsigned int)); // build position remap that maps each vertex to the one with identical position unsigned int* remap = allocator.allocate<unsigned int>(vertex_count); buildPositionRemap(remap, NULL, vertex_positions_data, vertex_count, vertex_positions_stride, NULL, allocator); Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count); rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride, NULL); unsigned int* components = allocator.allocate<unsigned int>(vertex_count); size_t component_count = buildComponents(components, vertex_count, indices, index_count, remap); float* component_errors = allocator.allocate<float>(component_count * 4); // overallocate for temporary use inside measureComponents measureComponents(component_errors, component_count, components, vertex_positions, vertex_count); float component_nexterror = 0; size_t result_count = pruneComponents(result, index_count, components, component_errors, component_count, target_error * target_error, component_nexterror); return result_count; } size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count) { using namespace meshopt; assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(vertex_colors_stride == 0 || (vertex_colors_stride >= 12 && vertex_colors_stride <= 256)); assert(vertex_colors_stride % sizeof(float) == 0); assert(vertex_colors == NULL || vertex_colors_stride != 0); assert(target_vertex_count <= vertex_count); size_t target_cell_count = target_vertex_count; if (target_cell_count == 0) return 0; meshopt_Allocator allocator; Vector3* vertex_positions = allocator.allocate<Vector3>(vertex_count); rescalePositions(vertex_positions, vertex_positions_data, vertex_count, vertex_positions_stride); // find the optimal grid size using guided binary search #if TRACE printf("source: %d vertices\n", int(vertex_count)); printf("target: %d cells\n", int(target_cell_count)); #endif unsigned int* vertex_ids = allocator.allocate<unsigned int>(vertex_count); size_t table_size = hashBuckets2(vertex_count); unsigned int* table = allocator.allocate<unsigned int>(table_size); const int kInterpolationPasses = 5; // invariant: # of vertices in min_grid <= target_count int min_grid = 0; int max_grid = 1025; size_t min_vertices = 0; size_t max_vertices = vertex_count; // instead of starting in the middle, let's guess as to what the answer might be! triangle count usually grows as a square of grid size... int next_grid_size = int(sqrtf(float(target_cell_count)) + 0.5f); for (int pass = 0; pass < 10 + kInterpolationPasses; ++pass) { assert(min_vertices < target_vertex_count); assert(max_grid - min_grid > 1); // we clamp the prediction of the grid size to make sure that the search converges int grid_size = next_grid_size; grid_size = (grid_size <= min_grid) ? min_grid + 1 : (grid_size >= max_grid ? max_grid - 1 : grid_size); computeVertexIds(vertex_ids, vertex_positions, NULL, vertex_count, grid_size); size_t vertices = countVertexCells(table, table_size, vertex_ids, vertex_count); #if TRACE printf("pass %d (%s): grid size %d, vertices %d, %s\n", pass, (pass == 0) ? "guess" : (pass <= kInterpolationPasses ? "lerp" : "binary"), grid_size, int(vertices), (vertices <= target_vertex_count) ? "under" : "over"); #endif float tip = interpolate(float(target_vertex_count), float(min_grid), float(min_vertices), float(grid_size), float(vertices), float(max_grid), float(max_vertices)); if (vertices <= target_vertex_count) { min_grid = grid_size; min_vertices = vertices; } else { max_grid = grid_size; max_vertices = vertices; } if (vertices == target_vertex_count || max_grid - min_grid <= 1) break; // we start by using interpolation search - it usually converges faster // however, interpolation search has a worst case of O(N) so we switch to binary search after a few iterations which converges in O(logN) next_grid_size = (pass < kInterpolationPasses) ? int(tip + 0.5f) : (min_grid + max_grid) / 2; } if (min_vertices == 0) return 0; // build vertex->cell association by mapping all vertices with the same quantized position to the same cell unsigned int* vertex_cells = allocator.allocate<unsigned int>(vertex_count); computeVertexIds(vertex_ids, vertex_positions, NULL, vertex_count, min_grid); size_t cell_count = fillVertexCells(table, table_size, vertex_cells, vertex_ids, vertex_count); // accumulate points into a reservoir for each target cell Reservoir* cell_reservoirs = allocator.allocate<Reservoir>(cell_count); memset(cell_reservoirs, 0, cell_count * sizeof(Reservoir)); fillCellReservoirs(cell_reservoirs, cell_count, vertex_positions, vertex_colors, vertex_colors_stride, vertex_count, vertex_cells); // for each target cell, find the vertex with the minimal error unsigned int* cell_remap = allocator.allocate<unsigned int>(cell_count); float* cell_errors = allocator.allocate<float>(cell_count); // we scale the color weight to bring it to the same scale as position so that error addition makes sense float color_weight_scaled = color_weight * (min_grid == 1 ? 1.f : 1.f / (min_grid - 1)); fillCellRemap(cell_remap, cell_errors, cell_count, vertex_cells, cell_reservoirs, vertex_positions, vertex_colors, vertex_colors_stride, color_weight_scaled * color_weight_scaled, vertex_count); // copy results to the output assert(cell_count <= target_vertex_count); memcpy(destination, cell_remap, sizeof(unsigned int) * cell_count); #if TRACE // compute error float result_error = 0.f; for (size_t i = 0; i < cell_count; ++i) result_error = result_error < cell_errors[i] ? cell_errors[i] : result_error; printf("result: %d cells, %e error\n", int(cell_count), sqrtf(result_error)); #endif return cell_count; } float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); float extent = rescalePositions(NULL, vertex_positions, vertex_count, vertex_positions_stride); return extent; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/spatialorder.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <float.h> #include <string.h> // This work is based on: // Fabian Giesen. Decoding Morton codes. 2009 namespace meshopt { // "Insert" two 0 bits after each of the 20 low bits of x inline unsigned long long part1By2(unsigned long long x) { x &= 0x000fffffull; // x = ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- jihg fedc ba98 7654 3210 x = (x ^ (x << 32)) & 0x000f00000000ffffull; // x = ---- ---- ---- jihg ---- ---- ---- ---- ---- ---- ---- ---- fedc ba98 7654 3210 x = (x ^ (x << 16)) & 0x000f0000ff0000ffull; // x = ---- ---- ---- jihg ---- ---- ---- ---- fedc ba98 ---- ---- ---- ---- 7654 3210 x = (x ^ (x << 8)) & 0x000f00f00f00f00full; // x = ---- ---- ---- jihg ---- ---- fedc ---- ---- ba98 ---- ---- 7654 ---- ---- 3210 x = (x ^ (x << 4)) & 0x00c30c30c30c30c3ull; // x = ---- ---- ji-- --hg ---- fe-- --dc ---- ba-- --98 ---- 76-- --54 ---- 32-- --10 x = (x ^ (x << 2)) & 0x0249249249249249ull; // x = ---- --j- -i-- h--g --f- -e-- d--c --b- -a-- 9--8 --7- -6-- 5--4 --3- -2-- 1--0 return x; } static void computeOrder(unsigned long long* result, const float* vertex_positions_data, size_t vertex_count, size_t vertex_positions_stride, bool morton) { size_t vertex_stride_float = vertex_positions_stride / sizeof(float); float minv[3] = {FLT_MAX, FLT_MAX, FLT_MAX}; float maxv[3] = {-FLT_MAX, -FLT_MAX, -FLT_MAX}; for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions_data + i * vertex_stride_float; for (int j = 0; j < 3; ++j) { float vj = v[j]; minv[j] = minv[j] > vj ? vj : minv[j]; maxv[j] = maxv[j] < vj ? vj : maxv[j]; } } float extent = 0.f; extent = (maxv[0] - minv[0]) < extent ? extent : (maxv[0] - minv[0]); extent = (maxv[1] - minv[1]) < extent ? extent : (maxv[1] - minv[1]); extent = (maxv[2] - minv[2]) < extent ? extent : (maxv[2] - minv[2]); // rescale each axis to 16 bits to get 48-bit Morton codes float scale = extent == 0 ? 0.f : 65535.f / extent; // generate Morton order based on the position inside a unit cube for (size_t i = 0; i < vertex_count; ++i) { const float* v = vertex_positions_data + i * vertex_stride_float; int x = int((v[0] - minv[0]) * scale + 0.5f); int y = int((v[1] - minv[1]) * scale + 0.5f); int z = int((v[2] - minv[2]) * scale + 0.5f); if (morton) result[i] = part1By2(x) | (part1By2(y) << 1) | (part1By2(z) << 2); else result[i] = ((unsigned long long)x << 0) | ((unsigned long long)y << 20) | ((unsigned long long)z << 40); } } static void radixSort10(unsigned int* destination, const unsigned int* source, const unsigned short* keys, size_t count) { unsigned int hist[1024]; memset(hist, 0, sizeof(hist)); // compute histogram (assume keys are 10-bit) for (size_t i = 0; i < count; ++i) hist[keys[i]]++; unsigned int sum = 0; // replace histogram data with prefix histogram sums in-place for (int i = 0; i < 1024; ++i) { unsigned int h = hist[i]; hist[i] = sum; sum += h; } assert(sum == count); // reorder values for (size_t i = 0; i < count; ++i) { unsigned int id = keys[source[i]]; destination[hist[id]++] = source[i]; } } static void computeHistogram(unsigned int (&hist)[256][2], const unsigned short* data, size_t count) { memset(hist, 0, sizeof(hist)); // compute 2 8-bit histograms in parallel for (size_t i = 0; i < count; ++i) { unsigned long long id = data[i]; hist[(id >> 0) & 255][0]++; hist[(id >> 8) & 255][1]++; } unsigned int sum0 = 0, sum1 = 0; // replace histogram data with prefix histogram sums in-place for (int i = 0; i < 256; ++i) { unsigned int h0 = hist[i][0], h1 = hist[i][1]; hist[i][0] = sum0; hist[i][1] = sum1; sum0 += h0; sum1 += h1; } assert(sum0 == count && sum1 == count); } static void radixPass(unsigned int* destination, const unsigned int* source, const unsigned short* keys, size_t count, unsigned int (&hist)[256][2], int pass) { int bitoff = pass * 8; for (size_t i = 0; i < count; ++i) { unsigned int id = unsigned(keys[source[i]] >> bitoff) & 255; destination[hist[id][pass]++] = source[i]; } } static void partitionPoints(unsigned int* target, const unsigned int* order, const unsigned char* sides, size_t split, size_t count) { size_t l = 0, r = split; for (size_t i = 0; i < count; ++i) { unsigned char side = sides[order[i]]; target[side ? r : l] = order[i]; l += 1; l -= side; r += side; } assert(l == split && r == count); } static void splitPoints(unsigned int* destination, unsigned int* orderx, unsigned int* ordery, unsigned int* orderz, const unsigned long long* keys, size_t count, void* scratch, size_t cluster_size) { if (count <= cluster_size) { memcpy(destination, orderx, count * sizeof(unsigned int)); return; } unsigned int* axes[3] = {orderx, ordery, orderz}; int bestk = -1; unsigned int bestdim = 0; for (int k = 0; k < 3; ++k) { const unsigned int mask = (1 << 20) - 1; unsigned int dim = (unsigned(keys[axes[k][count - 1]] >> (k * 20)) & mask) - (unsigned(keys[axes[k][0]] >> (k * 20)) & mask); if (dim >= bestdim) { bestk = k; bestdim = dim; } } assert(bestk >= 0); // split roughly in half, with the left split always being aligned to cluster size size_t split = ((count / 2) + cluster_size - 1) / cluster_size * cluster_size; assert(split > 0 && split < count); // mark sides of split for partitioning unsigned char* sides = static_cast<unsigned char*>(scratch) + count * sizeof(unsigned int); for (size_t i = 0; i < split; ++i) sides[axes[bestk][i]] = 0; for (size_t i = split; i < count; ++i) sides[axes[bestk][i]] = 1; // partition all axes into two sides, maintaining order unsigned int* temp = static_cast<unsigned int*>(scratch); for (int k = 0; k < 3; ++k) { if (k == bestk) continue; unsigned int* axis = axes[k]; memcpy(temp, axis, sizeof(unsigned int) * count); partitionPoints(axis, temp, sides, split, count); } // recursion depth is logarithmic and bounded as we always split in approximately half splitPoints(destination, orderx, ordery, orderz, keys, split, scratch, cluster_size); splitPoints(destination + split, orderx + split, ordery + split, orderz + split, keys, count - split, scratch, cluster_size); } } // namespace meshopt void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); meshopt_Allocator allocator; unsigned long long* keys = allocator.allocate<unsigned long long>(vertex_count); computeOrder(keys, vertex_positions, vertex_count, vertex_positions_stride, /* morton= */ true); unsigned int* scratch = allocator.allocate<unsigned int>(vertex_count * 2); // 4b for order + 2b for keys unsigned short* keyk = (unsigned short*)(scratch + vertex_count); for (size_t i = 0; i < vertex_count; ++i) destination[i] = unsigned(i); unsigned int* order[] = {scratch, destination}; // 5-pass radix sort computes the resulting order into scratch for (int k = 0; k < 5; ++k) { // copy 10-bit key segments into keyk to reduce cache pressure during radix pass for (size_t i = 0; i < vertex_count; ++i) keyk[i] = (unsigned short)((keys[i] >> (k * 10)) & 1023); radixSort10(order[k % 2], order[(k + 1) % 2], keyk, vertex_count); } // since our remap table is mapping old=>new, we need to reverse it for (size_t i = 0; i < vertex_count; ++i) destination[scratch[i]] = unsigned(i); } void meshopt_spatialSortTriangles(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride) { using namespace meshopt; assert(index_count % 3 == 0); assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); (void)vertex_count; size_t face_count = index_count / 3; size_t vertex_stride_float = vertex_positions_stride / sizeof(float); meshopt_Allocator allocator; float* centroids = allocator.allocate<float>(face_count * 3); for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; assert(a < vertex_count && b < vertex_count && c < vertex_count); const float* va = vertex_positions + a * vertex_stride_float; const float* vb = vertex_positions + b * vertex_stride_float; const float* vc = vertex_positions + c * vertex_stride_float; centroids[i * 3 + 0] = (va[0] + vb[0] + vc[0]) / 3.f; centroids[i * 3 + 1] = (va[1] + vb[1] + vc[1]) / 3.f; centroids[i * 3 + 2] = (va[2] + vb[2] + vc[2]) / 3.f; } unsigned int* remap = allocator.allocate<unsigned int>(face_count); meshopt_spatialSortRemap(remap, centroids, face_count, sizeof(float) * 3); // support in-order remap if (destination == indices) { unsigned int* indices_copy = allocator.allocate<unsigned int>(index_count); memcpy(indices_copy, indices, index_count * sizeof(unsigned int)); indices = indices_copy; } for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; unsigned int r = remap[i]; destination[r * 3 + 0] = a; destination[r * 3 + 1] = b; destination[r * 3 + 2] = c; } } void meshopt_spatialClusterPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t cluster_size) { using namespace meshopt; assert(vertex_positions_stride >= 12 && vertex_positions_stride <= 256); assert(vertex_positions_stride % sizeof(float) == 0); assert(cluster_size > 0); meshopt_Allocator allocator; unsigned long long* keys = allocator.allocate<unsigned long long>(vertex_count); computeOrder(keys, vertex_positions, vertex_count, vertex_positions_stride, /* morton= */ false); unsigned int* order = allocator.allocate<unsigned int>(vertex_count * 3); unsigned int* scratch = allocator.allocate<unsigned int>(vertex_count * 2); // 4b for order + 1b for side or 2b for keys unsigned short* keyk = reinterpret_cast<unsigned short*>(scratch + vertex_count); for (int k = 0; k < 3; ++k) { // copy 16-bit key segments into keyk to reduce cache pressure during radix pass for (size_t i = 0; i < vertex_count; ++i) keyk[i] = (unsigned short)(keys[i] >> (k * 20)); unsigned int hist[256][2]; computeHistogram(hist, keyk, vertex_count); for (size_t i = 0; i < vertex_count; ++i) order[k * vertex_count + i] = unsigned(i); radixPass(scratch, order + k * vertex_count, keyk, vertex_count, hist, 0); radixPass(order + k * vertex_count, scratch, keyk, vertex_count, hist, 1); } splitPoints(destination, order, order + vertex_count, order + 2 * vertex_count, keys, vertex_count, scratch, cluster_size); }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/stripifier.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <limits.h> #include <string.h> // This work is based on: // Francine Evans, Steven Skiena and Amitabh Varshney. Optimizing Triangle Strips for Fast Rendering. 1996 namespace meshopt { static unsigned int findStripFirst(const unsigned int buffer[][3], unsigned int buffer_size, const unsigned char* valence) { unsigned int index = 0; unsigned int iv = ~0u; for (size_t i = 0; i < buffer_size; ++i) { unsigned char va = valence[buffer[i][0]], vb = valence[buffer[i][1]], vc = valence[buffer[i][2]]; unsigned int v = (va < vb && va < vc) ? va : (vb < vc ? vb : vc); if (v < iv) { index = unsigned(i); iv = v; } } return index; } static int findStripNext(const unsigned int buffer[][3], unsigned int buffer_size, unsigned int e0, unsigned int e1) { for (size_t i = 0; i < buffer_size; ++i) { unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; if (e0 == a && e1 == b) return (int(i) << 2) | 2; else if (e0 == b && e1 == c) return (int(i) << 2) | 0; else if (e0 == c && e1 == a) return (int(i) << 2) | 1; } return -1; } } // namespace meshopt size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index) { assert(destination != indices); assert(index_count % 3 == 0); using namespace meshopt; meshopt_Allocator allocator; const size_t buffer_capacity = 8; unsigned int buffer[buffer_capacity][3] = {}; unsigned int buffer_size = 0; size_t index_offset = 0; unsigned int strip[2] = {}; unsigned int parity = 0; size_t strip_size = 0; // compute vertex valence; this is used to prioritize starting triangle for strips // note: we use 8-bit counters for performance; for outlier vertices the valence is incorrect but that just affects the heuristic unsigned char* valence = allocator.allocate<unsigned char>(vertex_count); memset(valence, 0, vertex_count); for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); valence[index]++; } int next = -1; while (buffer_size > 0 || index_offset < index_count) { assert(next < 0 || (size_t(next >> 2) < buffer_size && (next & 3) < 3)); // fill triangle buffer while (buffer_size < buffer_capacity && index_offset < index_count) { buffer[buffer_size][0] = indices[index_offset + 0]; buffer[buffer_size][1] = indices[index_offset + 1]; buffer[buffer_size][2] = indices[index_offset + 2]; buffer_size++; index_offset += 3; } assert(buffer_size > 0); if (next >= 0) { unsigned int i = next >> 2; unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; unsigned int v = buffer[i][next & 3]; // ordered removal from the buffer memmove(buffer[i], buffer[i + 1], (buffer_size - i - 1) * sizeof(buffer[0])); buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // find next triangle (note that edge order flips on every iteration) // in some cases we need to perform a swap to pick a different outgoing triangle edge // for [a b c], the default strip edge is [b c], but we might want to use [a c] int cont = findStripNext(buffer, buffer_size, parity ? strip[1] : v, parity ? v : strip[1]); int swap = cont < 0 ? findStripNext(buffer, buffer_size, parity ? v : strip[0], parity ? strip[0] : v) : -1; if (cont < 0 && swap >= 0) { // [a b c] => [a b a c] destination[strip_size++] = strip[0]; destination[strip_size++] = v; // next strip has same winding // ? a b => b a v strip[1] = v; next = swap; } else { // emit the next vertex in the strip destination[strip_size++] = v; // next strip has flipped winding strip[0] = strip[1]; strip[1] = v; parity ^= 1; next = cont; } } else { // if we didn't find anything, we need to find the next new triangle // we use a heuristic to maximize the strip length unsigned int i = findStripFirst(buffer, buffer_size, valence); unsigned int a = buffer[i][0], b = buffer[i][1], c = buffer[i][2]; // ordered removal from the buffer memmove(buffer[i], buffer[i + 1], (buffer_size - i - 1) * sizeof(buffer[0])); buffer_size--; // update vertex valences for strip start heuristic valence[a]--; valence[b]--; valence[c]--; // we need to pre-rotate the triangle so that we will find a match in the existing buffer on the next iteration int ea = findStripNext(buffer, buffer_size, c, b); int eb = findStripNext(buffer, buffer_size, a, c); int ec = findStripNext(buffer, buffer_size, b, a); // in some cases we can have several matching edges; since we can pick any edge, we pick the one with the smallest // triangle index in the buffer. this reduces the effect of stripification on ACMR and additionally - for unclear // reasons - slightly improves the stripification efficiency int mine = INT_MAX; mine = (ea >= 0 && mine > ea) ? ea : mine; mine = (eb >= 0 && mine > eb) ? eb : mine; mine = (ec >= 0 && mine > ec) ? ec : mine; if (ea == mine) { // keep abc next = ea; } else if (eb == mine) { // abc -> bca unsigned int t = a; a = b, b = c, c = t; next = eb; } else if (ec == mine) { // abc -> cab unsigned int t = c; c = b, b = a, a = t; next = ec; } if (restart_index) { if (strip_size) destination[strip_size++] = restart_index; destination[strip_size++] = a; destination[strip_size++] = b; destination[strip_size++] = c; // new strip always starts with the same edge winding strip[0] = b; strip[1] = c; parity = 1; } else { if (strip_size) { // connect last strip using degenerate triangles destination[strip_size++] = strip[1]; destination[strip_size++] = a; } // note that we may need to flip the emitted triangle based on parity // we always end up with outgoing edge "cb" in the end unsigned int e0 = parity ? c : b; unsigned int e1 = parity ? b : c; destination[strip_size++] = a; destination[strip_size++] = e0; destination[strip_size++] = e1; strip[0] = e0; strip[1] = e1; parity ^= 1; } } } return strip_size; } size_t meshopt_stripifyBound(size_t index_count) { assert(index_count % 3 == 0); // worst case without restarts is 2 degenerate indices and 3 indices per triangle // worst case with restarts is 1 restart index and 3 indices per triangle return (index_count / 3) * 5; } size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index) { assert(destination != indices); size_t offset = 0; size_t start = 0; for (size_t i = 0; i < index_count; ++i) { if (restart_index && indices[i] == restart_index) { start = i + 1; } else if (i - start >= 2) { unsigned int a = indices[i - 2], b = indices[i - 1], c = indices[i]; // flip winding for odd triangles if ((i - start) & 1) { unsigned int t = a; a = b, b = t; } // although we use restart indices, strip swaps still produce degenerate triangles, so skip them if (a != b && a != c && b != c) { destination[offset + 0] = a; destination[offset + 1] = b; destination[offset + 2] = c; offset += 3; } } } return offset; } size_t meshopt_unstripifyBound(size_t index_count) { assert(index_count == 0 || index_count >= 3); return (index_count == 0) ? 0 : (index_count - 2) * 3; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/vcacheoptimizer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> // This work is based on: // Tom Forsyth. Linear-Speed Vertex Cache Optimisation. 2006 // Pedro Sander, Diego Nehab and Joshua Barczak. Fast Triangle Reordering for Vertex Locality and Reduced Overdraw. 2007 namespace meshopt { const size_t kCacheSizeMax = 16; const size_t kValenceMax = 8; struct VertexScoreTable { float cache[1 + kCacheSizeMax]; float live[1 + kValenceMax]; }; // Tuned to minimize the ACMR of a GPU that has a cache profile similar to NVidia and AMD static const VertexScoreTable kVertexScoreTable = { {0.f, 0.779f, 0.791f, 0.789f, 0.981f, 0.843f, 0.726f, 0.847f, 0.882f, 0.867f, 0.799f, 0.642f, 0.613f, 0.600f, 0.568f, 0.372f, 0.234f}, {0.f, 0.995f, 0.713f, 0.450f, 0.404f, 0.059f, 0.005f, 0.147f, 0.006f}, }; // Tuned to minimize the encoded index buffer size static const VertexScoreTable kVertexScoreTableStrip = { {0.f, 1.000f, 1.000f, 1.000f, 0.453f, 0.561f, 0.490f, 0.459f, 0.179f, 0.526f, 0.000f, 0.227f, 0.184f, 0.490f, 0.112f, 0.050f, 0.131f}, {0.f, 0.956f, 0.786f, 0.577f, 0.558f, 0.618f, 0.549f, 0.499f, 0.489f}, }; struct TriangleAdjacency { unsigned int* counts; unsigned int* offsets; unsigned int* data; }; static void buildTriangleAdjacency(TriangleAdjacency& adjacency, const unsigned int* indices, size_t index_count, size_t vertex_count, meshopt_Allocator& allocator) { size_t face_count = index_count / 3; // allocate arrays adjacency.counts = allocator.allocate<unsigned int>(vertex_count); adjacency.offsets = allocator.allocate<unsigned int>(vertex_count); adjacency.data = allocator.allocate<unsigned int>(index_count); // fill triangle counts memset(adjacency.counts, 0, vertex_count * sizeof(unsigned int)); for (size_t i = 0; i < index_count; ++i) { assert(indices[i] < vertex_count); adjacency.counts[indices[i]]++; } // fill offset table unsigned int offset = 0; for (size_t i = 0; i < vertex_count; ++i) { adjacency.offsets[i] = offset; offset += adjacency.counts[i]; } assert(offset == index_count); // fill triangle data for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0], b = indices[i * 3 + 1], c = indices[i * 3 + 2]; adjacency.data[adjacency.offsets[a]++] = unsigned(i); adjacency.data[adjacency.offsets[b]++] = unsigned(i); adjacency.data[adjacency.offsets[c]++] = unsigned(i); } // fix offsets that have been disturbed by the previous pass for (size_t i = 0; i < vertex_count; ++i) { assert(adjacency.offsets[i] >= adjacency.counts[i]); adjacency.offsets[i] -= adjacency.counts[i]; } } static unsigned int getNextVertexDeadEnd(const unsigned int* dead_end, unsigned int& dead_end_top, unsigned int& input_cursor, const unsigned int* live_triangles, size_t vertex_count) { // check dead-end stack while (dead_end_top) { unsigned int vertex = dead_end[--dead_end_top]; if (live_triangles[vertex] > 0) return vertex; } // input order while (input_cursor < vertex_count) { if (live_triangles[input_cursor] > 0) return input_cursor; ++input_cursor; } return ~0u; } static unsigned int getNextVertexNeighbor(const unsigned int* next_candidates_begin, const unsigned int* next_candidates_end, const unsigned int* live_triangles, const unsigned int* cache_timestamps, unsigned int timestamp, unsigned int cache_size) { unsigned int best_candidate = ~0u; int best_priority = -1; for (const unsigned int* next_candidate = next_candidates_begin; next_candidate != next_candidates_end; ++next_candidate) { unsigned int vertex = *next_candidate; // otherwise we don't need to process it if (live_triangles[vertex] > 0) { int priority = 0; // will it be in cache after fanning? if (2 * live_triangles[vertex] + timestamp - cache_timestamps[vertex] <= cache_size) { priority = timestamp - cache_timestamps[vertex]; // position in cache } if (priority > best_priority) { best_candidate = vertex; best_priority = priority; } } } return best_candidate; } static float vertexScore(const VertexScoreTable* table, int cache_position, unsigned int live_triangles) { assert(cache_position >= -1 && cache_position < int(kCacheSizeMax)); unsigned int live_triangles_clamped = live_triangles < kValenceMax ? live_triangles : kValenceMax; return table->cache[1 + cache_position] + table->live[live_triangles_clamped]; } static unsigned int getNextTriangleDeadEnd(unsigned int& input_cursor, const unsigned char* emitted_flags, size_t face_count) { // input order while (input_cursor < face_count) { if (!emitted_flags[input_cursor]) return input_cursor; ++input_cursor; } return ~0u; } } // namespace meshopt void meshopt_optimizeVertexCacheTable(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const meshopt::VertexScoreTable* table) { using namespace meshopt; assert(index_count % 3 == 0); meshopt_Allocator allocator; // guard for empty meshes if (index_count == 0 || vertex_count == 0) return; // support in-place optimization if (destination == indices) { unsigned int* indices_copy = allocator.allocate<unsigned int>(index_count); memcpy(indices_copy, indices, index_count * sizeof(unsigned int)); indices = indices_copy; } unsigned int cache_size = 16; assert(cache_size <= kCacheSizeMax); size_t face_count = index_count / 3; // build adjacency information TriangleAdjacency adjacency = {}; buildTriangleAdjacency(adjacency, indices, index_count, vertex_count, allocator); // live triangle counts; note, we alias adjacency.counts as we remove triangles after emitting them so the counts always match unsigned int* live_triangles = adjacency.counts; // emitted flags unsigned char* emitted_flags = allocator.allocate<unsigned char>(face_count); memset(emitted_flags, 0, face_count); // compute initial vertex scores float* vertex_scores = allocator.allocate<float>(vertex_count); for (size_t i = 0; i < vertex_count; ++i) vertex_scores[i] = vertexScore(table, -1, live_triangles[i]); // compute triangle scores float* triangle_scores = allocator.allocate<float>(face_count); for (size_t i = 0; i < face_count; ++i) { unsigned int a = indices[i * 3 + 0]; unsigned int b = indices[i * 3 + 1]; unsigned int c = indices[i * 3 + 2]; triangle_scores[i] = vertex_scores[a] + vertex_scores[b] + vertex_scores[c]; } unsigned int cache_holder[2 * (kCacheSizeMax + 4)]; unsigned int* cache = cache_holder; unsigned int* cache_new = cache_holder + kCacheSizeMax + 4; size_t cache_count = 0; unsigned int current_triangle = 0; unsigned int input_cursor = 1; unsigned int output_triangle = 0; while (current_triangle != ~0u) { assert(output_triangle < face_count); unsigned int a = indices[current_triangle * 3 + 0]; unsigned int b = indices[current_triangle * 3 + 1]; unsigned int c = indices[current_triangle * 3 + 2]; // output indices destination[output_triangle * 3 + 0] = a; destination[output_triangle * 3 + 1] = b; destination[output_triangle * 3 + 2] = c; output_triangle++; // update emitted flags emitted_flags[current_triangle] = true; triangle_scores[current_triangle] = 0; // new triangle size_t cache_write = 0; cache_new[cache_write++] = a; cache_new[cache_write++] = b; cache_new[cache_write++] = c; // old triangles for (size_t i = 0; i < cache_count; ++i) { unsigned int index = cache[i]; cache_new[cache_write] = index; cache_write += (index != a) & (index != b) & (index != c); } unsigned int* cache_temp = cache; cache = cache_new, cache_new = cache_temp; cache_count = cache_write > cache_size ? cache_size : cache_write; // remove emitted triangle from adjacency data // this makes sure that we spend less time traversing these lists on subsequent iterations // live triangle counts are updated as a byproduct of these adjustments for (size_t k = 0; k < 3; ++k) { unsigned int index = indices[current_triangle * 3 + k]; unsigned int* neighbors = &adjacency.data[0] + adjacency.offsets[index]; size_t neighbors_size = adjacency.counts[index]; for (size_t i = 0; i < neighbors_size; ++i) { unsigned int tri = neighbors[i]; if (tri == current_triangle) { neighbors[i] = neighbors[neighbors_size - 1]; adjacency.counts[index]--; break; } } } unsigned int best_triangle = ~0u; float best_score = 0; // update cache positions, vertex scores and triangle scores, and find next best triangle for (size_t i = 0; i < cache_write; ++i) { unsigned int index = cache[i]; // no need to update scores if we are never going to use this vertex if (adjacency.counts[index] == 0) continue; int cache_position = i >= cache_size ? -1 : int(i); // update vertex score float score = vertexScore(table, cache_position, live_triangles[index]); float score_diff = score - vertex_scores[index]; vertex_scores[index] = score; // update scores of vertex triangles const unsigned int* neighbors_begin = &adjacency.data[0] + adjacency.offsets[index]; const unsigned int* neighbors_end = neighbors_begin + adjacency.counts[index]; for (const unsigned int* it = neighbors_begin; it != neighbors_end; ++it) { unsigned int tri = *it; assert(!emitted_flags[tri]); float tri_score = triangle_scores[tri] + score_diff; assert(tri_score > 0); best_triangle = best_score < tri_score ? tri : best_triangle; best_score = best_score < tri_score ? tri_score : best_score; triangle_scores[tri] = tri_score; } } // step through input triangles in order if we hit a dead-end current_triangle = best_triangle; if (current_triangle == ~0u) { current_triangle = getNextTriangleDeadEnd(input_cursor, &emitted_flags[0], face_count); } } assert(input_cursor == face_count); assert(output_triangle == face_count); } void meshopt_optimizeVertexCache(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count) { meshopt_optimizeVertexCacheTable(destination, indices, index_count, vertex_count, &meshopt::kVertexScoreTable); } void meshopt_optimizeVertexCacheStrip(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count) { meshopt_optimizeVertexCacheTable(destination, indices, index_count, vertex_count, &meshopt::kVertexScoreTableStrip); } void meshopt_optimizeVertexCacheFifo(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size) { using namespace meshopt; assert(index_count % 3 == 0); assert(cache_size >= 3); meshopt_Allocator allocator; // guard for empty meshes if (index_count == 0 || vertex_count == 0) return; // support in-place optimization if (destination == indices) { unsigned int* indices_copy = allocator.allocate<unsigned int>(index_count); memcpy(indices_copy, indices, index_count * sizeof(unsigned int)); indices = indices_copy; } size_t face_count = index_count / 3; // build adjacency information TriangleAdjacency adjacency = {}; buildTriangleAdjacency(adjacency, indices, index_count, vertex_count, allocator); // live triangle counts unsigned int* live_triangles = allocator.allocate<unsigned int>(vertex_count); memcpy(live_triangles, adjacency.counts, vertex_count * sizeof(unsigned int)); // cache time stamps unsigned int* cache_timestamps = allocator.allocate<unsigned int>(vertex_count); memset(cache_timestamps, 0, vertex_count * sizeof(unsigned int)); // dead-end stack unsigned int* dead_end = allocator.allocate<unsigned int>(index_count); unsigned int dead_end_top = 0; // emitted flags unsigned char* emitted_flags = allocator.allocate<unsigned char>(face_count); memset(emitted_flags, 0, face_count); unsigned int current_vertex = 0; unsigned int timestamp = cache_size + 1; unsigned int input_cursor = 1; // vertex to restart from in case of dead-end unsigned int output_triangle = 0; while (current_vertex != ~0u) { const unsigned int* next_candidates_begin = &dead_end[0] + dead_end_top; // emit all vertex neighbors const unsigned int* neighbors_begin = &adjacency.data[0] + adjacency.offsets[current_vertex]; const unsigned int* neighbors_end = neighbors_begin + adjacency.counts[current_vertex]; for (const unsigned int* it = neighbors_begin; it != neighbors_end; ++it) { unsigned int triangle = *it; if (!emitted_flags[triangle]) { unsigned int a = indices[triangle * 3 + 0], b = indices[triangle * 3 + 1], c = indices[triangle * 3 + 2]; // output indices destination[output_triangle * 3 + 0] = a; destination[output_triangle * 3 + 1] = b; destination[output_triangle * 3 + 2] = c; output_triangle++; // update dead-end stack dead_end[dead_end_top + 0] = a; dead_end[dead_end_top + 1] = b; dead_end[dead_end_top + 2] = c; dead_end_top += 3; // update live triangle counts live_triangles[a]--; live_triangles[b]--; live_triangles[c]--; // update cache info // if vertex is not in cache, put it in cache if (timestamp - cache_timestamps[a] > cache_size) cache_timestamps[a] = timestamp++; if (timestamp - cache_timestamps[b] > cache_size) cache_timestamps[b] = timestamp++; if (timestamp - cache_timestamps[c] > cache_size) cache_timestamps[c] = timestamp++; // update emitted flags emitted_flags[triangle] = true; } } // next candidates are the ones we pushed to dead-end stack just now const unsigned int* next_candidates_end = &dead_end[0] + dead_end_top; // get next vertex current_vertex = getNextVertexNeighbor(next_candidates_begin, next_candidates_end, &live_triangles[0], &cache_timestamps[0], timestamp, cache_size); if (current_vertex == ~0u) { current_vertex = getNextVertexDeadEnd(&dead_end[0], dead_end_top, input_cursor, &live_triangles[0], vertex_count); } } assert(output_triangle == face_count); }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/vertexcodec.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> // The block below auto-detects SIMD ISA that can be used on the target platform #ifndef MESHOPTIMIZER_NO_SIMD // The SIMD implementation requires SSSE3, which can be enabled unconditionally through compiler settings #if defined(__AVX__) || defined(__SSSE3__) #define SIMD_SSE #endif // An experimental implementation using AVX512 instructions; it's only enabled when AVX512 is enabled through compiler settings #if defined(__AVX512VBMI2__) && defined(__AVX512VBMI__) && defined(__AVX512VL__) && defined(__POPCNT__) #undef SIMD_SSE #define SIMD_AVX #endif // MSVC supports compiling SSSE3 code regardless of compile options; we use a cpuid-based scalar fallback #if !defined(SIMD_SSE) && !defined(SIMD_AVX) && defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_X64)) #define SIMD_SSE #define SIMD_FALLBACK #endif // GCC 4.9+ and clang 3.8+ support targeting SIMD ISA from individual functions; we use a cpuid-based scalar fallback #if !defined(SIMD_SSE) && !defined(SIMD_AVX) && ((defined(__clang__) && __clang_major__ * 100 + __clang_minor__ >= 308) || (defined(__GNUC__) && __GNUC__ * 100 + __GNUC_MINOR__ >= 409)) && (defined(__i386__) || defined(__x86_64__)) #define SIMD_SSE #define SIMD_FALLBACK #define SIMD_TARGET __attribute__((target("ssse3"))) #endif // GCC/clang define these when NEON support is available #if defined(__ARM_NEON__) || defined(__ARM_NEON) #define SIMD_NEON #endif // On MSVC, we assume that ARM builds always target NEON-capable devices #if !defined(SIMD_NEON) && defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) #define SIMD_NEON #endif // When targeting Wasm SIMD we can't use runtime cpuid checks so we unconditionally enable SIMD #if defined(__wasm_simd128__) #define SIMD_WASM // Prevent compiling other variant when wasm simd compilation is active #undef SIMD_NEON #undef SIMD_SSE #undef SIMD_AVX #endif #ifndef SIMD_TARGET #define SIMD_TARGET #endif // When targeting AArch64/x64, optimize for latency to allow decoding of individual 16-byte groups to overlap // We don't do this for 32-bit systems because we need 64-bit math for this and this will hurt in-order CPUs #if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) #define SIMD_LATENCYOPT #endif // In switch dispatch, marking default case as unreachable allows to remove redundant bounds checks #if defined(__GNUC__) #define SIMD_UNREACHABLE() __builtin_unreachable() #elif defined(_MSC_VER) #define SIMD_UNREACHABLE() __assume(false) #else #define SIMD_UNREACHABLE() assert(!"Unreachable") #endif #endif // !MESHOPTIMIZER_NO_SIMD #ifdef SIMD_SSE #include <tmmintrin.h> #endif #if defined(SIMD_SSE) && defined(SIMD_FALLBACK) #ifdef _MSC_VER #include <intrin.h> // __cpuid #else #include <cpuid.h> // __cpuid #endif #endif #ifdef SIMD_AVX #include <immintrin.h> #endif #ifdef SIMD_NEON #if defined(_MSC_VER) && defined(_M_ARM64) #include <arm64_neon.h> #else #include <arm_neon.h> #endif #endif #ifdef SIMD_WASM #include <wasm_simd128.h> #endif #ifndef TRACE #define TRACE 0 #endif #if TRACE #include <stdio.h> #endif #ifdef SIMD_WASM #define wasmx_splat_v32x4(v, i) wasm_i32x4_shuffle(v, v, i, i, i, i) #define wasmx_unpacklo_v8x16(a, b) wasm_i8x16_shuffle(a, b, 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23) #define wasmx_unpackhi_v8x16(a, b) wasm_i8x16_shuffle(a, b, 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31) #define wasmx_unpacklo_v16x8(a, b) wasm_i16x8_shuffle(a, b, 0, 8, 1, 9, 2, 10, 3, 11) #define wasmx_unpackhi_v16x8(a, b) wasm_i16x8_shuffle(a, b, 4, 12, 5, 13, 6, 14, 7, 15) #define wasmx_unpacklo_v64x2(a, b) wasm_i64x2_shuffle(a, b, 0, 2) #define wasmx_unpackhi_v64x2(a, b) wasm_i64x2_shuffle(a, b, 1, 3) #endif namespace meshopt { const unsigned char kVertexHeader = 0xa0; static int gEncodeVertexVersion = 1; const int kDecodeVertexVersion = 1; const size_t kVertexBlockSizeBytes = 8192; const size_t kVertexBlockMaxSize = 256; const size_t kByteGroupSize = 16; const size_t kByteGroupDecodeLimit = 24; const size_t kTailMinSizeV0 = 32; const size_t kTailMinSizeV1 = 24; static const int kBitsV0[4] = {0, 2, 4, 8}; static const int kBitsV1[5] = {0, 1, 2, 4, 8}; const int kEncodeDefaultLevel = 2; static size_t getVertexBlockSize(size_t vertex_size) { // make sure the entire block fits into the scratch buffer and is aligned to byte group size // note: the block size is implicitly part of the format, so we can't change it without breaking compatibility size_t result = (kVertexBlockSizeBytes / vertex_size) & ~(kByteGroupSize - 1); return (result < kVertexBlockMaxSize) ? result : kVertexBlockMaxSize; } inline unsigned int rotate(unsigned int v, int r) { return (v << r) | (v >> ((32 - r) & 31)); } template <typename T> inline T zigzag(T v) { return (0 - (v >> (sizeof(T) * 8 - 1))) ^ (v << 1); } template <typename T> inline T unzigzag(T v) { return (0 - (v & 1)) ^ (v >> 1); } #if TRACE struct Stats { size_t size; size_t header; // bytes for header size_t bitg[9]; // bytes for bit groups size_t bitc[8]; // bit consistency: how many bits are shared between all bytes in a group size_t ctrl[4]; // number of control groups }; static Stats* bytestats = NULL; static Stats vertexstats[256]; #endif static bool encodeBytesGroupZero(const unsigned char* buffer) { assert(kByteGroupSize == sizeof(unsigned long long) * 2); unsigned long long v[2]; memcpy(v, buffer, sizeof(v)); return (v[0] | v[1]) == 0; } static size_t encodeBytesGroupMeasure(const unsigned char* buffer, int bits) { assert(bits >= 0 && bits <= 8); if (bits == 0) return encodeBytesGroupZero(buffer) ? 0 : size_t(-1); if (bits == 8) return kByteGroupSize; size_t result = kByteGroupSize * bits / 8; unsigned char sentinel = (1 << bits) - 1; for (size_t i = 0; i < kByteGroupSize; ++i) result += buffer[i] >= sentinel; return result; } static unsigned char* encodeBytesGroup(unsigned char* data, const unsigned char* buffer, int bits) { assert(bits >= 0 && bits <= 8); assert(kByteGroupSize % 8 == 0); if (bits == 0) return data; if (bits == 8) { memcpy(data, buffer, kByteGroupSize); return data + kByteGroupSize; } size_t byte_size = 8 / bits; assert(kByteGroupSize % byte_size == 0); // fixed portion: bits bits for each value // variable portion: full byte for each out-of-range value (using 1...1 as sentinel) unsigned char sentinel = (1 << bits) - 1; for (size_t i = 0; i < kByteGroupSize; i += byte_size) { unsigned char byte = 0; for (size_t k = 0; k < byte_size; ++k) { unsigned char enc = (buffer[i + k] >= sentinel) ? sentinel : buffer[i + k]; byte <<= bits; byte |= enc; } // encode 1-bit groups in reverse bit order // this makes them faster to decode alongside other groups if (bits == 1) byte = (unsigned char)(((byte * 0x80200802ull) & 0x0884422110ull) * 0x0101010101ull >> 32); *data++ = byte; } for (size_t i = 0; i < kByteGroupSize; ++i) { unsigned char v = buffer[i]; // branchless append of out-of-range values *data = v; data += v >= sentinel; } return data; } static unsigned char* encodeBytes(unsigned char* data, unsigned char* data_end, const unsigned char* buffer, size_t buffer_size, const int bits[4]) { assert(buffer_size % kByteGroupSize == 0); unsigned char* header = data; // round number of groups to 4 to get number of header bytes size_t header_size = (buffer_size / kByteGroupSize + 3) / 4; if (size_t(data_end - data) < header_size) return NULL; data += header_size; memset(header, 0, header_size); int last_bits = -1; for (size_t i = 0; i < buffer_size; i += kByteGroupSize) { if (size_t(data_end - data) < kByteGroupDecodeLimit) return NULL; int best_bitk = 3; size_t best_size = encodeBytesGroupMeasure(buffer + i, bits[best_bitk]); for (int bitk = 0; bitk < 3; ++bitk) { size_t size = encodeBytesGroupMeasure(buffer + i, bits[bitk]); // favor consistent bit selection across groups, but never replace literals if (size < best_size || (size == best_size && bits[bitk] == last_bits && bits[best_bitk] != 8)) { best_bitk = bitk; best_size = size; } } size_t header_offset = i / kByteGroupSize; header[header_offset / 4] |= best_bitk << ((header_offset % 4) * 2); int best_bits = bits[best_bitk]; unsigned char* next = encodeBytesGroup(data, buffer + i, best_bits); assert(data + best_size == next); data = next; last_bits = best_bits; #if TRACE bytestats->bitg[best_bits] += best_size; #endif } #if TRACE bytestats->header += header_size; #endif return data; } template <typename T, bool Xor> static void encodeDeltas1(unsigned char* buffer, const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, const unsigned char last_vertex[256], size_t k, int rot) { size_t k0 = k & ~(sizeof(T) - 1); int ks = (k & (sizeof(T) - 1)) * 8; T p = last_vertex[k0]; for (size_t j = 1; j < sizeof(T); ++j) p |= T(last_vertex[k0 + j]) << (j * 8); const unsigned char* vertex = vertex_data + k0; for (size_t i = 0; i < vertex_count; ++i) { T v = vertex[0]; for (size_t j = 1; j < sizeof(T); ++j) v |= vertex[j] << (j * 8); T d = Xor ? T(rotate(v ^ p, rot)) : zigzag(T(v - p)); buffer[i] = (unsigned char)(d >> ks); p = v; vertex += vertex_size; } } static void encodeDeltas(unsigned char* buffer, const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, const unsigned char last_vertex[256], size_t k, int channel) { switch (channel & 3) { case 0: return encodeDeltas1<unsigned char, false>(buffer, vertex_data, vertex_count, vertex_size, last_vertex, k, 0); case 1: return encodeDeltas1<unsigned short, false>(buffer, vertex_data, vertex_count, vertex_size, last_vertex, k, 0); case 2: return encodeDeltas1<unsigned int, true>(buffer, vertex_data, vertex_count, vertex_size, last_vertex, k, channel >> 4); default: assert(!"Unsupported channel encoding"); // unreachable } } static int estimateBits(unsigned char v) { return v <= 15 ? (v <= 3 ? (v == 0 ? 0 : 2) : 4) : 8; } static int estimateRotate(const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, size_t k, size_t group_size) { size_t sizes[8] = {}; const unsigned char* vertex = vertex_data + k; unsigned int last = vertex[0] | (vertex[1] << 8) | (vertex[2] << 16) | (vertex[3] << 24); for (size_t i = 0; i < vertex_count; i += group_size) { unsigned int bitg = 0; // calculate bit consistency mask for the group for (size_t j = 0; j < group_size && i + j < vertex_count; ++j) { unsigned int v = vertex[0] | (vertex[1] << 8) | (vertex[2] << 16) | (vertex[3] << 24); unsigned int d = v ^ last; bitg |= d; last = v; vertex += vertex_size; } #if TRACE for (int j = 0; j < 32; ++j) vertexstats[k + (j / 8)].bitc[j % 8] += (i + group_size < vertex_count ? group_size : vertex_count - i) * (1 - ((bitg >> j) & 1)); #endif for (int j = 0; j < 8; ++j) { unsigned int bitr = rotate(bitg, j); sizes[j] += estimateBits((unsigned char)(bitr >> 0)) + estimateBits((unsigned char)(bitr >> 8)); sizes[j] += estimateBits((unsigned char)(bitr >> 16)) + estimateBits((unsigned char)(bitr >> 24)); } } int best_rot = 0; for (int rot = 1; rot < 8; ++rot) best_rot = (sizes[rot] < sizes[best_rot]) ? rot : best_rot; return best_rot; } static int estimateChannel(const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, size_t k, size_t vertex_block_size, size_t block_skip, int max_channel, int xor_rot) { unsigned char block[kVertexBlockMaxSize]; assert(vertex_block_size <= kVertexBlockMaxSize); unsigned char last_vertex[256] = {}; size_t sizes[3] = {}; assert(max_channel <= 3); for (size_t i = 0; i < vertex_count; i += vertex_block_size * block_skip) { size_t block_size = i + vertex_block_size < vertex_count ? vertex_block_size : vertex_count - i; size_t block_size_aligned = (block_size + kByteGroupSize - 1) & ~(kByteGroupSize - 1); memcpy(last_vertex, vertex_data + (i == 0 ? 0 : i - 1) * vertex_size, vertex_size); // we sometimes encode elements we didn't fill when rounding to kByteGroupSize if (block_size < block_size_aligned) memset(block + block_size, 0, block_size_aligned - block_size); for (int channel = 0; channel < max_channel; ++channel) for (size_t j = 0; j < 4; ++j) { encodeDeltas(block, vertex_data + i * vertex_size, block_size, vertex_size, last_vertex, k + j, channel | (xor_rot << 4)); for (size_t ig = 0; ig < block_size; ig += kByteGroupSize) { // to maximize encoding performance we only evaluate 1/2/4/8 bit groups size_t size1 = encodeBytesGroupMeasure(block + ig, 1); size_t size2 = encodeBytesGroupMeasure(block + ig, 2); size_t size4 = encodeBytesGroupMeasure(block + ig, 4); size_t size8 = encodeBytesGroupMeasure(block + ig, 8); size_t best_size = size1 < size2 ? size1 : size2; best_size = best_size < size4 ? best_size : size4; best_size = best_size < size8 ? best_size : size8; sizes[channel] += best_size; } } } int best_channel = 0; for (int channel = 1; channel < max_channel; ++channel) best_channel = (sizes[channel] < sizes[best_channel]) ? channel : best_channel; return best_channel == 2 ? best_channel | (xor_rot << 4) : best_channel; } static bool estimateControlZero(const unsigned char* buffer, size_t vertex_count_aligned) { for (size_t i = 0; i < vertex_count_aligned; i += kByteGroupSize) if (!encodeBytesGroupZero(buffer + i)) return false; return true; } static int estimateControl(const unsigned char* buffer, size_t vertex_count, size_t vertex_count_aligned, int level) { if (estimateControlZero(buffer, vertex_count_aligned)) return 2; // zero encoding if (level == 0) return 1; // 1248 encoding in level 0 for encoding speed // round number of groups to 4 to get number of header bytes size_t header_size = (vertex_count_aligned / kByteGroupSize + 3) / 4; size_t est_bytes0 = header_size, est_bytes1 = header_size; for (size_t i = 0; i < vertex_count_aligned; i += kByteGroupSize) { // assumes kBitsV1[] = {0, 1, 2, 4, 8} for performance size_t size0 = encodeBytesGroupMeasure(buffer + i, 0); size_t size1 = encodeBytesGroupMeasure(buffer + i, 1); size_t size2 = encodeBytesGroupMeasure(buffer + i, 2); size_t size4 = encodeBytesGroupMeasure(buffer + i, 4); size_t size8 = encodeBytesGroupMeasure(buffer + i, 8); // both control modes have access to 1/2/4 bit encoding size_t size12 = size1 < size2 ? size1 : size2; size_t size124 = size12 < size4 ? size12 : size4; // each control mode has access to 0/8 bit encoding respectively est_bytes0 += size124 < size0 ? size124 : size0; est_bytes1 += size124 < size8 ? size124 : size8; } // pick shortest control entry but prefer literal encoding if (est_bytes0 < vertex_count || est_bytes1 < vertex_count) return est_bytes0 < est_bytes1 ? 0 : 1; else return 3; // literal encoding } static unsigned char* encodeVertexBlock(unsigned char* data, unsigned char* data_end, const unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, unsigned char last_vertex[256], const unsigned char* channels, int version, int level) { assert(vertex_count > 0 && vertex_count <= kVertexBlockMaxSize); assert(vertex_size % 4 == 0); unsigned char buffer[kVertexBlockMaxSize]; assert(sizeof(buffer) % kByteGroupSize == 0); size_t vertex_count_aligned = (vertex_count + kByteGroupSize - 1) & ~(kByteGroupSize - 1); // we sometimes encode elements we didn't fill when rounding to kByteGroupSize memset(buffer, 0, sizeof(buffer)); size_t control_size = version == 0 ? 0 : vertex_size / 4; if (size_t(data_end - data) < control_size) return NULL; unsigned char* control = data; data += control_size; memset(control, 0, control_size); for (size_t k = 0; k < vertex_size; ++k) { encodeDeltas(buffer, vertex_data, vertex_count, vertex_size, last_vertex, k, version == 0 ? 0 : channels[k / 4]); #if TRACE const unsigned char* olddata = data; bytestats = &vertexstats[k]; #endif int ctrl = 0; if (version != 0) { ctrl = estimateControl(buffer, vertex_count, vertex_count_aligned, level); assert(unsigned(ctrl) < 4); control[k / 4] |= ctrl << ((k % 4) * 2); #if TRACE vertexstats[k].ctrl[ctrl]++; #endif } if (ctrl == 3) { // literal encoding if (size_t(data_end - data) < vertex_count) return NULL; memcpy(data, buffer, vertex_count); data += vertex_count; } else if (ctrl != 2) // non-zero encoding { data = encodeBytes(data, data_end, buffer, vertex_count_aligned, version == 0 ? kBitsV0 : kBitsV1 + ctrl); if (!data) return NULL; } #if TRACE bytestats = NULL; vertexstats[k].size += data - olddata; #endif } memcpy(last_vertex, &vertex_data[vertex_size * (vertex_count - 1)], vertex_size); return data; } #if defined(SIMD_FALLBACK) || (!defined(SIMD_SSE) && !defined(SIMD_NEON) && !defined(SIMD_AVX) && !defined(SIMD_WASM)) static const unsigned char* decodeBytesGroup(const unsigned char* data, unsigned char* buffer, int bits) { #define READ() byte = *data++ #define NEXT(bits) enc = byte >> (8 - bits), byte <<= bits, encv = *data_var, *buffer++ = (enc == (1 << bits) - 1) ? encv : enc, data_var += (enc == (1 << bits) - 1) unsigned char byte, enc, encv; const unsigned char* data_var; switch (bits) { case 0: memset(buffer, 0, kByteGroupSize); return data; case 1: data_var = data + 2; // 2 groups with 8 1-bit values in each byte (reversed from the order in other groups) READ(); byte = (unsigned char)(((byte * 0x80200802ull) & 0x0884422110ull) * 0x0101010101ull >> 32); NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1); READ(); byte = (unsigned char)(((byte * 0x80200802ull) & 0x0884422110ull) * 0x0101010101ull >> 32); NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1), NEXT(1); return data_var; case 2: data_var = data + 4; // 4 groups with 4 2-bit values in each byte READ(), NEXT(2), NEXT(2), NEXT(2), NEXT(2); READ(), NEXT(2), NEXT(2), NEXT(2), NEXT(2); READ(), NEXT(2), NEXT(2), NEXT(2), NEXT(2); READ(), NEXT(2), NEXT(2), NEXT(2), NEXT(2); return data_var; case 4: data_var = data + 8; // 8 groups with 2 4-bit values in each byte READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); READ(), NEXT(4), NEXT(4); return data_var; case 8: memcpy(buffer, data, kByteGroupSize); return data + kByteGroupSize; default: assert(!"Unexpected bit length"); // unreachable return data; } #undef READ #undef NEXT } static const unsigned char* decodeBytes(const unsigned char* data, const unsigned char* data_end, unsigned char* buffer, size_t buffer_size, const int* bits) { assert(buffer_size % kByteGroupSize == 0); // round number of groups to 4 to get number of header bytes size_t header_size = (buffer_size / kByteGroupSize + 3) / 4; if (size_t(data_end - data) < header_size) return NULL; const unsigned char* header = data; data += header_size; for (size_t i = 0; i < buffer_size; i += kByteGroupSize) { if (size_t(data_end - data) < kByteGroupDecodeLimit) return NULL; size_t header_offset = i / kByteGroupSize; int bitsk = (header[header_offset / 4] >> ((header_offset % 4) * 2)) & 3; data = decodeBytesGroup(data, buffer + i, bits[bitsk]); } return data; } template <typename T, bool Xor> static void decodeDeltas1(const unsigned char* buffer, unsigned char* transposed, size_t vertex_count, size_t vertex_size, const unsigned char* last_vertex, int rot) { for (size_t k = 0; k < 4; k += sizeof(T)) { size_t vertex_offset = k; T p = last_vertex[0]; for (size_t j = 1; j < sizeof(T); ++j) p |= last_vertex[j] << (8 * j); for (size_t i = 0; i < vertex_count; ++i) { T v = buffer[i]; for (size_t j = 1; j < sizeof(T); ++j) v |= buffer[i + vertex_count * j] << (8 * j); v = Xor ? T(rotate(v, rot)) ^ p : unzigzag(v) + p; for (size_t j = 0; j < sizeof(T); ++j) transposed[vertex_offset + j] = (unsigned char)(v >> (j * 8)); p = v; vertex_offset += vertex_size; } buffer += vertex_count * sizeof(T); last_vertex += sizeof(T); } } static const unsigned char* decodeVertexBlock(const unsigned char* data, const unsigned char* data_end, unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, unsigned char last_vertex[256], const unsigned char* channels, int version) { assert(vertex_count > 0 && vertex_count <= kVertexBlockMaxSize); unsigned char buffer[kVertexBlockMaxSize * 4]; unsigned char transposed[kVertexBlockSizeBytes]; size_t vertex_count_aligned = (vertex_count + kByteGroupSize - 1) & ~(kByteGroupSize - 1); assert(vertex_count <= vertex_count_aligned); size_t control_size = version == 0 ? 0 : vertex_size / 4; if (size_t(data_end - data) < control_size) return NULL; const unsigned char* control = data; data += control_size; for (size_t k = 0; k < vertex_size; k += 4) { unsigned char ctrl_byte = version == 0 ? 0 : control[k / 4]; for (size_t j = 0; j < 4; ++j) { int ctrl = (ctrl_byte >> (j * 2)) & 3; if (ctrl == 3) { // literal encoding if (size_t(data_end - data) < vertex_count) return NULL; memcpy(buffer + j * vertex_count, data, vertex_count); data += vertex_count; } else if (ctrl == 2) { // zero encoding memset(buffer + j * vertex_count, 0, vertex_count); } else { data = decodeBytes(data, data_end, buffer + j * vertex_count, vertex_count_aligned, version == 0 ? kBitsV0 : kBitsV1 + ctrl); if (!data) return NULL; } } int channel = version == 0 ? 0 : channels[k / 4]; switch (channel & 3) { case 0: decodeDeltas1<unsigned char, false>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, 0); break; case 1: decodeDeltas1<unsigned short, false>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, 0); break; case 2: decodeDeltas1<unsigned int, true>(buffer, transposed + k, vertex_count, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31); break; default: return NULL; // invalid channel type } } memcpy(vertex_data, transposed, vertex_count * vertex_size); memcpy(last_vertex, &transposed[vertex_size * (vertex_count - 1)], vertex_size); return data; } #endif #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) static unsigned char kDecodeBytesGroupShuffle[256][8]; static unsigned char kDecodeBytesGroupCount[256]; #ifdef __wasm__ __attribute__((cold)) // this saves 500 bytes in the output binary - we don't need to vectorize this loop! #endif static bool decodeBytesGroupBuildTables() { for (int mask = 0; mask < 256; ++mask) { unsigned char shuffle[8]; unsigned char count = 0; for (int i = 0; i < 8; ++i) { int maski = (mask >> i) & 1; shuffle[i] = maski ? count : 0x80; count += (unsigned char)(maski); } memcpy(kDecodeBytesGroupShuffle[mask], shuffle, 8); kDecodeBytesGroupCount[mask] = count; } return true; } static bool gDecodeBytesGroupInitialized = decodeBytesGroupBuildTables(); #endif #ifdef SIMD_SSE SIMD_TARGET inline __m128i decodeShuffleMask(unsigned char mask0, unsigned char mask1) { __m128i sm0 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask0])); __m128i sm1 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&kDecodeBytesGroupShuffle[mask1])); __m128i sm1off = _mm_set1_epi8(kDecodeBytesGroupCount[mask0]); __m128i sm1r = _mm_add_epi8(sm1, sm1off); return _mm_unpacklo_epi64(sm0, sm1r); } #ifdef __GNUC__ typedef int __attribute__((aligned(1))) unaligned_int; #else typedef int unaligned_int; #endif SIMD_TARGET inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits) { switch (hbits) { case 0: case 4: { __m128i result = _mm_setzero_si128(); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return data; } case 1: case 6: { #ifdef SIMD_LATENCYOPT unsigned int data32; memcpy(&data32, data, 4); data32 &= data32 >> 1; // arrange bits such that low bits of nibbles of data64 contain all 2-bit elements of data32 unsigned long long data64 = ((unsigned long long)data32 << 30) | (data32 & 0x3fffffff); // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3 int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60); #endif __m128i sel2 = _mm_cvtsi32_si128(*reinterpret_cast<const unaligned_int*>(data)); __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 4)); __m128i sel22 = _mm_unpacklo_epi8(_mm_srli_epi16(sel2, 4), sel2); __m128i sel2222 = _mm_unpacklo_epi8(_mm_srli_epi16(sel22, 2), sel22); __m128i sel = _mm_and_si128(sel2222, _mm_set1_epi8(3)); __m128i mask = _mm_cmpeq_epi8(sel, _mm_set1_epi8(3)); int mask16 = _mm_movemask_epi8(mask); unsigned char mask0 = (unsigned char)(mask16 & 255); unsigned char mask1 = (unsigned char)(mask16 >> 8); __m128i shuf = decodeShuffleMask(mask0, mask1); __m128i result = _mm_or_si128(_mm_shuffle_epi8(rest, shuf), _mm_andnot_si128(mask, sel)); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); #ifdef SIMD_LATENCYOPT return data + 4 + datacnt; #else return data + 4 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; #endif } case 2: case 7: { #ifdef SIMD_LATENCYOPT unsigned long long data64; memcpy(&data64, data, 8); data64 &= data64 >> 1; data64 &= data64 >> 2; // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3 int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60); #endif __m128i sel4 = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data)); __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 8)); __m128i sel44 = _mm_unpacklo_epi8(_mm_srli_epi16(sel4, 4), sel4); __m128i sel = _mm_and_si128(sel44, _mm_set1_epi8(15)); __m128i mask = _mm_cmpeq_epi8(sel, _mm_set1_epi8(15)); int mask16 = _mm_movemask_epi8(mask); unsigned char mask0 = (unsigned char)(mask16 & 255); unsigned char mask1 = (unsigned char)(mask16 >> 8); __m128i shuf = decodeShuffleMask(mask0, mask1); __m128i result = _mm_or_si128(_mm_shuffle_epi8(rest, shuf), _mm_andnot_si128(mask, sel)); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); #ifdef SIMD_LATENCYOPT return data + 8 + datacnt; #else return data + 8 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; #endif } case 3: case 8: { __m128i result = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data)); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return data + 16; } case 5: { __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data + 2)); unsigned char mask0 = data[0]; unsigned char mask1 = data[1]; __m128i shuf = decodeShuffleMask(mask0, mask1); __m128i result = _mm_shuffle_epi8(rest, shuf); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return data + 2 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; } default: SIMD_UNREACHABLE(); // unreachable } } #endif #ifdef SIMD_AVX static const __m128i kDecodeBytesGroupConfig[8][2] = { {_mm_setzero_si128(), _mm_setzero_si128()}, {_mm_set1_epi8(3), _mm_setr_epi8(6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24)}, {_mm_set1_epi8(15), _mm_setr_epi8(4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56)}, {_mm_setzero_si128(), _mm_setzero_si128()}, {_mm_setzero_si128(), _mm_setzero_si128()}, {_mm_set1_epi8(1), _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)}, {_mm_set1_epi8(3), _mm_setr_epi8(6, 4, 2, 0, 14, 12, 10, 8, 22, 20, 18, 16, 30, 28, 26, 24)}, {_mm_set1_epi8(15), _mm_setr_epi8(4, 0, 12, 8, 20, 16, 28, 24, 36, 32, 44, 40, 52, 48, 60, 56)}, }; SIMD_TARGET inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits) { switch (hbits) { case 0: case 4: { __m128i result = _mm_setzero_si128(); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return data; } case 5: // 1-bit case 1: // 2-bit case 6: case 2: // 4-bit case 7: { const unsigned char* skip = data + (2 << (hbits < 3 ? hbits : hbits - 5)); __m128i selb = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(data)); __m128i rest = _mm_loadu_si128(reinterpret_cast<const __m128i*>(skip)); __m128i sent = kDecodeBytesGroupConfig[hbits][0]; __m128i ctrl = kDecodeBytesGroupConfig[hbits][1]; __m128i selw = _mm_shuffle_epi32(selb, 0x44); __m128i sel = _mm_and_si128(sent, _mm_multishift_epi64_epi8(ctrl, selw)); __mmask16 mask16 = _mm_cmp_epi8_mask(sel, sent, _MM_CMPINT_EQ); __m128i result = _mm_mask_expand_epi8(sel, mask16, rest); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return skip + _mm_popcnt_u32(mask16); } case 3: case 8: { __m128i result = _mm_loadu_si128(reinterpret_cast<const __m128i*>(data)); _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result); return data + 16; } default: SIMD_UNREACHABLE(); // unreachable } } #endif #ifdef SIMD_NEON SIMD_TARGET inline uint8x16_t shuffleBytes(unsigned char mask0, unsigned char mask1, uint8x8_t rest0, uint8x8_t rest1) { uint8x8_t sm0 = vld1_u8(kDecodeBytesGroupShuffle[mask0]); uint8x8_t sm1 = vld1_u8(kDecodeBytesGroupShuffle[mask1]); uint8x8_t r0 = vtbl1_u8(rest0, sm0); uint8x8_t r1 = vtbl1_u8(rest1, sm1); return vcombine_u8(r0, r1); } SIMD_TARGET inline void neonMoveMask(uint8x16_t mask, unsigned char& mask0, unsigned char& mask1) { // magic constant found using z3 SMT assuming mask has 8 groups of 0xff or 0x00 const uint64_t magic = 0x000103070f1f3f80ull; uint64x2_t mask2 = vreinterpretq_u64_u8(mask); mask0 = uint8_t((vgetq_lane_u64(mask2, 0) * magic) >> 56); mask1 = uint8_t((vgetq_lane_u64(mask2, 1) * magic) >> 56); } SIMD_TARGET inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits) { switch (hbits) { case 0: case 4: { uint8x16_t result = vdupq_n_u8(0); vst1q_u8(buffer, result); return data; } case 1: case 6: { #ifdef SIMD_LATENCYOPT unsigned int data32; memcpy(&data32, data, 4); data32 &= data32 >> 1; // arrange bits such that low bits of nibbles of data64 contain all 2-bit elements of data32 unsigned long long data64 = ((unsigned long long)data32 << 30) | (data32 & 0x3fffffff); // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3 int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60); #endif uint8x8_t sel2 = vld1_u8(data); uint8x8_t sel22 = vzip_u8(vshr_n_u8(sel2, 4), sel2).val[0]; uint8x8x2_t sel2222 = vzip_u8(vshr_n_u8(sel22, 2), sel22); uint8x16_t sel = vandq_u8(vcombine_u8(sel2222.val[0], sel2222.val[1]), vdupq_n_u8(3)); uint8x16_t mask = vceqq_u8(sel, vdupq_n_u8(3)); unsigned char mask0, mask1; neonMoveMask(mask, mask0, mask1); uint8x8_t rest0 = vld1_u8(data + 4); uint8x8_t rest1 = vld1_u8(data + 4 + kDecodeBytesGroupCount[mask0]); uint8x16_t result = vbslq_u8(mask, shuffleBytes(mask0, mask1, rest0, rest1), sel); vst1q_u8(buffer, result); #ifdef SIMD_LATENCYOPT return data + 4 + datacnt; #else return data + 4 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; #endif } case 2: case 7: { #ifdef SIMD_LATENCYOPT unsigned long long data64; memcpy(&data64, data, 8); data64 &= data64 >> 1; data64 &= data64 >> 2; // adds all 1-bit nibbles together; the sum fits in 4 bits because datacnt=16 would have used mode 3 int datacnt = int(((data64 & 0x1111111111111111ull) * 0x1111111111111111ull) >> 60); #endif uint8x8_t sel4 = vld1_u8(data); uint8x8x2_t sel44 = vzip_u8(vshr_n_u8(sel4, 4), vand_u8(sel4, vdup_n_u8(15))); uint8x16_t sel = vcombine_u8(sel44.val[0], sel44.val[1]); uint8x16_t mask = vceqq_u8(sel, vdupq_n_u8(15)); unsigned char mask0, mask1; neonMoveMask(mask, mask0, mask1); uint8x8_t rest0 = vld1_u8(data + 8); uint8x8_t rest1 = vld1_u8(data + 8 + kDecodeBytesGroupCount[mask0]); uint8x16_t result = vbslq_u8(mask, shuffleBytes(mask0, mask1, rest0, rest1), sel); vst1q_u8(buffer, result); #ifdef SIMD_LATENCYOPT return data + 8 + datacnt; #else return data + 8 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; #endif } case 3: case 8: { uint8x16_t result = vld1q_u8(data); vst1q_u8(buffer, result); return data + 16; } case 5: { unsigned char mask0 = data[0]; unsigned char mask1 = data[1]; uint8x8_t rest0 = vld1_u8(data + 2); uint8x8_t rest1 = vld1_u8(data + 2 + kDecodeBytesGroupCount[mask0]); uint8x16_t result = shuffleBytes(mask0, mask1, rest0, rest1); vst1q_u8(buffer, result); return data + 2 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; } default: SIMD_UNREACHABLE(); // unreachable } } #endif #ifdef SIMD_WASM SIMD_TARGET inline v128_t decodeShuffleMask(unsigned char mask0, unsigned char mask1) { v128_t sm0 = wasm_v128_load(&kDecodeBytesGroupShuffle[mask0]); v128_t sm1 = wasm_v128_load(&kDecodeBytesGroupShuffle[mask1]); v128_t sm1off = wasm_v128_load8_splat(&kDecodeBytesGroupCount[mask0]); v128_t sm1r = wasm_i8x16_add(sm1, sm1off); return wasmx_unpacklo_v64x2(sm0, sm1r); } SIMD_TARGET inline void wasmMoveMask(v128_t mask, unsigned char& mask0, unsigned char& mask1) { // magic constant found using z3 SMT assuming mask has 8 groups of 0xff or 0x00 const uint64_t magic = 0x000103070f1f3f80ull; mask0 = uint8_t((wasm_i64x2_extract_lane(mask, 0) * magic) >> 56); mask1 = uint8_t((wasm_i64x2_extract_lane(mask, 1) * magic) >> 56); } SIMD_TARGET inline const unsigned char* decodeBytesGroupSimd(const unsigned char* data, unsigned char* buffer, int hbits) { switch (hbits) { case 0: case 4: { v128_t result = wasm_i8x16_splat(0); wasm_v128_store(buffer, result); return data; } case 1: case 6: { v128_t sel2 = wasm_v128_load(data); v128_t rest = wasm_v128_load(data + 4); v128_t sel22 = wasmx_unpacklo_v8x16(wasm_i16x8_shr(sel2, 4), sel2); v128_t sel2222 = wasmx_unpacklo_v8x16(wasm_i16x8_shr(sel22, 2), sel22); v128_t sel = wasm_v128_and(sel2222, wasm_i8x16_splat(3)); v128_t mask = wasm_i8x16_eq(sel, wasm_i8x16_splat(3)); unsigned char mask0, mask1; wasmMoveMask(mask, mask0, mask1); v128_t shuf = decodeShuffleMask(mask0, mask1); v128_t result = wasm_v128_bitselect(wasm_i8x16_swizzle(rest, shuf), sel, mask); wasm_v128_store(buffer, result); return data + 4 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; } case 2: case 7: { v128_t sel4 = wasm_v128_load(data); v128_t rest = wasm_v128_load(data + 8); v128_t sel44 = wasmx_unpacklo_v8x16(wasm_i16x8_shr(sel4, 4), sel4); v128_t sel = wasm_v128_and(sel44, wasm_i8x16_splat(15)); v128_t mask = wasm_i8x16_eq(sel, wasm_i8x16_splat(15)); unsigned char mask0, mask1; wasmMoveMask(mask, mask0, mask1); v128_t shuf = decodeShuffleMask(mask0, mask1); v128_t result = wasm_v128_bitselect(wasm_i8x16_swizzle(rest, shuf), sel, mask); wasm_v128_store(buffer, result); return data + 8 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; } case 3: case 8: { v128_t result = wasm_v128_load(data); wasm_v128_store(buffer, result); return data + 16; } case 5: { v128_t rest = wasm_v128_load(data + 2); unsigned char mask0 = data[0]; unsigned char mask1 = data[1]; v128_t shuf = decodeShuffleMask(mask0, mask1); v128_t result = wasm_i8x16_swizzle(rest, shuf); wasm_v128_store(buffer, result); return data + 2 + kDecodeBytesGroupCount[mask0] + kDecodeBytesGroupCount[mask1]; } default: SIMD_UNREACHABLE(); // unreachable } } #endif #if defined(SIMD_SSE) || defined(SIMD_AVX) SIMD_TARGET inline void transpose8(__m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3) { __m128i t0 = _mm_unpacklo_epi8(x0, x1); __m128i t1 = _mm_unpackhi_epi8(x0, x1); __m128i t2 = _mm_unpacklo_epi8(x2, x3); __m128i t3 = _mm_unpackhi_epi8(x2, x3); x0 = _mm_unpacklo_epi16(t0, t2); x1 = _mm_unpackhi_epi16(t0, t2); x2 = _mm_unpacklo_epi16(t1, t3); x3 = _mm_unpackhi_epi16(t1, t3); } SIMD_TARGET inline __m128i unzigzag8(__m128i v) { __m128i xl = _mm_sub_epi8(_mm_setzero_si128(), _mm_and_si128(v, _mm_set1_epi8(1))); __m128i xr = _mm_and_si128(_mm_srli_epi16(v, 1), _mm_set1_epi8(127)); return _mm_xor_si128(xl, xr); } SIMD_TARGET inline __m128i unzigzag16(__m128i v) { __m128i xl = _mm_sub_epi16(_mm_setzero_si128(), _mm_and_si128(v, _mm_set1_epi16(1))); __m128i xr = _mm_srli_epi16(v, 1); return _mm_xor_si128(xl, xr); } SIMD_TARGET inline __m128i rotate32(__m128i v, int r) { return _mm_or_si128(_mm_slli_epi32(v, r), _mm_srli_epi32(v, 32 - r)); } #endif #ifdef SIMD_NEON SIMD_TARGET inline void transpose8(uint8x16_t& x0, uint8x16_t& x1, uint8x16_t& x2, uint8x16_t& x3) { uint8x16x2_t t01 = vzipq_u8(x0, x1); uint8x16x2_t t23 = vzipq_u8(x2, x3); uint16x8x2_t x01 = vzipq_u16(vreinterpretq_u16_u8(t01.val[0]), vreinterpretq_u16_u8(t23.val[0])); uint16x8x2_t x23 = vzipq_u16(vreinterpretq_u16_u8(t01.val[1]), vreinterpretq_u16_u8(t23.val[1])); x0 = vreinterpretq_u8_u16(x01.val[0]); x1 = vreinterpretq_u8_u16(x01.val[1]); x2 = vreinterpretq_u8_u16(x23.val[0]); x3 = vreinterpretq_u8_u16(x23.val[1]); } SIMD_TARGET inline uint8x16_t unzigzag8(uint8x16_t v) { uint8x16_t xl = vreinterpretq_u8_s8(vnegq_s8(vreinterpretq_s8_u8(vandq_u8(v, vdupq_n_u8(1))))); uint8x16_t xr = vshrq_n_u8(v, 1); return veorq_u8(xl, xr); } SIMD_TARGET inline uint8x16_t unzigzag16(uint8x16_t v) { uint16x8_t vv = vreinterpretq_u16_u8(v); uint8x16_t xl = vreinterpretq_u8_s16(vnegq_s16(vreinterpretq_s16_u16(vandq_u16(vv, vdupq_n_u16(1))))); uint8x16_t xr = vreinterpretq_u8_u16(vshrq_n_u16(vv, 1)); return veorq_u8(xl, xr); } SIMD_TARGET inline uint8x16_t rotate32(uint8x16_t v, int r) { uint32x4_t v32 = vreinterpretq_u32_u8(v); return vreinterpretq_u8_u32(vorrq_u32(vshlq_u32(v32, vdupq_n_s32(r)), vshlq_u32(v32, vdupq_n_s32(r - 32)))); } template <int Channel> SIMD_TARGET inline uint8x8_t rebase(uint8x8_t npi, uint8x16_t r0, uint8x16_t r1, uint8x16_t r2, uint8x16_t r3) { switch (Channel) { case 0: { uint8x16_t rsum = vaddq_u8(vaddq_u8(r0, r1), vaddq_u8(r2, r3)); uint8x8_t rsumx = vadd_u8(vget_low_u8(rsum), vget_high_u8(rsum)); return vadd_u8(vadd_u8(npi, rsumx), vext_u8(rsumx, rsumx, 4)); } case 1: { uint16x8_t rsum = vaddq_u16(vaddq_u16(vreinterpretq_u16_u8(r0), vreinterpretq_u16_u8(r1)), vaddq_u16(vreinterpretq_u16_u8(r2), vreinterpretq_u16_u8(r3))); uint16x4_t rsumx = vadd_u16(vget_low_u16(rsum), vget_high_u16(rsum)); return vreinterpret_u8_u16(vadd_u16(vadd_u16(vreinterpret_u16_u8(npi), rsumx), vext_u16(rsumx, rsumx, 2))); } case 2: { uint8x16_t rsum = veorq_u8(veorq_u8(r0, r1), veorq_u8(r2, r3)); uint8x8_t rsumx = veor_u8(vget_low_u8(rsum), vget_high_u8(rsum)); return veor_u8(veor_u8(npi, rsumx), vext_u8(rsumx, rsumx, 4)); } default: return npi; } } #endif #ifdef SIMD_WASM SIMD_TARGET inline void transpose8(v128_t& x0, v128_t& x1, v128_t& x2, v128_t& x3) { v128_t t0 = wasmx_unpacklo_v8x16(x0, x1); v128_t t1 = wasmx_unpackhi_v8x16(x0, x1); v128_t t2 = wasmx_unpacklo_v8x16(x2, x3); v128_t t3 = wasmx_unpackhi_v8x16(x2, x3); x0 = wasmx_unpacklo_v16x8(t0, t2); x1 = wasmx_unpackhi_v16x8(t0, t2); x2 = wasmx_unpacklo_v16x8(t1, t3); x3 = wasmx_unpackhi_v16x8(t1, t3); } SIMD_TARGET inline v128_t unzigzag8(v128_t v) { v128_t xl = wasm_i8x16_neg(wasm_v128_and(v, wasm_i8x16_splat(1))); v128_t xr = wasm_u8x16_shr(v, 1); return wasm_v128_xor(xl, xr); } SIMD_TARGET inline v128_t unzigzag16(v128_t v) { v128_t xl = wasm_i16x8_neg(wasm_v128_and(v, wasm_i16x8_splat(1))); v128_t xr = wasm_u16x8_shr(v, 1); return wasm_v128_xor(xl, xr); } SIMD_TARGET inline v128_t rotate32(v128_t v, int r) { return wasm_v128_or(wasm_i32x4_shl(v, r), wasm_i32x4_shr(v, 32 - r)); } #endif #if defined(SIMD_SSE) || defined(SIMD_AVX) || defined(SIMD_NEON) || defined(SIMD_WASM) SIMD_TARGET static const unsigned char* decodeBytesSimd(const unsigned char* data, const unsigned char* data_end, unsigned char* buffer, size_t buffer_size, int hshift) { assert(buffer_size % kByteGroupSize == 0); assert(kByteGroupSize == 16); // round number of groups to 4 to get number of header bytes size_t header_size = (buffer_size / kByteGroupSize + 3) / 4; if (size_t(data_end - data) < header_size) return NULL; const unsigned char* header = data; data += header_size; size_t i = 0; // fast-path: process 4 groups at a time, do a shared bounds check for (; i + kByteGroupSize * 4 <= buffer_size && size_t(data_end - data) >= kByteGroupDecodeLimit * 4; i += kByteGroupSize * 4) { size_t header_offset = i / kByteGroupSize; unsigned char header_byte = header[header_offset / 4]; data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 0, hshift + ((header_byte >> 0) & 3)); data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 1, hshift + ((header_byte >> 2) & 3)); data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 2, hshift + ((header_byte >> 4) & 3)); data = decodeBytesGroupSimd(data, buffer + i + kByteGroupSize * 3, hshift + ((header_byte >> 6) & 3)); } // slow-path: process remaining groups for (; i < buffer_size; i += kByteGroupSize) { if (size_t(data_end - data) < kByteGroupDecodeLimit) return NULL; size_t header_offset = i / kByteGroupSize; unsigned char header_byte = header[header_offset / 4]; data = decodeBytesGroupSimd(data, buffer + i, hshift + ((header_byte >> ((header_offset % 4) * 2)) & 3)); } return data; } template <int Channel> SIMD_TARGET static void decodeDeltas4Simd(const unsigned char* buffer, unsigned char* transposed, size_t vertex_count_aligned, size_t vertex_size, unsigned char last_vertex[4], int rot) { #if defined(SIMD_SSE) || defined(SIMD_AVX) #define TEMP __m128i #define PREP() __m128i pi = _mm_cvtsi32_si128(*reinterpret_cast<const int*>(last_vertex)) #define LOAD(i) __m128i r##i = _mm_loadu_si128(reinterpret_cast<const __m128i*>(buffer + j + i * vertex_count_aligned)) #define GRP4(i) t0 = r##i, t1 = _mm_shuffle_epi32(r##i, 1), t2 = _mm_shuffle_epi32(r##i, 2), t3 = _mm_shuffle_epi32(r##i, 3) #define FIXD(i) t##i = pi = Channel == 0 ? _mm_add_epi8(pi, t##i) : (Channel == 1 ? _mm_add_epi16(pi, t##i) : _mm_xor_si128(pi, t##i)) #define SAVE(i) *reinterpret_cast<int*>(savep) = _mm_cvtsi128_si32(t##i), savep += vertex_size #endif #ifdef SIMD_NEON #define TEMP uint8x8_t #define PREP() uint8x8_t pi = vreinterpret_u8_u32(vld1_lane_u32(reinterpret_cast<uint32_t*>(last_vertex), vdup_n_u32(0), 0)) #define LOAD(i) uint8x16_t r##i = vld1q_u8(buffer + j + i * vertex_count_aligned) #define GRP4(i) t0 = vget_low_u8(r##i), t1 = vreinterpret_u8_u32(vdup_lane_u32(vreinterpret_u32_u8(t0), 1)), t2 = vget_high_u8(r##i), t3 = vreinterpret_u8_u32(vdup_lane_u32(vreinterpret_u32_u8(t2), 1)) #define FIXD(i) t##i = pi = Channel == 0 ? vadd_u8(pi, t##i) : (Channel == 1 ? vreinterpret_u8_u16(vadd_u16(vreinterpret_u16_u8(pi), vreinterpret_u16_u8(t##i))) : veor_u8(pi, t##i)) #define SAVE(i) vst1_lane_u32(reinterpret_cast<uint32_t*>(savep), vreinterpret_u32_u8(t##i), 0), savep += vertex_size #endif #ifdef SIMD_WASM #define TEMP v128_t #define PREP() v128_t pi = wasm_v128_load(last_vertex) #define LOAD(i) v128_t r##i = wasm_v128_load(buffer + j + i * vertex_count_aligned) #define GRP4(i) t0 = r##i, t1 = wasmx_splat_v32x4(r##i, 1), t2 = wasmx_splat_v32x4(r##i, 2), t3 = wasmx_splat_v32x4(r##i, 3) #define FIXD(i) t##i = pi = Channel == 0 ? wasm_i8x16_add(pi, t##i) : (Channel == 1 ? wasm_i16x8_add(pi, t##i) : wasm_v128_xor(pi, t##i)) #define SAVE(i) wasm_v128_store32_lane(savep, t##i, 0), savep += vertex_size #endif #define UNZR(i) r##i = Channel == 0 ? unzigzag8(r##i) : (Channel == 1 ? unzigzag16(r##i) : rotate32(r##i, rot)) PREP(); unsigned char* savep = transposed; for (size_t j = 0; j < vertex_count_aligned; j += 16) { LOAD(0); LOAD(1); LOAD(2); LOAD(3); transpose8(r0, r1, r2, r3); TEMP t0, t1, t2, t3; TEMP npi = pi; UNZR(0); GRP4(0); FIXD(0), FIXD(1), FIXD(2), FIXD(3); SAVE(0), SAVE(1), SAVE(2), SAVE(3); UNZR(1); GRP4(1); FIXD(0), FIXD(1), FIXD(2), FIXD(3); SAVE(0), SAVE(1), SAVE(2), SAVE(3); UNZR(2); GRP4(2); FIXD(0), FIXD(1), FIXD(2), FIXD(3); SAVE(0), SAVE(1), SAVE(2), SAVE(3); UNZR(3); GRP4(3); FIXD(0), FIXD(1), FIXD(2), FIXD(3); SAVE(0), SAVE(1), SAVE(2), SAVE(3); #if defined(SIMD_LATENCYOPT) && defined(SIMD_NEON) && (defined(__APPLE__) || defined(_WIN32)) // instead of relying on accumulated pi, recompute it from scratch from r0..r3; this shortens dependency between loop iterations pi = rebase<Channel>(npi, r0, r1, r2, r3); #else (void)npi; #endif #undef UNZR #undef TEMP #undef PREP #undef LOAD #undef GRP4 #undef FIXD #undef SAVE } } SIMD_TARGET static const unsigned char* decodeVertexBlockSimd(const unsigned char* data, const unsigned char* data_end, unsigned char* vertex_data, size_t vertex_count, size_t vertex_size, unsigned char last_vertex[256], const unsigned char* channels, int version) { assert(vertex_count > 0 && vertex_count <= kVertexBlockMaxSize); unsigned char buffer[kVertexBlockMaxSize * 4]; unsigned char transposed[kVertexBlockSizeBytes]; size_t vertex_count_aligned = (vertex_count + kByteGroupSize - 1) & ~(kByteGroupSize - 1); size_t control_size = version == 0 ? 0 : vertex_size / 4; if (size_t(data_end - data) < control_size) return NULL; const unsigned char* control = data; data += control_size; for (size_t k = 0; k < vertex_size; k += 4) { unsigned char ctrl_byte = version == 0 ? 0 : control[k / 4]; for (size_t j = 0; j < 4; ++j) { int ctrl = (ctrl_byte >> (j * 2)) & 3; if (ctrl == 3) { // literal encoding; safe to over-copy due to tail if (size_t(data_end - data) < vertex_count_aligned) return NULL; memcpy(buffer + j * vertex_count_aligned, data, vertex_count_aligned); data += vertex_count; } else if (ctrl == 2) { // zero encoding memset(buffer + j * vertex_count_aligned, 0, vertex_count_aligned); } else { // for v0, headers are mapped to 0..3; for v1, headers are mapped to 4..8 int hshift = version == 0 ? 0 : 4 + ctrl; data = decodeBytesSimd(data, data_end, buffer + j * vertex_count_aligned, vertex_count_aligned, hshift); if (!data) return NULL; } } int channel = version == 0 ? 0 : channels[k / 4]; switch (channel & 3) { case 0: decodeDeltas4Simd<0>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, 0); break; case 1: decodeDeltas4Simd<1>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, 0); break; case 2: decodeDeltas4Simd<2>(buffer, transposed + k, vertex_count_aligned, vertex_size, last_vertex + k, (32 - (channel >> 4)) & 31); break; default: return NULL; // invalid channel type } } memcpy(vertex_data, transposed, vertex_count * vertex_size); memcpy(last_vertex, &transposed[vertex_size * (vertex_count - 1)], vertex_size); return data; } #endif #if defined(SIMD_SSE) && defined(SIMD_FALLBACK) static unsigned int getCpuFeatures() { int cpuinfo[4] = {}; #ifdef _MSC_VER __cpuid(cpuinfo, 1); #else __cpuid(1, cpuinfo[0], cpuinfo[1], cpuinfo[2], cpuinfo[3]); #endif return cpuinfo[2]; } static unsigned int cpuid = getCpuFeatures(); #endif } // namespace meshopt size_t meshopt_encodeVertexBufferLevel(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size, int level, int version) { using namespace meshopt; assert(vertex_size > 0 && vertex_size <= 256); assert(vertex_size % 4 == 0); assert(level >= 0 && level <= 9); // only a subset of this range is used right now assert(version < 0 || unsigned(version) <= kDecodeVertexVersion); version = version < 0 ? gEncodeVertexVersion : version; #if TRACE memset(vertexstats, 0, sizeof(vertexstats)); #endif const unsigned char* vertex_data = static_cast<const unsigned char*>(vertices); unsigned char* data = buffer; unsigned char* data_end = buffer + buffer_size; if (size_t(data_end - data) < 1) return 0; *data++ = (unsigned char)(kVertexHeader | version); unsigned char first_vertex[256] = {}; if (vertex_count > 0) memcpy(first_vertex, vertex_data, vertex_size); unsigned char last_vertex[256] = {}; memcpy(last_vertex, first_vertex, vertex_size); size_t vertex_block_size = getVertexBlockSize(vertex_size); unsigned char channels[64] = {}; if (version != 0 && level > 1 && vertex_count > 1) for (size_t k = 0; k < vertex_size; k += 4) { int rot = level >= 3 ? estimateRotate(vertex_data, vertex_count, vertex_size, k, /* group_size= */ 16) : 0; int channel = estimateChannel(vertex_data, vertex_count, vertex_size, k, vertex_block_size, /* block_skip= */ 3, /* max_channels= */ level >= 3 ? 3 : 2, rot); assert(unsigned(channel) < 2 || ((channel & 3) == 2 && unsigned(channel >> 4) < 8)); channels[k / 4] = (unsigned char)channel; } size_t vertex_offset = 0; while (vertex_offset < vertex_count) { size_t block_size = (vertex_offset + vertex_block_size < vertex_count) ? vertex_block_size : vertex_count - vertex_offset; data = encodeVertexBlock(data, data_end, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, last_vertex, channels, version, level); if (!data) return 0; vertex_offset += block_size; } size_t tail_size = vertex_size + (version == 0 ? 0 : vertex_size / 4); size_t tail_size_min = version == 0 ? kTailMinSizeV0 : kTailMinSizeV1; size_t tail_size_pad = tail_size < tail_size_min ? tail_size_min : tail_size; if (size_t(data_end - data) < tail_size_pad) return 0; if (tail_size < tail_size_pad) { memset(data, 0, tail_size_pad - tail_size); data += tail_size_pad - tail_size; } memcpy(data, first_vertex, vertex_size); data += vertex_size; if (version != 0) { memcpy(data, channels, vertex_size / 4); data += vertex_size / 4; } assert(data >= buffer + tail_size); assert(data <= buffer + buffer_size); #if TRACE size_t total_size = data - buffer; for (size_t k = 0; k < vertex_size; ++k) { const Stats& vsk = vertexstats[k]; printf("%2d: %7d bytes [%4.1f%%] %.1f bpv", int(k), int(vsk.size), double(vsk.size) / double(total_size) * 100, double(vsk.size) / double(vertex_count) * 8); size_t total_k = vsk.header + vsk.bitg[1] + vsk.bitg[2] + vsk.bitg[4] + vsk.bitg[8]; double total_kr = total_k ? 1.0 / double(total_k) : 0; if (version != 0) { int channel = channels[k / 4]; if ((channel & 3) == 2 && k % 4 == 0) printf(" | ^%d", channel >> 4); else printf(" | %2s", channel == 0 ? "1" : (channel == 1 && k % 2 == 0 ? "2" : ".")); } printf(" | hdr [%5.1f%%] bitg [1 %4.1f%% 2 %4.1f%% 4 %4.1f%% 8 %4.1f%%]", double(vsk.header) * total_kr * 100, double(vsk.bitg[1]) * total_kr * 100, double(vsk.bitg[2]) * total_kr * 100, double(vsk.bitg[4]) * total_kr * 100, double(vsk.bitg[8]) * total_kr * 100); size_t total_ctrl = vsk.ctrl[0] + vsk.ctrl[1] + vsk.ctrl[2] + vsk.ctrl[3]; if (total_ctrl) { printf(" | ctrl %3.0f%% %3.0f%% %3.0f%% %3.0f%%", double(vsk.ctrl[0]) / double(total_ctrl) * 100, double(vsk.ctrl[1]) / double(total_ctrl) * 100, double(vsk.ctrl[2]) / double(total_ctrl) * 100, double(vsk.ctrl[3]) / double(total_ctrl) * 100); } if (level >= 3) printf(" | bitc [%3.0f%% %3.0f%% %3.0f%% %3.0f%% %3.0f%% %3.0f%% %3.0f%% %3.0f%%]", double(vsk.bitc[0]) / double(vertex_count) * 100, double(vsk.bitc[1]) / double(vertex_count) * 100, double(vsk.bitc[2]) / double(vertex_count) * 100, double(vsk.bitc[3]) / double(vertex_count) * 100, double(vsk.bitc[4]) / double(vertex_count) * 100, double(vsk.bitc[5]) / double(vertex_count) * 100, double(vsk.bitc[6]) / double(vertex_count) * 100, double(vsk.bitc[7]) / double(vertex_count) * 100); printf("\n"); } #endif return data - buffer; } size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size) { return meshopt_encodeVertexBufferLevel(buffer, buffer_size, vertices, vertex_count, vertex_size, meshopt::kEncodeDefaultLevel, meshopt::gEncodeVertexVersion); } size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size) { using namespace meshopt; assert(vertex_size > 0 && vertex_size <= 256); assert(vertex_size % 4 == 0); size_t vertex_block_size = getVertexBlockSize(vertex_size); size_t vertex_block_count = (vertex_count + vertex_block_size - 1) / vertex_block_size; size_t vertex_block_control_size = vertex_size / 4; size_t vertex_block_header_size = (vertex_block_size / kByteGroupSize + 3) / 4; size_t vertex_block_data_size = vertex_block_size; size_t tail_size = vertex_size + (vertex_size / 4); size_t tail_size_min = kTailMinSizeV0 > kTailMinSizeV1 ? kTailMinSizeV0 : kTailMinSizeV1; size_t tail_size_pad = tail_size < tail_size_min ? tail_size_min : tail_size; assert(tail_size_pad >= kByteGroupDecodeLimit); return 1 + vertex_block_count * vertex_size * (vertex_block_control_size + vertex_block_header_size + vertex_block_data_size) + tail_size_pad; } void meshopt_encodeVertexVersion(int version) { assert(unsigned(version) <= unsigned(meshopt::kDecodeVertexVersion)); meshopt::gEncodeVertexVersion = version; } int meshopt_decodeVertexVersion(const unsigned char* buffer, size_t buffer_size) { if (buffer_size < 1) return -1; unsigned char header = buffer[0]; if ((header & 0xf0) != meshopt::kVertexHeader) return -1; int version = header & 0x0f; if (version > meshopt::kDecodeVertexVersion) return -1; return version; } int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t vertex_size, const unsigned char* buffer, size_t buffer_size) { using namespace meshopt; assert(vertex_size > 0 && vertex_size <= 256); assert(vertex_size % 4 == 0); const unsigned char* (*decode)(const unsigned char*, const unsigned char*, unsigned char*, size_t, size_t, unsigned char[256], const unsigned char*, int) = NULL; #if defined(SIMD_SSE) && defined(SIMD_FALLBACK) decode = (cpuid & (1 << 9)) ? decodeVertexBlockSimd : decodeVertexBlock; #elif defined(SIMD_SSE) || defined(SIMD_AVX) || defined(SIMD_NEON) || defined(SIMD_WASM) decode = decodeVertexBlockSimd; #else decode = decodeVertexBlock; #endif #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) assert(gDecodeBytesGroupInitialized); (void)gDecodeBytesGroupInitialized; #endif unsigned char* vertex_data = static_cast<unsigned char*>(destination); const unsigned char* data = buffer; const unsigned char* data_end = buffer + buffer_size; if (size_t(data_end - data) < 1) return -2; unsigned char data_header = *data++; if ((data_header & 0xf0) != kVertexHeader) return -1; int version = data_header & 0x0f; if (version > kDecodeVertexVersion) return -1; size_t tail_size = vertex_size + (version == 0 ? 0 : vertex_size / 4); size_t tail_size_min = version == 0 ? kTailMinSizeV0 : kTailMinSizeV1; size_t tail_size_pad = tail_size < tail_size_min ? tail_size_min : tail_size; if (size_t(data_end - data) < tail_size_pad) return -2; const unsigned char* tail = data_end - tail_size; unsigned char last_vertex[256]; memcpy(last_vertex, tail, vertex_size); const unsigned char* channels = version == 0 ? NULL : tail + vertex_size; size_t vertex_block_size = getVertexBlockSize(vertex_size); size_t vertex_offset = 0; while (vertex_offset < vertex_count) { size_t block_size = (vertex_offset + vertex_block_size < vertex_count) ? vertex_block_size : vertex_count - vertex_offset; data = decode(data, data_end, vertex_data + vertex_offset * vertex_size, block_size, vertex_size, last_vertex, channels, version); if (!data) return -2; vertex_offset += block_size; } if (size_t(data_end - data) != tail_size_pad) return -3; return 0; } #undef SIMD_NEON #undef SIMD_SSE #undef SIMD_AVX #undef SIMD_WASM #undef SIMD_FALLBACK #undef SIMD_TARGET #undef SIMD_LATENCYOPT
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/vertexfilter.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <math.h> #include <string.h> // The block below auto-detects SIMD ISA that can be used on the target platform #ifndef MESHOPTIMIZER_NO_SIMD // The SIMD implementation requires SSE2, which can be enabled unconditionally through compiler settings #if defined(__SSE2__) #define SIMD_SSE #endif // MSVC supports compiling SSE2 code regardless of compile options; we assume all 32-bit CPUs support SSE2 #if !defined(SIMD_SSE) && defined(_MSC_VER) && !defined(__clang__) && (defined(_M_IX86) || defined(_M_X64)) #define SIMD_SSE #endif // GCC/clang define these when NEON support is available #if defined(__ARM_NEON__) || defined(__ARM_NEON) #define SIMD_NEON #endif // On MSVC, we assume that ARM builds always target NEON-capable devices #if !defined(SIMD_NEON) && defined(_MSC_VER) && (defined(_M_ARM) || defined(_M_ARM64)) #define SIMD_NEON #endif // When targeting Wasm SIMD we can't use runtime cpuid checks so we unconditionally enable SIMD #if defined(__wasm_simd128__) #define SIMD_WASM // Prevent compiling other variant when wasm simd compilation is active #undef SIMD_NEON #undef SIMD_SSE #endif #endif // !MESHOPTIMIZER_NO_SIMD #ifdef SIMD_SSE #include <emmintrin.h> #include <stdint.h> #endif #ifdef _MSC_VER #include <intrin.h> #endif #ifdef SIMD_NEON #if defined(_MSC_VER) && defined(_M_ARM64) #include <arm64_neon.h> #else #include <arm_neon.h> #endif #endif #ifdef SIMD_WASM #undef __DEPRECATED #include <wasm_simd128.h> #endif #ifdef SIMD_WASM #define wasmx_unpacklo_v16x8(a, b) wasm_v16x8_shuffle(a, b, 0, 8, 1, 9, 2, 10, 3, 11) #define wasmx_unpackhi_v16x8(a, b) wasm_v16x8_shuffle(a, b, 4, 12, 5, 13, 6, 14, 7, 15) #define wasmx_unziplo_v32x4(a, b) wasm_v32x4_shuffle(a, b, 0, 2, 4, 6) #define wasmx_unziphi_v32x4(a, b) wasm_v32x4_shuffle(a, b, 1, 3, 5, 7) #endif #ifndef __has_builtin #define __has_builtin(x) 0 #endif namespace meshopt { #if !defined(SIMD_SSE) && !defined(SIMD_NEON) && !defined(SIMD_WASM) template <typename T> static void decodeFilterOct(T* data, size_t count) { const float max = float((1 << (sizeof(T) * 8 - 1)) - 1); for (size_t i = 0; i < count; ++i) { // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count float x = float(data[i * 4 + 0]); float y = float(data[i * 4 + 1]); float z = float(data[i * 4 + 2]) - fabsf(x) - fabsf(y); // fixup octahedral coordinates for z<0 float t = (z >= 0.f) ? 0.f : z; x += (x >= 0.f) ? t : -t; y += (y >= 0.f) ? t : -t; // compute normal length & scale float l = sqrtf(x * x + y * y + z * z); float s = max / l; // rounded signed float->int int xf = int(x * s + (x >= 0.f ? 0.5f : -0.5f)); int yf = int(y * s + (y >= 0.f ? 0.5f : -0.5f)); int zf = int(z * s + (z >= 0.f ? 0.5f : -0.5f)); data[i * 4 + 0] = T(xf); data[i * 4 + 1] = T(yf); data[i * 4 + 2] = T(zf); } } static void decodeFilterQuat(short* data, size_t count) { const float scale = 32767.f / sqrtf(2.f); for (size_t i = 0; i < count; ++i) { // recover scale from the high byte of the component int sf = data[i * 4 + 3] | 3; float s = float(sf); // convert x/y/z to floating point (unscaled! implied scale of 1/sqrt(2.f) * 1/sf) float x = float(data[i * 4 + 0]); float y = float(data[i * 4 + 1]); float z = float(data[i * 4 + 2]); // reconstruct w as a square root (unscaled); we clamp to 0.f to avoid NaN due to precision errors float ws = s * s; float ww = ws * 2.f - x * x - y * y - z * z; float w = sqrtf(ww >= 0.f ? ww : 0.f); // compute final scale; note that all computations above are unscaled // we need to divide by sf to get out of fixed point, divide by sqrt(2) to renormalize and multiply by 32767 to get to int16 range float ss = scale / s; // rounded signed float->int int xf = int(x * ss + (x >= 0.f ? 0.5f : -0.5f)); int yf = int(y * ss + (y >= 0.f ? 0.5f : -0.5f)); int zf = int(z * ss + (z >= 0.f ? 0.5f : -0.5f)); int wf = int(w * ss + 0.5f); int qc = data[i * 4 + 3] & 3; // output order is dictated by input index data[i * 4 + ((qc + 1) & 3)] = short(xf); data[i * 4 + ((qc + 2) & 3)] = short(yf); data[i * 4 + ((qc + 3) & 3)] = short(zf); data[i * 4 + ((qc + 0) & 3)] = short(wf); } } static void decodeFilterExp(unsigned int* data, size_t count) { for (size_t i = 0; i < count; ++i) { unsigned int v = data[i]; // decode mantissa and exponent int m = int(v << 8) >> 8; int e = int(v) >> 24; union { float f; unsigned int ui; } u; // optimized version of ldexp(float(m), e) u.ui = unsigned(e + 127) << 23; u.f = u.f * float(m); data[i] = u.ui; } } template <typename ST, typename T> static void decodeFilterColor(T* data, size_t count) { const float max = float((1 << (sizeof(T) * 8)) - 1); for (size_t i = 0; i < count; ++i) { // recover scale from alpha high bit int as = data[i * 4 + 3]; as |= as >> 1; as |= as >> 2; as |= as >> 4; as |= as >> 8; // noop for 8-bit // convert to RGB in fixed point (co/cg are sign extended) int y = data[i * 4 + 0], co = ST(data[i * 4 + 1]), cg = ST(data[i * 4 + 2]); int r = y + co - cg; int g = y + cg; int b = y - co - cg; // expand alpha by one bit to match other components int a = data[i * 4 + 3]; a = ((a << 1) & as) | (a & 1); // compute scaling factor float ss = max / float(as); // rounded float->int int rf = int(float(r) * ss + 0.5f); int gf = int(float(g) * ss + 0.5f); int bf = int(float(b) * ss + 0.5f); int af = int(float(a) * ss + 0.5f); data[i * 4 + 0] = T(rf); data[i * 4 + 1] = T(gf); data[i * 4 + 2] = T(bf); data[i * 4 + 3] = T(af); } } #endif #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) template <typename T> static void dispatchSimd(void (*process)(T*, size_t), T* data, size_t count, size_t stride) { assert(stride <= 4); size_t count4 = count & ~size_t(3); process(data, count4); if (count4 < count) { T tail[4 * 4] = {}; // max stride 4, max count 4 size_t tail_size = (count - count4) * stride * sizeof(T); assert(tail_size <= sizeof(tail)); memcpy(tail, data + count4 * stride, tail_size); process(tail, count - count4); memcpy(data + count4 * stride, tail, tail_size); } } inline uint64_t rotateleft64(uint64_t v, int x) { #if defined(_MSC_VER) && !defined(__clang__) return _rotl64(v, x); #elif defined(__clang__) && __has_builtin(__builtin_rotateleft64) return __builtin_rotateleft64(v, x); #else return (v << (x & 63)) | (v >> ((64 - x) & 63)); #endif } #endif #ifdef SIMD_SSE static void decodeFilterOctSimd8(signed char* data, size_t count) { const __m128 sign = _mm_set1_ps(-0.f); for (size_t i = 0; i < count; i += 4) { __m128i n4 = _mm_loadu_si128(reinterpret_cast<__m128i*>(&data[i * 4])); // sign-extends each of x,y in [x y ? ?] with arithmetic shifts __m128i xf = _mm_srai_epi32(_mm_slli_epi32(n4, 24), 24); __m128i yf = _mm_srai_epi32(_mm_slli_epi32(n4, 16), 24); // unpack z; note that z is unsigned so we technically don't need to sign extend it __m128i zf = _mm_srai_epi32(_mm_slli_epi32(n4, 8), 24); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count __m128 x = _mm_cvtepi32_ps(xf); __m128 y = _mm_cvtepi32_ps(yf); __m128 z = _mm_sub_ps(_mm_cvtepi32_ps(zf), _mm_add_ps(_mm_andnot_ps(sign, x), _mm_andnot_ps(sign, y))); // fixup octahedral coordinates for z<0 __m128 t = _mm_min_ps(z, _mm_setzero_ps()); x = _mm_add_ps(x, _mm_xor_ps(t, _mm_and_ps(x, sign))); y = _mm_add_ps(y, _mm_xor_ps(t, _mm_and_ps(y, sign))); // compute normal length & scale __m128 ll = _mm_add_ps(_mm_mul_ps(x, x), _mm_add_ps(_mm_mul_ps(y, y), _mm_mul_ps(z, z))); __m128 s = _mm_mul_ps(_mm_set1_ps(127.f), _mm_rsqrt_ps(ll)); // rounded signed float->int __m128i xr = _mm_cvtps_epi32(_mm_mul_ps(x, s)); __m128i yr = _mm_cvtps_epi32(_mm_mul_ps(y, s)); __m128i zr = _mm_cvtps_epi32(_mm_mul_ps(z, s)); // combine xr/yr/zr into final value __m128i res = _mm_and_si128(n4, _mm_set1_epi32(0xff000000)); res = _mm_or_si128(res, _mm_and_si128(xr, _mm_set1_epi32(0xff))); res = _mm_or_si128(res, _mm_slli_epi32(_mm_and_si128(yr, _mm_set1_epi32(0xff)), 8)); res = _mm_or_si128(res, _mm_slli_epi32(_mm_and_si128(zr, _mm_set1_epi32(0xff)), 16)); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[i * 4]), res); } } static void decodeFilterOctSimd16(short* data, size_t count) { const __m128 sign = _mm_set1_ps(-0.f); for (size_t i = 0; i < count; i += 4) { __m128 n4_0 = _mm_loadu_ps(reinterpret_cast<float*>(&data[(i + 0) * 4])); __m128 n4_1 = _mm_loadu_ps(reinterpret_cast<float*>(&data[(i + 2) * 4])); // gather both x/y 16-bit pairs in each 32-bit lane __m128i n4 = _mm_castps_si128(_mm_shuffle_ps(n4_0, n4_1, _MM_SHUFFLE(2, 0, 2, 0))); // sign-extends each of x,y in [x y] with arithmetic shifts __m128i xf = _mm_srai_epi32(_mm_slli_epi32(n4, 16), 16); __m128i yf = _mm_srai_epi32(n4, 16); // unpack z; note that z is unsigned so we don't need to sign extend it __m128i z4 = _mm_castps_si128(_mm_shuffle_ps(n4_0, n4_1, _MM_SHUFFLE(3, 1, 3, 1))); __m128i zf = _mm_and_si128(z4, _mm_set1_epi32(0x7fff)); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count __m128 x = _mm_cvtepi32_ps(xf); __m128 y = _mm_cvtepi32_ps(yf); __m128 z = _mm_sub_ps(_mm_cvtepi32_ps(zf), _mm_add_ps(_mm_andnot_ps(sign, x), _mm_andnot_ps(sign, y))); // fixup octahedral coordinates for z<0 __m128 t = _mm_min_ps(z, _mm_setzero_ps()); x = _mm_add_ps(x, _mm_xor_ps(t, _mm_and_ps(x, sign))); y = _mm_add_ps(y, _mm_xor_ps(t, _mm_and_ps(y, sign))); // compute normal length & scale __m128 ll = _mm_add_ps(_mm_mul_ps(x, x), _mm_add_ps(_mm_mul_ps(y, y), _mm_mul_ps(z, z))); __m128 s = _mm_div_ps(_mm_set1_ps(32767.f), _mm_sqrt_ps(ll)); // rounded signed float->int __m128i xr = _mm_cvtps_epi32(_mm_mul_ps(x, s)); __m128i yr = _mm_cvtps_epi32(_mm_mul_ps(y, s)); __m128i zr = _mm_cvtps_epi32(_mm_mul_ps(z, s)); // mix x/z and y/0 to make 16-bit unpack easier __m128i xzr = _mm_or_si128(_mm_and_si128(xr, _mm_set1_epi32(0xffff)), _mm_slli_epi32(zr, 16)); __m128i y0r = _mm_and_si128(yr, _mm_set1_epi32(0xffff)); // pack x/y/z using 16-bit unpacks; note that this has 0 where we should have .w __m128i res_0 = _mm_unpacklo_epi16(xzr, y0r); __m128i res_1 = _mm_unpackhi_epi16(xzr, y0r); // patch in .w __m128i maskw = _mm_set_epi32(0xffff0000, 0, 0xffff0000, 0); res_0 = _mm_or_si128(res_0, _mm_and_si128(_mm_castps_si128(n4_0), maskw)); res_1 = _mm_or_si128(res_1, _mm_and_si128(_mm_castps_si128(n4_1), maskw)); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[(i + 0) * 4]), res_0); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[(i + 2) * 4]), res_1); } } static void decodeFilterQuatSimd(short* data, size_t count) { const float scale = 32767.f / sqrtf(2.f); for (size_t i = 0; i < count; i += 4) { __m128 q4_0 = _mm_loadu_ps(reinterpret_cast<float*>(&data[(i + 0) * 4])); __m128 q4_1 = _mm_loadu_ps(reinterpret_cast<float*>(&data[(i + 2) * 4])); // gather both x/y 16-bit pairs in each 32-bit lane __m128i q4_xy = _mm_castps_si128(_mm_shuffle_ps(q4_0, q4_1, _MM_SHUFFLE(2, 0, 2, 0))); __m128i q4_zc = _mm_castps_si128(_mm_shuffle_ps(q4_0, q4_1, _MM_SHUFFLE(3, 1, 3, 1))); // sign-extends each of x,y in [x y] with arithmetic shifts __m128i xf = _mm_srai_epi32(_mm_slli_epi32(q4_xy, 16), 16); __m128i yf = _mm_srai_epi32(q4_xy, 16); __m128i zf = _mm_srai_epi32(_mm_slli_epi32(q4_zc, 16), 16); __m128i cf = _mm_srai_epi32(q4_zc, 16); // get a floating-point scaler using zc with bottom 2 bits set to 1 (which represents 1.f) __m128i sf = _mm_or_si128(cf, _mm_set1_epi32(3)); __m128 s = _mm_cvtepi32_ps(sf); // convert x/y/z to floating point (unscaled! implied scale of 1/sqrt(2.f) * 1/sf) __m128 x = _mm_cvtepi32_ps(xf); __m128 y = _mm_cvtepi32_ps(yf); __m128 z = _mm_cvtepi32_ps(zf); // reconstruct w as a square root (unscaled); we clamp to 0.f to avoid NaN due to precision errors __m128 ws = _mm_mul_ps(s, _mm_add_ps(s, s)); // s*2s instead of 2*(s*s) to work around clang bug with integer multiplication __m128 ww = _mm_sub_ps(ws, _mm_add_ps(_mm_mul_ps(x, x), _mm_add_ps(_mm_mul_ps(y, y), _mm_mul_ps(z, z)))); __m128 w = _mm_sqrt_ps(_mm_max_ps(ww, _mm_setzero_ps())); // compute final scale; note that all computations above are unscaled // we need to divide by sf to get out of fixed point, divide by sqrt(2) to renormalize and multiply by 32767 to get to int16 range __m128 ss = _mm_div_ps(_mm_set1_ps(scale), s); // rounded signed float->int __m128i xr = _mm_cvtps_epi32(_mm_mul_ps(x, ss)); __m128i yr = _mm_cvtps_epi32(_mm_mul_ps(y, ss)); __m128i zr = _mm_cvtps_epi32(_mm_mul_ps(z, ss)); __m128i wr = _mm_cvtps_epi32(_mm_mul_ps(w, ss)); // mix x/z and w/y to make 16-bit unpack easier __m128i xzr = _mm_or_si128(_mm_and_si128(xr, _mm_set1_epi32(0xffff)), _mm_slli_epi32(zr, 16)); __m128i wyr = _mm_or_si128(_mm_and_si128(wr, _mm_set1_epi32(0xffff)), _mm_slli_epi32(yr, 16)); // pack x/y/z/w using 16-bit unpacks; we pack wxyz by default (for qc=0) __m128i res_0 = _mm_unpacklo_epi16(wyr, xzr); __m128i res_1 = _mm_unpackhi_epi16(wyr, xzr); // store results to stack so that we can rotate using scalar instructions uint64_t res[4]; _mm_storeu_si128(reinterpret_cast<__m128i*>(&res[0]), res_0); _mm_storeu_si128(reinterpret_cast<__m128i*>(&res[2]), res_1); // rotate and store uint64_t* out = reinterpret_cast<uint64_t*>(&data[i * 4]); out[0] = rotateleft64(res[0], data[(i + 0) * 4 + 3] << 4); out[1] = rotateleft64(res[1], data[(i + 1) * 4 + 3] << 4); out[2] = rotateleft64(res[2], data[(i + 2) * 4 + 3] << 4); out[3] = rotateleft64(res[3], data[(i + 3) * 4 + 3] << 4); } } static void decodeFilterExpSimd(unsigned int* data, size_t count) { for (size_t i = 0; i < count; i += 4) { __m128i v = _mm_loadu_si128(reinterpret_cast<__m128i*>(&data[i])); // decode exponent into 2^x directly __m128i ef = _mm_srai_epi32(v, 24); __m128i es = _mm_slli_epi32(_mm_add_epi32(ef, _mm_set1_epi32(127)), 23); // decode 24-bit mantissa into floating-point value __m128i mf = _mm_srai_epi32(_mm_slli_epi32(v, 8), 8); __m128 m = _mm_cvtepi32_ps(mf); __m128 r = _mm_mul_ps(_mm_castsi128_ps(es), m); _mm_storeu_ps(reinterpret_cast<float*>(&data[i]), r); } } static void decodeFilterColorSimd8(unsigned char* data, size_t count) { for (size_t i = 0; i < count; i += 4) { __m128i c4 = _mm_loadu_si128(reinterpret_cast<__m128i*>(&data[i * 4])); // unpack y/co/cg/a (co/cg are sign extended with arithmetic shifts) __m128i yf = _mm_and_si128(c4, _mm_set1_epi32(0xff)); __m128i cof = _mm_srai_epi32(_mm_slli_epi32(c4, 16), 24); __m128i cgf = _mm_srai_epi32(_mm_slli_epi32(c4, 8), 24); __m128i af = _mm_srli_epi32(c4, 24); // recover scale from alpha high bit __m128i as = af; as = _mm_or_si128(as, _mm_srli_epi32(as, 1)); as = _mm_or_si128(as, _mm_srli_epi32(as, 2)); as = _mm_or_si128(as, _mm_srli_epi32(as, 4)); // expand alpha by one bit to match other components af = _mm_or_si128(_mm_and_si128(_mm_slli_epi32(af, 1), as), _mm_and_si128(af, _mm_set1_epi32(1))); // compute scaling factor __m128 ss = _mm_mul_ps(_mm_set1_ps(255.f), _mm_rcp_ps(_mm_cvtepi32_ps(as))); // convert to RGB in fixed point __m128i rf = _mm_add_epi32(yf, _mm_sub_epi32(cof, cgf)); __m128i gf = _mm_add_epi32(yf, cgf); __m128i bf = _mm_sub_epi32(yf, _mm_add_epi32(cof, cgf)); // rounded signed float->int __m128i rr = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(rf), ss)); __m128i gr = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(gf), ss)); __m128i br = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(bf), ss)); __m128i ar = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(af), ss)); // repack rgba into final value __m128i res = rr; res = _mm_or_si128(res, _mm_slli_epi32(gr, 8)); res = _mm_or_si128(res, _mm_slli_epi32(br, 16)); res = _mm_or_si128(res, _mm_slli_epi32(ar, 24)); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[i * 4]), res); } } static void decodeFilterColorSimd16(unsigned short* data, size_t count) { for (size_t i = 0; i < count; i += 4) { __m128i c4_0 = _mm_loadu_si128(reinterpret_cast<__m128i*>(&data[(i + 0) * 4])); __m128i c4_1 = _mm_loadu_si128(reinterpret_cast<__m128i*>(&data[(i + 2) * 4])); // gather both y/co 16-bit pairs in each 32-bit lane __m128i c4_yco = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(c4_0), _mm_castsi128_ps(c4_1), _MM_SHUFFLE(2, 0, 2, 0))); __m128i c4_cga = _mm_castps_si128(_mm_shuffle_ps(_mm_castsi128_ps(c4_0), _mm_castsi128_ps(c4_1), _MM_SHUFFLE(3, 1, 3, 1))); // unpack y/co/cg/a components (co/cg are sign extended with arithmetic shifts) __m128i yf = _mm_and_si128(c4_yco, _mm_set1_epi32(0xffff)); __m128i cof = _mm_srai_epi32(c4_yco, 16); __m128i cgf = _mm_srai_epi32(_mm_slli_epi32(c4_cga, 16), 16); __m128i af = _mm_srli_epi32(c4_cga, 16); // recover scale from alpha high bit __m128i as = af; as = _mm_or_si128(as, _mm_srli_epi32(as, 1)); as = _mm_or_si128(as, _mm_srli_epi32(as, 2)); as = _mm_or_si128(as, _mm_srli_epi32(as, 4)); as = _mm_or_si128(as, _mm_srli_epi32(as, 8)); // expand alpha by one bit to match other components af = _mm_or_si128(_mm_and_si128(_mm_slli_epi32(af, 1), as), _mm_and_si128(af, _mm_set1_epi32(1))); // compute scaling factor __m128 ss = _mm_div_ps(_mm_set1_ps(65535.f), _mm_cvtepi32_ps(as)); // convert to RGB in fixed point __m128i rf = _mm_add_epi32(yf, _mm_sub_epi32(cof, cgf)); __m128i gf = _mm_add_epi32(yf, cgf); __m128i bf = _mm_sub_epi32(yf, _mm_add_epi32(cof, cgf)); // rounded signed float->int __m128i rr = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(rf), ss)); __m128i gr = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(gf), ss)); __m128i br = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(bf), ss)); __m128i ar = _mm_cvtps_epi32(_mm_mul_ps(_mm_cvtepi32_ps(af), ss)); // mix r/b and g/a to make 16-bit unpack easier __m128i rbr = _mm_or_si128(_mm_and_si128(rr, _mm_set1_epi32(0xffff)), _mm_slli_epi32(br, 16)); __m128i gar = _mm_or_si128(_mm_and_si128(gr, _mm_set1_epi32(0xffff)), _mm_slli_epi32(ar, 16)); // pack r/g/b/a using 16-bit unpacks __m128i res_0 = _mm_unpacklo_epi16(rbr, gar); __m128i res_1 = _mm_unpackhi_epi16(rbr, gar); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[(i + 0) * 4]), res_0); _mm_storeu_si128(reinterpret_cast<__m128i*>(&data[(i + 2) * 4]), res_1); } } #endif #if defined(SIMD_NEON) && !defined(__aarch64__) && !defined(_M_ARM64) inline float32x4_t vsqrtq_f32(float32x4_t x) { float32x4_t r = vrsqrteq_f32(x); r = vmulq_f32(r, vrsqrtsq_f32(vmulq_f32(r, x), r)); // refine rsqrt estimate return vmulq_f32(r, x); } inline float32x4_t vdivq_f32(float32x4_t x, float32x4_t y) { float32x4_t r = vrecpeq_f32(y); r = vmulq_f32(r, vrecpsq_f32(y, r)); // refine rcp estimate return vmulq_f32(x, r); } #ifndef __ARM_FEATURE_FMA inline float32x4_t vfmaq_f32(float32x4_t x, float32x4_t y, float32x4_t z) { return vaddq_f32(x, vmulq_f32(y, z)); } #endif #endif #ifdef SIMD_NEON static void decodeFilterOctSimd8(signed char* data, size_t count) { const int32x4_t sign = vdupq_n_s32(0x80000000); for (size_t i = 0; i < count; i += 4) { int32x4_t n4 = vld1q_s32(reinterpret_cast<int32_t*>(&data[i * 4])); // sign-extends each of x,y in [x y ? ?] with arithmetic shifts int32x4_t xf = vshrq_n_s32(vshlq_n_s32(n4, 24), 24); int32x4_t yf = vshrq_n_s32(vshlq_n_s32(n4, 16), 24); // unpack z; note that z is unsigned so we technically don't need to sign extend it int32x4_t zf = vshrq_n_s32(vshlq_n_s32(n4, 8), 24); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count float32x4_t x = vcvtq_f32_s32(xf); float32x4_t y = vcvtq_f32_s32(yf); float32x4_t z = vsubq_f32(vcvtq_f32_s32(zf), vaddq_f32(vabsq_f32(x), vabsq_f32(y))); // fixup octahedral coordinates for z<0 float32x4_t t = vminq_f32(z, vdupq_n_f32(0.f)); x = vaddq_f32(x, vreinterpretq_f32_s32(veorq_s32(vreinterpretq_s32_f32(t), vandq_s32(vreinterpretq_s32_f32(x), sign)))); y = vaddq_f32(y, vreinterpretq_f32_s32(veorq_s32(vreinterpretq_s32_f32(t), vandq_s32(vreinterpretq_s32_f32(y), sign)))); // compute normal length & scale float32x4_t ll = vfmaq_f32(vfmaq_f32(vmulq_f32(x, x), y, y), z, z); float32x4_t rl = vrsqrteq_f32(ll); float32x4_t s = vmulq_f32(vdupq_n_f32(127.f), rl); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 8 bits so we can omit the subtraction const float32x4_t fsnap = vdupq_n_f32(3 << 22); int32x4_t xr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, x, s)); int32x4_t yr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, y, s)); int32x4_t zr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, z, s)); // combine xr/yr/zr into final value int32x4_t res = vsliq_n_s32(xr, vsliq_n_s32(yr, zr, 8), 8); res = vbslq_s32(vdupq_n_u32(0xff000000), n4, res); vst1q_s32(reinterpret_cast<int32_t*>(&data[i * 4]), res); } } static void decodeFilterOctSimd16(short* data, size_t count) { const int32x4_t sign = vdupq_n_s32(0x80000000); for (size_t i = 0; i < count; i += 4) { int32x4_t n4_0 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 0) * 4])); int32x4_t n4_1 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 2) * 4])); // gather both x/y 16-bit pairs in each 32-bit lane int32x4_t n4 = vuzpq_s32(n4_0, n4_1).val[0]; // sign-extends each of x,y in [x y] with arithmetic shifts int32x4_t xf = vshrq_n_s32(vshlq_n_s32(n4, 16), 16); int32x4_t yf = vshrq_n_s32(n4, 16); // unpack z; note that z is unsigned so we don't need to sign extend it int32x4_t z4 = vuzpq_s32(n4_0, n4_1).val[1]; int32x4_t zf = vandq_s32(z4, vdupq_n_s32(0x7fff)); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count float32x4_t x = vcvtq_f32_s32(xf); float32x4_t y = vcvtq_f32_s32(yf); float32x4_t z = vsubq_f32(vcvtq_f32_s32(zf), vaddq_f32(vabsq_f32(x), vabsq_f32(y))); // fixup octahedral coordinates for z<0 float32x4_t t = vminq_f32(z, vdupq_n_f32(0.f)); x = vaddq_f32(x, vreinterpretq_f32_s32(veorq_s32(vreinterpretq_s32_f32(t), vandq_s32(vreinterpretq_s32_f32(x), sign)))); y = vaddq_f32(y, vreinterpretq_f32_s32(veorq_s32(vreinterpretq_s32_f32(t), vandq_s32(vreinterpretq_s32_f32(y), sign)))); // compute normal length & scale float32x4_t ll = vfmaq_f32(vfmaq_f32(vmulq_f32(x, x), y, y), z, z); #if !defined(__aarch64__) && !defined(_M_ARM64) float32x4_t rl = vrsqrteq_f32(ll); rl = vmulq_f32(rl, vrsqrtsq_f32(vmulq_f32(rl, ll), rl)); // refine rsqrt estimate float32x4_t s = vmulq_f32(vdupq_n_f32(32767.f), rl); #else float32x4_t s = vdivq_f32(vdupq_n_f32(32767.f), vsqrtq_f32(ll)); #endif // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const float32x4_t fsnap = vdupq_n_f32(3 << 22); int32x4_t xr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, x, s)); int32x4_t yr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, y, s)); int32x4_t zr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, z, s)); // mix x/z and y/0 to make 16-bit unpack easier int32x4_t xzr = vsliq_n_s32(xr, zr, 16); int32x4_t y0r = vandq_s32(yr, vdupq_n_s32(0xffff)); // pack x/y/z using 16-bit unpacks; note that this has 0 where we should have .w int32x4_t res_0 = vreinterpretq_s32_s16(vzipq_s16(vreinterpretq_s16_s32(xzr), vreinterpretq_s16_s32(y0r)).val[0]); int32x4_t res_1 = vreinterpretq_s32_s16(vzipq_s16(vreinterpretq_s16_s32(xzr), vreinterpretq_s16_s32(y0r)).val[1]); // patch in .w res_0 = vbslq_s32(vreinterpretq_u32_u64(vdupq_n_u64(0xffff000000000000)), n4_0, res_0); res_1 = vbslq_s32(vreinterpretq_u32_u64(vdupq_n_u64(0xffff000000000000)), n4_1, res_1); vst1q_s32(reinterpret_cast<int32_t*>(&data[(i + 0) * 4]), res_0); vst1q_s32(reinterpret_cast<int32_t*>(&data[(i + 2) * 4]), res_1); } } static void decodeFilterQuatSimd(short* data, size_t count) { const float scale = 32767.f / sqrtf(2.f); for (size_t i = 0; i < count; i += 4) { int32x4_t q4_0 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 0) * 4])); int32x4_t q4_1 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 2) * 4])); // gather both x/y 16-bit pairs in each 32-bit lane int32x4_t q4_xy = vuzpq_s32(q4_0, q4_1).val[0]; int32x4_t q4_zc = vuzpq_s32(q4_0, q4_1).val[1]; // sign-extends each of x,y in [x y] with arithmetic shifts int32x4_t xf = vshrq_n_s32(vshlq_n_s32(q4_xy, 16), 16); int32x4_t yf = vshrq_n_s32(q4_xy, 16); int32x4_t zf = vshrq_n_s32(vshlq_n_s32(q4_zc, 16), 16); int32x4_t cf = vshrq_n_s32(q4_zc, 16); // get a floating-point scaler using zc with bottom 2 bits set to 1 (which represents 1.f) int32x4_t sf = vorrq_s32(cf, vdupq_n_s32(3)); float32x4_t s = vcvtq_f32_s32(sf); // convert x/y/z to floating point (unscaled! implied scale of 1/sqrt(2.f) * 1/sf) float32x4_t x = vcvtq_f32_s32(xf); float32x4_t y = vcvtq_f32_s32(yf); float32x4_t z = vcvtq_f32_s32(zf); // reconstruct w as a square root (unscaled); we clamp to 0.f to avoid NaN due to precision errors float32x4_t ws = vmulq_f32(s, s); float32x4_t ww = vsubq_f32(vaddq_f32(ws, ws), vfmaq_f32(vfmaq_f32(vmulq_f32(x, x), y, y), z, z)); float32x4_t w = vsqrtq_f32(vmaxq_f32(ww, vdupq_n_f32(0.f))); // compute final scale; note that all computations above are unscaled // we need to divide by sf to get out of fixed point, divide by sqrt(2) to renormalize and multiply by 32767 to get to int16 range float32x4_t ss = vdivq_f32(vdupq_n_f32(scale), s); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const float32x4_t fsnap = vdupq_n_f32(3 << 22); int32x4_t xr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, x, ss)); int32x4_t yr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, y, ss)); int32x4_t zr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, z, ss)); int32x4_t wr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, w, ss)); // mix x/z and w/y to make 16-bit unpack easier int32x4_t xzr = vsliq_n_s32(xr, zr, 16); int32x4_t wyr = vsliq_n_s32(wr, yr, 16); // pack x/y/z/w using 16-bit unpacks; we pack wxyz by default (for qc=0) uint64x2_t res_0 = vreinterpretq_u64_s16(vzipq_s16(vreinterpretq_s16_s32(wyr), vreinterpretq_s16_s32(xzr)).val[0]); uint64x2_t res_1 = vreinterpretq_u64_s16(vzipq_s16(vreinterpretq_s16_s32(wyr), vreinterpretq_s16_s32(xzr)).val[1]); // store results to stack so that we can rotate using scalar instructions // TODO: volatile works around LLVM mis-optimizing code; https://github.com/llvm/llvm-project/issues/166808 volatile uint64_t res[4]; vst1q_u64(const_cast<uint64_t*>(&res[0]), res_0); vst1q_u64(const_cast<uint64_t*>(&res[2]), res_1); // rotate and store uint64_t* out = reinterpret_cast<uint64_t*>(&data[i * 4]); out[0] = rotateleft64(res[0], data[(i + 0) * 4 + 3] << 4); out[1] = rotateleft64(res[1], data[(i + 1) * 4 + 3] << 4); out[2] = rotateleft64(res[2], data[(i + 2) * 4 + 3] << 4); out[3] = rotateleft64(res[3], data[(i + 3) * 4 + 3] << 4); } } static void decodeFilterExpSimd(unsigned int* data, size_t count) { for (size_t i = 0; i < count; i += 4) { int32x4_t v = vld1q_s32(reinterpret_cast<int32_t*>(&data[i])); // decode exponent into 2^x directly int32x4_t ef = vshrq_n_s32(v, 24); int32x4_t es = vshlq_n_s32(vaddq_s32(ef, vdupq_n_s32(127)), 23); // decode 24-bit mantissa into floating-point value int32x4_t mf = vshrq_n_s32(vshlq_n_s32(v, 8), 8); float32x4_t m = vcvtq_f32_s32(mf); float32x4_t r = vmulq_f32(vreinterpretq_f32_s32(es), m); vst1q_f32(reinterpret_cast<float*>(&data[i]), r); } } static void decodeFilterColorSimd8(unsigned char* data, size_t count) { for (size_t i = 0; i < count; i += 4) { int32x4_t c4 = vld1q_s32(reinterpret_cast<int32_t*>(&data[i * 4])); // unpack y/co/cg/a (co/cg are sign extended with arithmetic shifts) int32x4_t yf = vandq_s32(c4, vdupq_n_s32(0xff)); int32x4_t cof = vshrq_n_s32(vshlq_n_s32(c4, 16), 24); int32x4_t cgf = vshrq_n_s32(vshlq_n_s32(c4, 8), 24); int32x4_t af = vreinterpretq_s32_u32(vshrq_n_u32(vreinterpretq_u32_s32(c4), 24)); // recover scale from alpha high bit int32x4_t as = af; as = vorrq_s32(as, vshrq_n_s32(as, 1)); as = vorrq_s32(as, vshrq_n_s32(as, 2)); as = vorrq_s32(as, vshrq_n_s32(as, 4)); // expand alpha by one bit to match other components af = vorrq_s32(vandq_s32(vshlq_n_s32(af, 1), as), vandq_s32(af, vdupq_n_s32(1))); // compute scaling factor float32x4_t ss = vmulq_f32(vdupq_n_f32(255.f), vrecpeq_f32(vcvtq_f32_s32(as))); // convert to RGB in fixed point int32x4_t rf = vaddq_s32(yf, vsubq_s32(cof, cgf)); int32x4_t gf = vaddq_s32(yf, cgf); int32x4_t bf = vsubq_s32(yf, vaddq_s32(cof, cgf)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 8 bits so we can omit the subtraction const float32x4_t fsnap = vdupq_n_f32(3 << 22); int32x4_t rr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(rf), ss)); int32x4_t gr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(gf), ss)); int32x4_t br = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(bf), ss)); int32x4_t ar = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(af), ss)); // repack rgba into final value int32x4_t res = vsliq_n_s32(rr, vsliq_n_s32(gr, vsliq_n_s32(br, ar, 8), 8), 8); vst1q_s32(reinterpret_cast<int32_t*>(&data[i * 4]), res); } } static void decodeFilterColorSimd16(unsigned short* data, size_t count) { for (size_t i = 0; i < count; i += 4) { int32x4_t c4_0 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 0) * 4])); int32x4_t c4_1 = vld1q_s32(reinterpret_cast<int32_t*>(&data[(i + 2) * 4])); // gather both y/co 16-bit pairs in each 32-bit lane int32x4_t c4_yco = vuzpq_s32(c4_0, c4_1).val[0]; int32x4_t c4_cga = vuzpq_s32(c4_0, c4_1).val[1]; // unpack y/co/cg/a components (co/cg are sign extended with arithmetic shifts) int32x4_t yf = vandq_s32(c4_yco, vdupq_n_s32(0xffff)); int32x4_t cof = vshrq_n_s32(c4_yco, 16); int32x4_t cgf = vshrq_n_s32(vshlq_n_s32(c4_cga, 16), 16); int32x4_t af = vreinterpretq_s32_u32(vshrq_n_u32(vreinterpretq_u32_s32(c4_cga), 16)); // recover scale from alpha high bit int32x4_t as = af; as = vorrq_s32(as, vshrq_n_s32(as, 1)); as = vorrq_s32(as, vshrq_n_s32(as, 2)); as = vorrq_s32(as, vshrq_n_s32(as, 4)); as = vorrq_s32(as, vshrq_n_s32(as, 8)); // expand alpha by one bit to match other components af = vorrq_s32(vandq_s32(vshlq_n_s32(af, 1), as), vandq_s32(af, vdupq_n_s32(1))); // compute scaling factor float32x4_t ss = vdivq_f32(vdupq_n_f32(65535.f), vcvtq_f32_s32(as)); // convert to RGB in fixed point int32x4_t rf = vaddq_s32(yf, vsubq_s32(cof, cgf)); int32x4_t gf = vaddq_s32(yf, cgf); int32x4_t bf = vsubq_s32(yf, vaddq_s32(cof, cgf)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const float32x4_t fsnap = vdupq_n_f32(3 << 22); int32x4_t rr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(rf), ss)); int32x4_t gr = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(gf), ss)); int32x4_t br = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(bf), ss)); int32x4_t ar = vreinterpretq_s32_f32(vfmaq_f32(fsnap, vcvtq_f32_s32(af), ss)); // mix r/b and g/a to make 16-bit unpack easier int32x4_t rbr = vsliq_n_s32(rr, br, 16); int32x4_t gar = vsliq_n_s32(gr, ar, 16); // pack r/g/b/a using 16-bit unpacks int32x4_t res_0 = vreinterpretq_s32_s16(vzipq_s16(vreinterpretq_s16_s32(rbr), vreinterpretq_s16_s32(gar)).val[0]); int32x4_t res_1 = vreinterpretq_s32_s16(vzipq_s16(vreinterpretq_s16_s32(rbr), vreinterpretq_s16_s32(gar)).val[1]); vst1q_s32(reinterpret_cast<int32_t*>(&data[(i + 0) * 4]), res_0); vst1q_s32(reinterpret_cast<int32_t*>(&data[(i + 2) * 4]), res_1); } } #endif #ifdef SIMD_WASM static void decodeFilterOctSimd8(signed char* data, size_t count) { const v128_t sign = wasm_f32x4_splat(-0.f); for (size_t i = 0; i < count; i += 4) { v128_t n4 = wasm_v128_load(&data[i * 4]); // sign-extends each of x,y in [x y ? ?] with arithmetic shifts v128_t xf = wasm_i32x4_shr(wasm_i32x4_shl(n4, 24), 24); v128_t yf = wasm_i32x4_shr(wasm_i32x4_shl(n4, 16), 24); // unpack z; note that z is unsigned so we technically don't need to sign extend it v128_t zf = wasm_i32x4_shr(wasm_i32x4_shl(n4, 8), 24); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count v128_t x = wasm_f32x4_convert_i32x4(xf); v128_t y = wasm_f32x4_convert_i32x4(yf); v128_t z = wasm_f32x4_sub(wasm_f32x4_convert_i32x4(zf), wasm_f32x4_add(wasm_f32x4_abs(x), wasm_f32x4_abs(y))); // fixup octahedral coordinates for z<0 // note: i32x4_min with 0 is equvalent to f32x4_min v128_t t = wasm_i32x4_min(z, wasm_i32x4_splat(0)); x = wasm_f32x4_add(x, wasm_v128_xor(t, wasm_v128_and(x, sign))); y = wasm_f32x4_add(y, wasm_v128_xor(t, wasm_v128_and(y, sign))); // compute normal length & scale v128_t ll = wasm_f32x4_add(wasm_f32x4_mul(x, x), wasm_f32x4_add(wasm_f32x4_mul(y, y), wasm_f32x4_mul(z, z))); v128_t s = wasm_f32x4_div(wasm_f32x4_splat(127.f), wasm_f32x4_sqrt(ll)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 8 bits so we can omit the subtraction const v128_t fsnap = wasm_f32x4_splat(3 << 22); v128_t xr = wasm_f32x4_add(wasm_f32x4_mul(x, s), fsnap); v128_t yr = wasm_f32x4_add(wasm_f32x4_mul(y, s), fsnap); v128_t zr = wasm_f32x4_add(wasm_f32x4_mul(z, s), fsnap); // combine xr/yr/zr into final value v128_t res = wasm_v128_and(n4, wasm_i32x4_splat(0xff000000)); res = wasm_v128_or(res, wasm_v128_and(xr, wasm_i32x4_splat(0xff))); res = wasm_v128_or(res, wasm_i32x4_shl(wasm_v128_and(yr, wasm_i32x4_splat(0xff)), 8)); res = wasm_v128_or(res, wasm_i32x4_shl(wasm_v128_and(zr, wasm_i32x4_splat(0xff)), 16)); wasm_v128_store(&data[i * 4], res); } } static void decodeFilterOctSimd16(short* data, size_t count) { const v128_t sign = wasm_f32x4_splat(-0.f); // TODO: volatile here works around LLVM mis-optimizing code; https://github.com/llvm/llvm-project/issues/149457 volatile v128_t zmask = wasm_i32x4_splat(0x7fff); for (size_t i = 0; i < count; i += 4) { v128_t n4_0 = wasm_v128_load(&data[(i + 0) * 4]); v128_t n4_1 = wasm_v128_load(&data[(i + 2) * 4]); // gather both x/y 16-bit pairs in each 32-bit lane v128_t n4 = wasmx_unziplo_v32x4(n4_0, n4_1); // sign-extends each of x,y in [x y] with arithmetic shifts v128_t xf = wasm_i32x4_shr(wasm_i32x4_shl(n4, 16), 16); v128_t yf = wasm_i32x4_shr(n4, 16); // unpack z; note that z is unsigned so we don't need to sign extend it v128_t z4 = wasmx_unziphi_v32x4(n4_0, n4_1); v128_t zf = wasm_v128_and(z4, zmask); // convert x and y to floats and reconstruct z; this assumes zf encodes 1.f at the same bit count v128_t x = wasm_f32x4_convert_i32x4(xf); v128_t y = wasm_f32x4_convert_i32x4(yf); v128_t z = wasm_f32x4_sub(wasm_f32x4_convert_i32x4(zf), wasm_f32x4_add(wasm_f32x4_abs(x), wasm_f32x4_abs(y))); // fixup octahedral coordinates for z<0 // note: i32x4_min with 0 is equvalent to f32x4_min v128_t t = wasm_i32x4_min(z, wasm_i32x4_splat(0)); x = wasm_f32x4_add(x, wasm_v128_xor(t, wasm_v128_and(x, sign))); y = wasm_f32x4_add(y, wasm_v128_xor(t, wasm_v128_and(y, sign))); // compute normal length & scale v128_t ll = wasm_f32x4_add(wasm_f32x4_mul(x, x), wasm_f32x4_add(wasm_f32x4_mul(y, y), wasm_f32x4_mul(z, z))); v128_t s = wasm_f32x4_div(wasm_f32x4_splat(32767.f), wasm_f32x4_sqrt(ll)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const v128_t fsnap = wasm_f32x4_splat(3 << 22); v128_t xr = wasm_f32x4_add(wasm_f32x4_mul(x, s), fsnap); v128_t yr = wasm_f32x4_add(wasm_f32x4_mul(y, s), fsnap); v128_t zr = wasm_f32x4_add(wasm_f32x4_mul(z, s), fsnap); // mix x/z and y/0 to make 16-bit unpack easier v128_t xzr = wasm_v128_or(wasm_v128_and(xr, wasm_i32x4_splat(0xffff)), wasm_i32x4_shl(zr, 16)); v128_t y0r = wasm_v128_and(yr, wasm_i32x4_splat(0xffff)); // pack x/y/z using 16-bit unpacks; note that this has 0 where we should have .w v128_t res_0 = wasmx_unpacklo_v16x8(xzr, y0r); v128_t res_1 = wasmx_unpackhi_v16x8(xzr, y0r); // patch in .w res_0 = wasm_v128_or(res_0, wasm_v128_and(n4_0, wasm_i64x2_splat(0xffff000000000000))); res_1 = wasm_v128_or(res_1, wasm_v128_and(n4_1, wasm_i64x2_splat(0xffff000000000000))); wasm_v128_store(&data[(i + 0) * 4], res_0); wasm_v128_store(&data[(i + 2) * 4], res_1); } } static void decodeFilterQuatSimd(short* data, size_t count) { const float scale = 32767.f / sqrtf(2.f); for (size_t i = 0; i < count; i += 4) { v128_t q4_0 = wasm_v128_load(&data[(i + 0) * 4]); v128_t q4_1 = wasm_v128_load(&data[(i + 2) * 4]); // gather both x/y 16-bit pairs in each 32-bit lane v128_t q4_xy = wasmx_unziplo_v32x4(q4_0, q4_1); v128_t q4_zc = wasmx_unziphi_v32x4(q4_0, q4_1); // sign-extends each of x,y in [x y] with arithmetic shifts v128_t xf = wasm_i32x4_shr(wasm_i32x4_shl(q4_xy, 16), 16); v128_t yf = wasm_i32x4_shr(q4_xy, 16); v128_t zf = wasm_i32x4_shr(wasm_i32x4_shl(q4_zc, 16), 16); v128_t cf = wasm_i32x4_shr(q4_zc, 16); // get a floating-point scaler using zc with bottom 2 bits set to 1 (which represents 1.f) v128_t sf = wasm_v128_or(cf, wasm_i32x4_splat(3)); v128_t s = wasm_f32x4_convert_i32x4(sf); // convert x/y/z to floating point (unscaled! implied scale of 1/sqrt(2.f) * 1/sf) v128_t x = wasm_f32x4_convert_i32x4(xf); v128_t y = wasm_f32x4_convert_i32x4(yf); v128_t z = wasm_f32x4_convert_i32x4(zf); // reconstruct w as a square root (unscaled); we clamp to 0.f to avoid NaN due to precision errors // note: i32x4_max with 0 is equivalent to f32x4_max v128_t ws = wasm_f32x4_mul(s, s); v128_t ww = wasm_f32x4_sub(wasm_f32x4_add(ws, ws), wasm_f32x4_add(wasm_f32x4_mul(x, x), wasm_f32x4_add(wasm_f32x4_mul(y, y), wasm_f32x4_mul(z, z)))); v128_t w = wasm_f32x4_sqrt(wasm_i32x4_max(ww, wasm_i32x4_splat(0))); // compute final scale; note that all computations above are unscaled // we need to divide by sf to get out of fixed point, divide by sqrt(2) to renormalize and multiply by 32767 to get to int16 range v128_t ss = wasm_f32x4_div(wasm_f32x4_splat(scale), s); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const v128_t fsnap = wasm_f32x4_splat(3 << 22); v128_t xr = wasm_f32x4_add(wasm_f32x4_mul(x, ss), fsnap); v128_t yr = wasm_f32x4_add(wasm_f32x4_mul(y, ss), fsnap); v128_t zr = wasm_f32x4_add(wasm_f32x4_mul(z, ss), fsnap); v128_t wr = wasm_f32x4_add(wasm_f32x4_mul(w, ss), fsnap); // mix x/z and w/y to make 16-bit unpack easier v128_t xzr = wasm_v128_or(wasm_v128_and(xr, wasm_i32x4_splat(0xffff)), wasm_i32x4_shl(zr, 16)); v128_t wyr = wasm_v128_or(wasm_v128_and(wr, wasm_i32x4_splat(0xffff)), wasm_i32x4_shl(yr, 16)); // pack x/y/z/w using 16-bit unpacks; we pack wxyz by default (for qc=0) v128_t res_0 = wasmx_unpacklo_v16x8(wyr, xzr); v128_t res_1 = wasmx_unpackhi_v16x8(wyr, xzr); // compute component index shifted left by 4 (and moved into i32x4 slot) v128_t cm = wasm_i32x4_shl(cf, 4); // rotate and store uint64_t* out = reinterpret_cast<uint64_t*>(&data[i * 4]); out[0] = rotateleft64(wasm_i64x2_extract_lane(res_0, 0), wasm_i32x4_extract_lane(cm, 0)); out[1] = rotateleft64(wasm_i64x2_extract_lane(res_0, 1), wasm_i32x4_extract_lane(cm, 1)); out[2] = rotateleft64(wasm_i64x2_extract_lane(res_1, 0), wasm_i32x4_extract_lane(cm, 2)); out[3] = rotateleft64(wasm_i64x2_extract_lane(res_1, 1), wasm_i32x4_extract_lane(cm, 3)); } } static void decodeFilterExpSimd(unsigned int* data, size_t count) { for (size_t i = 0; i < count; i += 4) { v128_t v = wasm_v128_load(&data[i]); // decode exponent into 2^x directly v128_t ef = wasm_i32x4_shr(v, 24); v128_t es = wasm_i32x4_shl(wasm_i32x4_add(ef, wasm_i32x4_splat(127)), 23); // decode 24-bit mantissa into floating-point value v128_t mf = wasm_i32x4_shr(wasm_i32x4_shl(v, 8), 8); v128_t m = wasm_f32x4_convert_i32x4(mf); v128_t r = wasm_f32x4_mul(es, m); wasm_v128_store(&data[i], r); } } static void decodeFilterColorSimd8(unsigned char* data, size_t count) { // TODO: volatile here works around LLVM mis-optimizing code; https://github.com/llvm/llvm-project/issues/149457 volatile v128_t zero = wasm_i32x4_splat(0); for (size_t i = 0; i < count; i += 4) { v128_t c4 = wasm_v128_load(&data[i * 4]); // unpack y/co/cg/a (co/cg are sign extended with arithmetic shifts) v128_t yf = wasm_v128_and(c4, wasm_i32x4_splat(0xff)); v128_t cof = wasm_i32x4_shr(wasm_i32x4_shl(c4, 16), 24); v128_t cgf = wasm_i32x4_shr(wasm_i32x4_shl(c4, 8), 24); v128_t af = wasm_v128_or(zero, wasm_u32x4_shr(c4, 24)); // recover scale from alpha high bit v128_t as = af; as = wasm_v128_or(as, wasm_i32x4_shr(as, 1)); as = wasm_v128_or(as, wasm_i32x4_shr(as, 2)); as = wasm_v128_or(as, wasm_i32x4_shr(as, 4)); // expand alpha by one bit to match other components af = wasm_v128_or(wasm_v128_and(wasm_i32x4_shl(af, 1), as), wasm_v128_and(af, wasm_i32x4_splat(1))); // compute scaling factor v128_t ss = wasm_f32x4_div(wasm_f32x4_splat(255.f), wasm_f32x4_convert_i32x4(as)); // convert to RGB in fixed point v128_t rf = wasm_i32x4_add(yf, wasm_i32x4_sub(cof, cgf)); v128_t gf = wasm_i32x4_add(yf, cgf); v128_t bf = wasm_i32x4_sub(yf, wasm_i32x4_add(cof, cgf)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 8 bits so we can omit the subtraction const v128_t fsnap = wasm_f32x4_splat(3 << 22); v128_t rr = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(rf), ss), fsnap); v128_t gr = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(gf), ss), fsnap); v128_t br = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(bf), ss), fsnap); v128_t ar = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(af), ss), fsnap); // repack rgba into final value v128_t res = wasm_v128_and(rr, wasm_i32x4_splat(0xff)); res = wasm_v128_or(res, wasm_i32x4_shl(wasm_v128_and(gr, wasm_i32x4_splat(0xff)), 8)); res = wasm_v128_or(res, wasm_i32x4_shl(wasm_v128_and(br, wasm_i32x4_splat(0xff)), 16)); res = wasm_v128_or(res, wasm_i32x4_shl(ar, 24)); wasm_v128_store(&data[i * 4], res); } } static void decodeFilterColorSimd16(unsigned short* data, size_t count) { // TODO: volatile here works around LLVM mis-optimizing code; https://github.com/llvm/llvm-project/issues/149457 volatile v128_t zero = wasm_i32x4_splat(0); for (size_t i = 0; i < count; i += 4) { v128_t c4_0 = wasm_v128_load(&data[(i + 0) * 4]); v128_t c4_1 = wasm_v128_load(&data[(i + 2) * 4]); // gather both y/co 16-bit pairs in each 32-bit lane v128_t c4_yco = wasmx_unziplo_v32x4(c4_0, c4_1); v128_t c4_cga = wasmx_unziphi_v32x4(c4_0, c4_1); // unpack y/co/cg/a components (co/cg are sign extended with arithmetic shifts) v128_t yf = wasm_v128_and(c4_yco, wasm_i32x4_splat(0xffff)); v128_t cof = wasm_i32x4_shr(c4_yco, 16); v128_t cgf = wasm_i32x4_shr(wasm_i32x4_shl(c4_cga, 16), 16); v128_t af = wasm_v128_or(zero, wasm_u32x4_shr(c4_cga, 16)); // recover scale from alpha high bit v128_t as = af; as = wasm_v128_or(as, wasm_i32x4_shr(as, 1)); as = wasm_v128_or(as, wasm_i32x4_shr(as, 2)); as = wasm_v128_or(as, wasm_i32x4_shr(as, 4)); as = wasm_v128_or(as, wasm_i32x4_shr(as, 8)); // expand alpha by one bit to match other components af = wasm_v128_or(wasm_v128_and(wasm_i32x4_shl(af, 1), as), wasm_v128_and(af, wasm_i32x4_splat(1))); // compute scaling factor v128_t ss = wasm_f32x4_div(wasm_f32x4_splat(65535.f), wasm_f32x4_convert_i32x4(as)); // convert to RGB in fixed point v128_t rf = wasm_i32x4_add(yf, wasm_i32x4_sub(cof, cgf)); v128_t gf = wasm_i32x4_add(yf, cgf); v128_t bf = wasm_i32x4_sub(yf, wasm_i32x4_add(cof, cgf)); // fast rounded signed float->int: addition triggers renormalization after which mantissa stores the integer value // note: the result is offset by 0x4B40_0000, but we only need the low 16 bits so we can omit the subtraction const v128_t fsnap = wasm_f32x4_splat(3 << 22); v128_t rr = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(rf), ss), fsnap); v128_t gr = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(gf), ss), fsnap); v128_t br = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(bf), ss), fsnap); v128_t ar = wasm_f32x4_add(wasm_f32x4_mul(wasm_f32x4_convert_i32x4(af), ss), fsnap); // mix r/b and g/a to make 16-bit unpack easier v128_t rbr = wasm_v128_or(wasm_v128_and(rr, wasm_i32x4_splat(0xffff)), wasm_i32x4_shl(br, 16)); v128_t gar = wasm_v128_or(wasm_v128_and(gr, wasm_i32x4_splat(0xffff)), wasm_i32x4_shl(ar, 16)); // pack r/g/b/a using 16-bit unpacks v128_t res_0 = wasmx_unpacklo_v16x8(rbr, gar); v128_t res_1 = wasmx_unpackhi_v16x8(rbr, gar); wasm_v128_store(&data[(i + 0) * 4], res_0); wasm_v128_store(&data[(i + 2) * 4], res_1); } } #endif // optimized variant of frexp inline int optlog2(float v) { union { float f; unsigned int ui; } u; u.f = v; // +1 accounts for implicit 1. in mantissa; denormalized numbers will end up clamped to min_exp by calling code return v == 0 ? 0 : int((u.ui >> 23) & 0xff) - 127 + 1; } // optimized variant of ldexp inline float optexp2(int e) { union { float f; unsigned int ui; } u; u.ui = unsigned(e + 127) << 23; return u.f; } } // namespace meshopt void meshopt_decodeFilterOct(void* buffer, size_t count, size_t stride) { using namespace meshopt; assert(stride == 4 || stride == 8); #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) if (stride == 4) dispatchSimd(decodeFilterOctSimd8, static_cast<signed char*>(buffer), count, 4); else dispatchSimd(decodeFilterOctSimd16, static_cast<short*>(buffer), count, 4); #else if (stride == 4) decodeFilterOct(static_cast<signed char*>(buffer), count); else decodeFilterOct(static_cast<short*>(buffer), count); #endif } void meshopt_decodeFilterQuat(void* buffer, size_t count, size_t stride) { using namespace meshopt; assert(stride == 8); (void)stride; #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) dispatchSimd(decodeFilterQuatSimd, static_cast<short*>(buffer), count, 4); #else decodeFilterQuat(static_cast<short*>(buffer), count); #endif } void meshopt_decodeFilterExp(void* buffer, size_t count, size_t stride) { using namespace meshopt; assert(stride > 0 && stride % 4 == 0); #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) dispatchSimd(decodeFilterExpSimd, static_cast<unsigned int*>(buffer), count * (stride / 4), 1); #else decodeFilterExp(static_cast<unsigned int*>(buffer), count * (stride / 4)); #endif } void meshopt_decodeFilterColor(void* buffer, size_t count, size_t stride) { using namespace meshopt; assert(stride == 4 || stride == 8); #if defined(SIMD_SSE) || defined(SIMD_NEON) || defined(SIMD_WASM) if (stride == 4) dispatchSimd(decodeFilterColorSimd8, static_cast<unsigned char*>(buffer), count, 4); else dispatchSimd(decodeFilterColorSimd16, static_cast<unsigned short*>(buffer), count, 4); #else if (stride == 4) decodeFilterColor<signed char>(static_cast<unsigned char*>(buffer), count); else decodeFilterColor<short>(static_cast<unsigned short*>(buffer), count); #endif } void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data) { assert(stride == 4 || stride == 8); assert(bits >= 2 && bits <= 16); signed char* d8 = static_cast<signed char*>(destination); short* d16 = static_cast<short*>(destination); int bytebits = int(stride * 2); for (size_t i = 0; i < count; ++i) { const float* n = &data[i * 4]; // octahedral encoding of a unit vector float nx = n[0], ny = n[1], nz = n[2], nw = n[3]; float nl = fabsf(nx) + fabsf(ny) + fabsf(nz); float ns = nl == 0.f ? 0.f : 1.f / nl; nx *= ns; ny *= ns; float u = (nz >= 0.f) ? nx : (1 - fabsf(ny)) * (nx >= 0.f ? 1.f : -1.f); float v = (nz >= 0.f) ? ny : (1 - fabsf(nx)) * (ny >= 0.f ? 1.f : -1.f); int fu = meshopt_quantizeSnorm(u, bits); int fv = meshopt_quantizeSnorm(v, bits); int fo = meshopt_quantizeSnorm(1.f, bits); int fw = meshopt_quantizeSnorm(nw, bytebits); if (stride == 4) { d8[i * 4 + 0] = (signed char)(fu); d8[i * 4 + 1] = (signed char)(fv); d8[i * 4 + 2] = (signed char)(fo); d8[i * 4 + 3] = (signed char)(fw); } else { d16[i * 4 + 0] = short(fu); d16[i * 4 + 1] = short(fv); d16[i * 4 + 2] = short(fo); d16[i * 4 + 3] = short(fw); } } } void meshopt_encodeFilterQuat(void* destination_, size_t count, size_t stride, int bits, const float* data) { assert(stride == 8); assert(bits >= 4 && bits <= 16); (void)stride; short* destination = static_cast<short*>(destination_); const float scaler = sqrtf(2.f); for (size_t i = 0; i < count; ++i) { const float* q = &data[i * 4]; short* d = &destination[i * 4]; // establish maximum quaternion component int qc = 0; qc = fabsf(q[1]) > fabsf(q[qc]) ? 1 : qc; qc = fabsf(q[2]) > fabsf(q[qc]) ? 2 : qc; qc = fabsf(q[3]) > fabsf(q[qc]) ? 3 : qc; // we use double-cover properties to discard the sign float sign = q[qc] < 0.f ? -1.f : 1.f; // note: we always encode a cyclical swizzle to be able to recover the order via rotation d[0] = short(meshopt_quantizeSnorm(q[(qc + 1) & 3] * scaler * sign, bits)); d[1] = short(meshopt_quantizeSnorm(q[(qc + 2) & 3] * scaler * sign, bits)); d[2] = short(meshopt_quantizeSnorm(q[(qc + 3) & 3] * scaler * sign, bits)); d[3] = short((meshopt_quantizeSnorm(1.f, bits) & ~3) | qc); } } void meshopt_encodeFilterExp(void* destination_, size_t count, size_t stride, int bits, const float* data, enum meshopt_EncodeExpMode mode) { using namespace meshopt; assert(stride > 0 && stride % 4 == 0 && stride <= 256); assert(bits >= 1 && bits <= 24); unsigned int* destination = static_cast<unsigned int*>(destination_); size_t stride_float = stride / sizeof(float); int component_exp[64]; assert(stride_float <= sizeof(component_exp) / sizeof(int)); const int min_exp = -100; if (mode == meshopt_EncodeExpSharedComponent) { for (size_t j = 0; j < stride_float; ++j) component_exp[j] = min_exp; for (size_t i = 0; i < count; ++i) { const float* v = &data[i * stride_float]; // use maximum exponent to encode values; this guarantees that mantissa is [-1, 1] for (size_t j = 0; j < stride_float; ++j) { int e = optlog2(v[j]); component_exp[j] = (component_exp[j] < e) ? e : component_exp[j]; } } } for (size_t i = 0; i < count; ++i) { const float* v = &data[i * stride_float]; unsigned int* d = &destination[i * stride_float]; int vector_exp = min_exp; if (mode == meshopt_EncodeExpSharedVector) { // use maximum exponent to encode values; this guarantees that mantissa is [-1, 1] for (size_t j = 0; j < stride_float; ++j) { int e = optlog2(v[j]); vector_exp = (vector_exp < e) ? e : vector_exp; } } else if (mode == meshopt_EncodeExpSeparate) { for (size_t j = 0; j < stride_float; ++j) { int e = optlog2(v[j]); component_exp[j] = (min_exp < e) ? e : min_exp; } } else if (mode == meshopt_EncodeExpClamped) { for (size_t j = 0; j < stride_float; ++j) { int e = optlog2(v[j]); component_exp[j] = (0 < e) ? e : 0; } } else { // the code below assumes component_exp is initialized outside of the loop assert(mode == meshopt_EncodeExpSharedComponent); } for (size_t j = 0; j < stride_float; ++j) { int exp = (mode == meshopt_EncodeExpSharedVector) ? vector_exp : component_exp[j]; // note that we additionally scale the mantissa to make it a K-bit signed integer (K-1 bits for magnitude) exp -= (bits - 1); // compute renormalized rounded mantissa for each component int mmask = (1 << 24) - 1; int m = int(v[j] * optexp2(-exp) + (v[j] >= 0 ? 0.5f : -0.5f)); d[j] = (m & mmask) | (unsigned(exp) << 24); } } } void meshopt_encodeFilterColor(void* destination, size_t count, size_t stride, int bits, const float* data) { assert(stride == 4 || stride == 8); assert(bits >= 2 && bits <= 16); unsigned char* d8 = static_cast<unsigned char*>(destination); unsigned short* d16 = static_cast<unsigned short*>(destination); for (size_t i = 0; i < count; ++i) { const float* c = &data[i * 4]; int fr = meshopt_quantizeUnorm(c[0], bits); int fg = meshopt_quantizeUnorm(c[1], bits); int fb = meshopt_quantizeUnorm(c[2], bits); // YCoCg-R encoding with truncated Co/Cg ensures that decoding can be done using integers int fco = (fr - fb) / 2; int tmp = fb + fco; int fcg = (fg - tmp) / 2; int fy = tmp + fcg; // validate that R/G/B can be reconstructed with K bit integers assert(unsigned((fy + fco - fcg) | (fy + fcg) | (fy - fco - fcg)) < (1u << bits)); // alpha: K-1-bit encoding with high bit set to 1 int fa = (meshopt_quantizeUnorm(c[3], bits) >> 1) | (1 << (bits - 1)); if (stride == 4) { d8[i * 4 + 0] = (unsigned char)(fy); d8[i * 4 + 1] = (unsigned char)(fco); d8[i * 4 + 2] = (unsigned char)(fcg); d8[i * 4 + 3] = (unsigned char)(fa); } else { d16[i * 4 + 0] = (unsigned short)(fy); d16[i * 4 + 1] = (unsigned short)(fco); d16[i * 4 + 2] = (unsigned short)(fcg); d16[i * 4 + 3] = (unsigned short)(fa); } } } #undef SIMD_SSE #undef SIMD_NEON #undef SIMD_WASM
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/vfetchoptimizer.cpp
C++
// This file is part of meshoptimizer library; see meshoptimizer.h for version/license details #include "meshoptimizer.h" #include <assert.h> #include <string.h> size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count) { assert(index_count % 3 == 0); memset(destination, -1, vertex_count * sizeof(unsigned int)); unsigned int next_vertex = 0; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); if (destination[index] == ~0u) { destination[index] = next_vertex++; } } assert(next_vertex <= vertex_count); return next_vertex; } size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size) { assert(index_count % 3 == 0); assert(vertex_size > 0 && vertex_size <= 256); meshopt_Allocator allocator; // support in-place optimization if (destination == vertices) { unsigned char* vertices_copy = allocator.allocate<unsigned char>(vertex_count * vertex_size); memcpy(vertices_copy, vertices, vertex_count * vertex_size); vertices = vertices_copy; } // build vertex remap table unsigned int* vertex_remap = allocator.allocate<unsigned int>(vertex_count); memset(vertex_remap, -1, vertex_count * sizeof(unsigned int)); unsigned int next_vertex = 0; for (size_t i = 0; i < index_count; ++i) { unsigned int index = indices[i]; assert(index < vertex_count); unsigned int& remap = vertex_remap[index]; if (remap == ~0u) // vertex was not added to destination VB { // add vertex memcpy(static_cast<unsigned char*>(destination) + next_vertex * vertex_size, static_cast<const unsigned char*>(vertices) + index * vertex_size, vertex_size); remap = next_vertex++; } // modify indices in place indices[i] = remap; } assert(next_vertex <= vertex_count); return next_vertex; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/bitmask.py
Python
#!/usr/bin/python3 from z3 import * def same8(v): return Or(v == 0, v == 0xff) magic = BitVec('magic', 64) x = BitVec('x', 64) y = x * magic s = Solver() solve_using(s, ForAll([x], Or( Not(And([same8((x >> (i * 8)) & 0xff) for i in range(8)])), # x has bytes that aren't equal to 0xff or 0x00 And([(x >> (i * 8 + 7)) & 1 == (y >> (56 + i)) & 1 for i in range(8)]) # every byte of x has bits that are equal to a corresponding top bit of y ))) print("magic =", hex(s.model().eval(magic).as_long()))
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/clusterfuzz.cpp
C++
#include "../src/meshoptimizer.h" #include <float.h> #include <stdint.h> #include <stdlib.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* buffer, size_t size) { if (size == 0) return 0; srand(buffer[0]); float vb[100][4]; for (int i = 0; i < 100; ++i) { vb[i][0] = rand() % 10; vb[i][1] = rand() % 10; vb[i][2] = rand() % 10; vb[i][3] = rand() % 10; } unsigned int ib[999]; int indices = (size - 1) < 999 ? (size - 1) / 3 * 3 : 999; for (int i = 0; i < indices; ++i) ib[i] = buffer[1 + i] % 100; meshopt_Meshlet ml[333]; unsigned int mv[333 * 3]; unsigned char mt[333 * 4]; meshopt_buildMeshlets(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 4, /* max_triangles= */ 4, 0.f); meshopt_buildMeshletsScan(ml, mv, mt, ib, indices, 100, /* max_vertices= */ 4, /* max_triangles= */ 4); meshopt_buildMeshletsScan(ml, mv, mt, ib, indices, 100, /* max_vertices= */ 4, /* max_triangles= */ 8); meshopt_buildMeshletsFlex(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 4, /* min_triangles= */ 4, /* max_triangles= */ 8, 0.f, 2.f); meshopt_buildMeshletsFlex(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 8, /* min_triangles= */ 8, /* max_triangles= */ 16, 0.f, 2.f); meshopt_buildMeshletsFlex(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 16, /* min_triangles= */ 8, /* max_triangles= */ 32, 0.f, 2.f); meshopt_buildMeshletsFlex(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 16, /* min_triangles= */ 16, /* max_triangles= */ 32, 0.f, 2.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 4, /* min_triangles= */ 4, /* max_triangles= */ 8, 0.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 8, /* min_triangles= */ 4, /* max_triangles= */ 32, 0.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 8, /* min_triangles= */ 8, /* max_triangles= */ 32, 0.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 8, /* min_triangles= */ 12, /* max_triangles= */ 32, 0.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 16, /* min_triangles= */ 16, /* max_triangles= */ 32, 0.f); meshopt_buildMeshletsSpatial(ml, mv, mt, ib, indices, vb[0], 100, sizeof(float) * 4, /* max_vertices= */ 16, /* min_triangles= */ 32, /* max_triangles= */ 32, 0.f); unsigned int part[333]; unsigned int clsize[333]; // treat each triangle as a cluster for (int i = 0; i < indices; ++i) clsize[i / 3] = 3; meshopt_partitionClusters(part, ib, indices, clsize, indices / 3, vb[0], 100, sizeof(float) * 4, /* target_group_size= */ 12); return 0; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/codecbench.cpp
C++
#include "../src/meshoptimizer.h" #include <algorithm> #include <vector> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> #ifdef __EMSCRIPTEN__ #include <emscripten.h> double timestamp() { return emscripten_get_now() * 1e-3; } #elif defined(_WIN32) struct LARGE_INTEGER { __int64 QuadPart; }; extern "C" __declspec(dllimport) int __stdcall QueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount); extern "C" __declspec(dllimport) int __stdcall QueryPerformanceFrequency(LARGE_INTEGER* lpFrequency); double timestamp() { LARGE_INTEGER freq, counter; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&counter); return double(counter.QuadPart) / double(freq.QuadPart); } #else double timestamp() { timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec); } #endif struct Vertex { uint16_t data[16]; }; uint32_t murmur3(uint32_t h) { h ^= h >> 16; h *= 0x85ebca6bu; h ^= h >> 13; h *= 0xc2b2ae35u; h ^= h >> 16; return h; } void benchCodecs(const std::vector<Vertex>& vertices, const std::vector<unsigned int>& indices, double& bestvd, double& bestid, bool verbose) { std::vector<Vertex> vb(vertices.size()); std::vector<unsigned int> ib(indices.size()); std::vector<unsigned char> vc(meshopt_encodeVertexBufferBound(vertices.size(), sizeof(Vertex))); std::vector<unsigned char> ic(meshopt_encodeIndexBufferBound(indices.size(), vertices.size())); if (verbose) printf("source: vertex data %d bytes, index data %d bytes\n", int(vertices.size() * sizeof(Vertex)), int(indices.size() * 4)); meshopt_optimizeVertexCache(&ib[0], &indices[0], indices.size(), vertices.size()); meshopt_optimizeVertexFetch(&vb[0], &ib[0], indices.size(), &vertices[0], vertices.size(), sizeof(Vertex)); vc.resize(vc.capacity()); vc.resize(meshopt_encodeVertexBuffer(&vc[0], vc.size(), &vb[0], vertices.size(), sizeof(Vertex))); ic.resize(ic.capacity()); ic.resize(meshopt_encodeIndexBuffer(&ic[0], ic.size(), &ib[0], indices.size())); if (verbose) printf("encode: vertex data %d bytes, index data %d bytes\n", int(vc.size()), int(ic.size())); for (int attempt = 0; attempt < 50; ++attempt) { double t0 = timestamp(); int rv = meshopt_decodeVertexBuffer(&vb[0], vertices.size(), sizeof(Vertex), &vc[0], vc.size()); assert(rv == 0); (void)rv; double t1 = timestamp(); int ri = meshopt_decodeIndexBuffer(&ib[0], indices.size(), 4, &ic[0], ic.size()); assert(ri == 0); (void)ri; double t2 = timestamp(); if (verbose) printf("decode: vertex %.2f ms (%.2f GB/sec), index %.2f ms (%.2f GB/sec)\n", (t1 - t0) * 1000, double(vertices.size() * sizeof(Vertex)) / 1e9 / (t1 - t0), (t2 - t1) * 1000, double(indices.size() * 4) / 1e9 / (t2 - t1)); bestvd = std::max(bestvd, double(vertices.size() * sizeof(Vertex)) / 1e9 / (t1 - t0)); bestid = std::max(bestid, double(indices.size() * 4) / 1e9 / (t2 - t1)); } } void benchFilters(size_t count, double& besto8, double& besto12, double& bestq12, double& bestc8, double& bestc12, double& bestexp, bool verbose) { // note: the filters are branchless so we just run them on runs of zeroes size_t count4 = (count + 3) & ~3; std::vector<unsigned char> d4(count4 * 4); std::vector<unsigned char> d8(count4 * 8); if (verbose) printf("filters: oct8 data %d bytes, oct12/quat12 data %d bytes\n", int(d4.size()), int(d8.size())); for (int attempt = 0; attempt < 50; ++attempt) { double t0 = timestamp(); meshopt_decodeFilterOct(&d4[0], count4, 4); double t1 = timestamp(); meshopt_decodeFilterOct(&d8[0], count4, 8); double t2 = timestamp(); meshopt_decodeFilterQuat(&d8[0], count4, 8); double t3 = timestamp(); meshopt_decodeFilterColor(&d4[0], count4, 4); double t4 = timestamp(); meshopt_decodeFilterColor(&d8[0], count4, 8); double t5 = timestamp(); meshopt_decodeFilterExp(&d8[0], count4, 8); double t6 = timestamp(); if (verbose) printf("filter: oct8 %.2f ms (%.2f GB/sec), oct12 %.2f ms (%.2f GB/sec), quat12 %.2f ms (%.2f GB/sec), col8 %.2f ms (%.2f GB/sec), col12 %.2f ms (%.2f GB/sec), exp %.2f ms (%.2f GB/sec)\n", (t1 - t0) * 1000, double(d4.size()) / 1e9 / (t1 - t0), (t2 - t1) * 1000, double(d8.size()) / 1e9 / (t2 - t1), (t3 - t2) * 1000, double(d8.size()) / 1e9 / (t3 - t2), (t4 - t3) * 1000, double(d8.size()) / 1e9 / (t4 - t3), (t5 - t4) * 1000, double(d4.size()) / 1e9 / (t5 - t4), (t6 - t5) * 1000, double(d8.size()) / 1e9 / (t6 - t5)); besto8 = std::max(besto8, double(d4.size()) / 1e9 / (t1 - t0)); besto12 = std::max(besto12, double(d8.size()) / 1e9 / (t2 - t1)); bestq12 = std::max(bestq12, double(d8.size()) / 1e9 / (t3 - t2)); bestc8 = std::max(bestc8, double(d4.size()) / 1e9 / (t4 - t3)); bestc12 = std::max(bestc12, double(d8.size()) / 1e9 / (t5 - t4)); bestexp = std::max(bestexp, double(d8.size()) / 1e9 / (t6 - t5)); } } void benchMeshlets(const std::vector<float>& positions, const std::vector<unsigned int>& indices, bool encoderefs, double& bestml, bool verbose) { const size_t max_vertices = 64; const size_t max_triangles = 96; size_t max_meshlets = meshopt_buildMeshletsBound(indices.size(), max_vertices, max_triangles); std::vector<meshopt_Meshlet> meshlets(max_meshlets); std::vector<unsigned int> meshlet_vertices(indices.size()); std::vector<unsigned char> meshlet_triangles(indices.size()); meshlets.resize(meshopt_buildMeshlets(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices.data(), indices.size(), positions.data(), positions.size() / 3, sizeof(float) * 3, max_vertices, max_triangles, 0.f)); const meshopt_Meshlet& last = meshlets.back(); meshlet_vertices.resize(last.vertex_offset + last.vertex_count); meshlet_triangles.resize(last.triangle_offset + last.triangle_count * 3); std::vector<unsigned char> cbuf(meshopt_encodeMeshletBound(max_vertices, max_triangles)); // optimize each meshlet for locality before encoding for (size_t i = 0; i < meshlets.size(); ++i) meshopt_optimizeMeshlet(&meshlet_vertices[meshlets[i].vertex_offset], &meshlet_triangles[meshlets[i].triangle_offset], meshlets[i].triangle_count, meshlets[i].vertex_count); // optimize meshlet_vertices for locality (requires vertex reorder) // TODO: over-allocate meshlet_vertices to multiple of 3 to make meshopt_optimizeVertexFetch below work without assertions std::vector<float> positionscopy(positions.size()); meshlet_vertices.resize((meshlet_vertices.size() + 2) / 3 * 3); meshopt_optimizeVertexFetch(&positionscopy[0], &meshlet_vertices[0], meshlet_vertices.size(), &positions[0], positions.size() / 3, sizeof(float) * 3); #if 0 // TODO: disabled for now to make meshlet decoder tuning more accurate; might make sense to re-enable in the future for SOL timings // pack meshlets in decreasing triangle count order to reduce branch mispredictions // (this matters less on real-world meshes but is more prominent on regular grids?) std::sort(meshlets.begin(), meshlets.end(), [](const meshopt_Meshlet& lhs, const meshopt_Meshlet& rhs) { return lhs.triangle_count > rhs.triangle_count; }); #endif std::vector<unsigned char> packed; size_t totals = 0; for (size_t i = 0; i < meshlets.size(); ++i) { const meshopt_Meshlet& meshlet = meshlets[i]; size_t mvc = encoderefs ? meshlet.vertex_count : 0; size_t mbs = meshopt_encodeMeshlet(&cbuf[0], cbuf.size(), &meshlet_vertices[meshlet.vertex_offset], mvc, &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count); assert(mbs > 0); packed.push_back((unsigned char)mvc); packed.push_back((unsigned char)meshlet.triangle_count); packed.push_back((unsigned char)(mbs & 0xff)); packed.push_back((unsigned char)((mbs >> 8) & 0xff)); packed.insert(packed.end(), cbuf.begin(), cbuf.begin() + mbs); totals += size_t(meshlet.triangle_count) * 3 + size_t(mvc) * 4; } if (verbose) printf("meshlets (%d/%d): %d meshlets, packed %d bytes (%.1f bits/triangle)\n", int(max_vertices), int(max_triangles), int(meshlets.size()), int(packed.size()), double(packed.size() * 8) / double(indices.size() / 3)); unsigned int rv[256]; unsigned char rt[256 * 3]; for (int attempt = 0; attempt < 50; ++attempt) { double t0 = timestamp(); const unsigned char* p = &packed[0]; for (size_t i = 0; i < meshlets.size(); ++i) { size_t mbs = p[2] | (p[3] << 8); int rc = meshopt_decodeMeshlet(rv, p[0], rt, p[1], p + 4, mbs); assert(rc == 0); (void)rc; p += 4 + mbs; } assert(p == &packed[0] + packed.size()); double t1 = timestamp(); if (verbose) printf("meshlet decode: %.2f ms (%.2f GB/sec)\n", (t1 - t0) * 1000, double(totals) / 1e9 / (t1 - t0)); bestml = std::max(bestml, double(totals) / 1e9 / (t1 - t0)); } } struct File { std::vector<unsigned char> data; size_t stride; size_t count; }; File readFile(const char* path) { FILE* file = fopen(path, "rb"); assert(file); const char* name = strrchr(path, '/'); name = name ? name + 1 : path; int vcnt, vsz; int sr = sscanf(name, "v%d_s%d_", &vcnt, &vsz); assert(sr == 2); (void)sr; std::vector<unsigned char> input; unsigned char buffer[4096]; size_t bytes_read; while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) input.insert(input.end(), buffer, buffer + bytes_read); fclose(file); File result = {}; result.count = vcnt; result.stride = vsz; std::vector<unsigned char> decoded(result.count * result.stride); int res = meshopt_decodeVertexBuffer(&decoded[0], result.count, result.stride, &input[0], input.size()); if (res != 0 && input.size() == decoded.size()) { // some files are not encoded memcpy(decoded.data(), input.data(), decoded.size()); } result.data.resize(meshopt_encodeVertexBufferBound(result.count, result.stride)); result.data.resize(meshopt_encodeVertexBuffer(result.data.data(), result.data.size(), decoded.data(), result.count, result.stride)); return result; } int main(int argc, char** argv) { bool verbose = false; bool loop = false; bool inputs = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-v") == 0) verbose = true; if (strcmp(argv[i], "-l") == 0) loop = true; if (argv[i][0] != '-') inputs = true; } if (inputs) { std::vector<File> files; for (int i = 1; i < argc; ++i) if (argv[i][0] != '-') files.push_back(readFile(argv[i])); size_t max_size = 0; size_t total_size = 0; size_t total_comp = 0; for (size_t i = 0; i < files.size(); ++i) { max_size = std::max(max_size, files[i].count * files[i].stride); total_size += files[i].count * files[i].stride; total_comp += files[i].data.size(); } printf("%d files, ratio %.2f (%.2f MB => %.2f MB)\n", int(files.size()), double(total_comp) / double(total_size), double(total_size) / 1024 / 1024, double(total_comp) / 1024 / 1024); std::vector<unsigned char> buffer(max_size); for (int l = 0; l < (loop ? 100 : 1); ++l) { double bestvd = 0; for (int attempt = 0; attempt < 50; ++attempt) { double t0 = timestamp(); for (size_t i = 0; i < files.size(); ++i) { int rv = meshopt_decodeVertexBuffer(&buffer[0], files[i].count, files[i].stride, &files[i].data[0], files[i].data.size()); assert(rv == 0); (void)rv; } double t1 = timestamp(); bestvd = std::max(bestvd, double(total_size) / 1e9 / (t1 - t0)); } printf("Score (GB/s):\t%.2f\n", bestvd); } return 0; } const int N = 1000; std::vector<Vertex> vertices; vertices.reserve((N + 1) * (N + 1)); std::vector<float> positions((N + 1) * (N + 1) * 3); for (int x = 0; x <= N; ++x) { for (int y = 0; y <= N; ++y) { Vertex v; for (int k = 0; k < 16; ++k) { uint32_t h = murmur3((x * (N + 1) + y) * 16 + k); // use random k-bit sequence for each word to test all encoding types // note: this doesn't stress the sentinel logic too much but it's all branchless so it's probably fine? v.data[k] = h & ((1 << (k + 1)) - 1); } size_t index = vertices.size(); positions[index * 3 + 0] = float(x); positions[index * 3 + 1] = float(y); positions[index * 3 + 2] = 0.f; vertices.push_back(v); } } std::vector<unsigned int> indices; indices.reserve(N * N * 6); for (int x = 0; x < N; ++x) { for (int y = 0; y < N; ++y) { indices.push_back((x + 0) * N + (y + 0)); indices.push_back((x + 1) * N + (y + 0)); indices.push_back((x + 0) * N + (y + 1)); indices.push_back((x + 0) * N + (y + 1)); indices.push_back((x + 1) * N + (y + 0)); indices.push_back((x + 1) * N + (y + 1)); } } printf("Codec:\tvtx\tidx\tmlet\tmletΔ\toct8\toct12\tquat12\tcol8\tcol12\texp\n"); for (int l = 0; l < (loop ? 100 : 1); ++l) { double bestvd = 0, bestid = 0; benchCodecs(vertices, indices, bestvd, bestid, verbose); double bestml = 0, bestmt = 0; benchMeshlets(positions, indices, /* encoderefs= */ true, bestml, verbose); benchMeshlets(positions, indices, /* encoderefs= */ false, bestmt, verbose); double besto8 = 0, besto12 = 0, bestq12 = 0, bestc8 = 0, bestc12 = 0, bestexp = 0; benchFilters(8 * N * N, besto8, besto12, bestq12, bestc8, bestc12, bestexp, verbose); printf("GB/s :\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\n", bestvd, bestid, bestml, bestmt, besto8, besto12, bestq12, bestc8, bestc12, bestexp); } }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/codecfuzz.cpp
C++
#include "../src/meshoptimizer.h" #include <stdint.h> #include <stdlib.h> #include <string.h> void fuzzDecoder(const uint8_t* data, size_t size, size_t stride, int (*decode)(void*, size_t, size_t, const unsigned char*, size_t)) { size_t count = 66; // must be divisible by 3 for decodeIndexBuffer; should be >=64 to cover large vertex blocks void* destination = malloc(count * stride); assert(destination); int rc = decode(destination, count, stride, reinterpret_cast<const unsigned char*>(data), size); (void)rc; free(destination); } void fuzzRoundtrip(const uint8_t* data, size_t size, size_t stride, int level) { size_t count = size / stride; size_t bound = meshopt_encodeVertexBufferBound(count, stride); void* encoded = malloc(bound); void* decoded = malloc(count * stride); assert(encoded && decoded); size_t res = meshopt_encodeVertexBufferLevel(static_cast<unsigned char*>(encoded), bound, data, count, stride, level, -1); assert(res > 0 && res <= bound); // encode again at the boundary to check for memory safety // this should produce the same output because encoder is deterministic size_t rese = meshopt_encodeVertexBufferLevel(static_cast<unsigned char*>(encoded) + bound - res, res, data, count, stride, level, -1); assert(rese == res); int rc = meshopt_decodeVertexBuffer(decoded, count, stride, static_cast<unsigned char*>(encoded) + bound - res, res); assert(rc == 0); assert(memcmp(data, decoded, count * stride) == 0); free(decoded); free(encoded); } size_t align(size_t value, size_t alignment) { return (value + alignment - 1) & ~(alignment - 1); } void fuzzDecodeMeshlet(size_t vertex_count, size_t triangle_count, const unsigned char* data, size_t size) { // raw decoding: allowed to write align(count, 4) elements unsigned int rt[256]; unsigned int rv[256]; meshopt_decodeMeshletRaw(rv + 256 - align(vertex_count, 4), vertex_count, rt + 256 - align(triangle_count, 4), triangle_count, data, size); // regular decoding: allowed to write align(count * size, 4) bytes // with variations for 3-byte triangles and 2-byte vertex references unsigned short rsv[256]; unsigned char rbt[256 * 3]; meshopt_decodeMeshlet(rv + 256 - vertex_count, vertex_count, 4, rt + 256 - triangle_count, triangle_count, 4, data, size); meshopt_decodeMeshlet(rsv + 256 - align(vertex_count, 2), vertex_count, 2, rt + 256 - triangle_count, triangle_count, 4, data, size); meshopt_decodeMeshlet(rv + 256 - vertex_count, vertex_count, 4, rbt + 256 * 3 - align(triangle_count * 3, 4), triangle_count, 3, data, size); meshopt_decodeMeshlet(rsv + 256 - align(vertex_count, 2), vertex_count, 2, rbt + 256 * 3 - align(triangle_count * 3, 4), triangle_count, 3, data, size); } void fuzzRoundtripMeshlet(const uint8_t* data, size_t size) { size_t triangle_count = size / 3; if (triangle_count > 256) triangle_count = 256; unsigned char buf[4096]; size_t enc = meshopt_encodeMeshlet(buf, sizeof(buf), NULL, 0, reinterpret_cast<const unsigned char*>(data), triangle_count); assert(enc > 0); assert(enc <= meshopt_encodeMeshletBound(0, triangle_count)); unsigned int rt4[256]; int rc4 = meshopt_decodeMeshlet(static_cast<unsigned int*>(NULL), 0, rt4, triangle_count, buf, enc); assert(rc4 == 0); for (size_t i = 0; i < triangle_count; ++i) { unsigned char a = data[i * 3 + 0], b = data[i * 3 + 1], c = data[i * 3 + 2]; unsigned int abc = (a << 0) | (b << 8) | (c << 16); unsigned int bca = (b << 0) | (c << 8) | (a << 16); unsigned int cba = (c << 0) | (a << 8) | (b << 16); unsigned int tri = rt4[i]; assert(tri == abc || tri == bca || tri == cba); } unsigned char rt3[256 * 3]; int rc3 = meshopt_decodeMeshlet(static_cast<unsigned int*>(NULL), 0, rt3, triangle_count, buf, enc); assert(rc3 == 0); for (size_t i = 0; i < triangle_count; ++i) { unsigned char a = data[i * 3 + 0], b = data[i * 3 + 1], c = data[i * 3 + 2]; unsigned int abc = (a << 0) | (b << 8) | (c << 16); unsigned int bca = (b << 0) | (c << 8) | (a << 16); unsigned int cba = (c << 0) | (a << 8) | (b << 16); unsigned int tri = rt3[i * 3 + 0] | (rt3[i * 3 + 1] << 8) | (rt3[i * 3 + 2] << 16); assert(tri == abc || tri == bca || tri == cba); } } void fuzzRoundtripMeshletV(const uint8_t* data, size_t size) { size_t vertex_count = size / 4; if (vertex_count > 256) vertex_count = 256; unsigned char tri[4] = {0, 1, 2}; unsigned char buf[4096]; size_t enc = meshopt_encodeMeshlet(buf, sizeof(buf), reinterpret_cast<const uint32_t*>(data), vertex_count, tri, 1); assert(enc > 0); assert(enc <= meshopt_encodeMeshletBound(vertex_count, 1)); unsigned int rv4[256]; int rc4 = meshopt_decodeMeshlet(rv4, vertex_count, tri, 1, buf, enc); assert(rc4 == 0); for (size_t i = 0; i < vertex_count; ++i) assert(rv4[i] == reinterpret_cast<const uint32_t*>(data)[i]); unsigned short rv2[256]; int rc2 = meshopt_decodeMeshlet(rv2, vertex_count, tri, 1, buf, enc); assert(rc2 == 0); for (size_t i = 0; i < vertex_count; ++i) assert(rv2[i] == uint16_t(reinterpret_cast<const uint32_t*>(data)[i])); } extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { // decodeIndexBuffer supports 2 and 4-byte indices fuzzDecoder(data, size, 2, meshopt_decodeIndexBuffer); fuzzDecoder(data, size, 4, meshopt_decodeIndexBuffer); // decodeIndexSequence supports 2 and 4-byte indices fuzzDecoder(data, size, 2, meshopt_decodeIndexSequence); fuzzDecoder(data, size, 4, meshopt_decodeIndexSequence); // decodeVertexBuffer supports any strides divisible by 4 in 4-256 interval // it's a waste of time to check all of them, so we'll just check a few with different alignment mod 16 fuzzDecoder(data, size, 4, meshopt_decodeVertexBuffer); fuzzDecoder(data, size, 16, meshopt_decodeVertexBuffer); fuzzDecoder(data, size, 24, meshopt_decodeVertexBuffer); fuzzDecoder(data, size, 32, meshopt_decodeVertexBuffer); // encodeVertexBuffer/decodeVertexBuffer should roundtrip for any stride, check a few with different alignment mod 16 // this also checks memory safety properties of the encoder // to conserve time, we only check one version/level combination, biased towards version 1 uint8_t data0 = size > 0 ? data[0] : 0; int level = data0 % 5; meshopt_encodeVertexVersion(level < 4 ? 1 : 0); fuzzRoundtrip(data, size, 4, level); fuzzRoundtrip(data, size, 16, level); fuzzRoundtrip(data, size, 24, level); fuzzRoundtrip(data, size, 32, level); // validate that decodeMeshlet works on untrusted data and is memory safe within documented limits if (size > 2) fuzzDecodeMeshlet(data[0] + 1, data[1] + 1, reinterpret_cast<const unsigned char*>(data + 2), size - 2); // validate that index data roundtrips in meshlet encoding modulo rotation fuzzRoundtripMeshlet(data, size); // validate that vertex data roundtrips in meshlet encoding fuzzRoundtripMeshletV(data, size); return 0; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/codectest.cpp
C++
#include "../src/meshoptimizer.h" #include <vector> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _WIN32 #include <fcntl.h> #include <io.h> #endif size_t measure(const char* cmd, const std::vector<unsigned char>& data) { FILE* file = fopen("/tmp/codectest.in", "wb"); if (!file) return 0; fwrite(data.data(), data.size(), 1, file); fclose(file); char actualcmd[1024]; snprintf(actualcmd, sizeof(actualcmd), cmd, "/tmp/codectest.in", "/tmp/codectest.out"); int rc = system(actualcmd); if (rc) return 0; file = fopen("/tmp/codectest.out", "rb"); if (!file) return 0; fseek(file, 0, SEEK_END); long result = ftell(file); fclose(file); return result; } size_t measure_lz4(const std::vector<unsigned char>& data) { return measure("lz4 -f -q %s %s", data); } size_t measure_zstd(const std::vector<unsigned char>& data) { return measure("zstd -f -q %s -o %s", data); } struct Stats { bool testz; double count; double size; double ratio; double ratio_lz4; double ratio_zstd; double total; double total_lz4; double total_zstd; }; void testFile(FILE* file, size_t count, size_t stride, int level, Stats* stats = 0) { std::vector<unsigned char> input; unsigned char buffer[4096]; size_t bytes_read; while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) input.insert(input.end(), buffer, buffer + bytes_read); std::vector<unsigned char> decoded(count * stride); int res = meshopt_decodeVertexBuffer(&decoded[0], count, stride, &input[0], input.size()); if (res != 0 && input.size() == decoded.size()) { // some files are not encoded memcpy(decoded.data(), input.data(), decoded.size()); } else if (res != 0) { printf(" error decoding input: %d", res); return; } std::vector<unsigned char> output(meshopt_encodeVertexBufferBound(count, stride)); output.resize(meshopt_encodeVertexBufferLevel(output.data(), output.size(), decoded.data(), count, stride, level, -1)); printf(" raw %zu KB\t", decoded.size() / 1024); printf(" vtx %.3f", double(output.size()) / double(decoded.size())); if (stats) { stats->count++; stats->size += double(decoded.size()); stats->total += double(output.size()); stats->ratio += log(double(output.size()) / double(decoded.size())); } if (stats && stats->testz) { size_t decoded_lz4 = measure_lz4(decoded); size_t output_lz4 = measure_lz4(output); size_t decoded_zstd = measure_zstd(decoded); size_t output_zstd = measure_zstd(output); stats->total_lz4 += output_lz4; stats->total_zstd += output_zstd; stats->ratio_lz4 += log(double(output_lz4) / double(decoded.size())); stats->ratio_zstd += log(double(output_zstd) / double(decoded.size())); printf("\tlz4 %.3f", double(decoded_lz4) / double(decoded.size())); printf(" vtx+lz4 %.3f", double(output_lz4) / double(decoded.size())); printf("\tzstd %.3f", double(decoded_zstd) / double(decoded.size())); printf(" vtx+zstd %.3f", double(output_zstd) / double(decoded.size())); } } void testFile(const char* path, int level, Stats* stats = 0) { FILE* file = fopen(path, "rb"); if (!file) return; const char* name = strrchr(path, '/'); name = name ? name + 1 : path; int vcnt, vsz; int sr = sscanf(name, "v%d_s%d_", &vcnt, &vsz); assert(sr == 2); (void)sr; const char* name0 = strchr(strchr(name, '_') + 1, '_') + 1; const char* name1 = strstr(name0, "_R"); size_t namel = name1 ? name1 - name0 : strlen(name0); namel = namel > 25 ? 25 : namel; #if TRACE printf("%.*s: %s\n", int(namel), name0, path); #else printf("%25.*s:", int(namel), name0); #endif testFile(file, vcnt, vsz, level, stats); printf("\n"); fclose(file); } int main(int argc, char** argv) { #ifdef _WIN32 _setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); #endif if (argc > 1 && (strcmp(argv[1], "-test") == 0 || strcmp(argv[1], "-testz") == 0)) { Stats stats = {}; stats.testz = strcmp(argv[1], "-testz") == 0; int level = -1; if (argc > 2 && argv[2][0] == '-' && argv[2][1] >= '0' && argv[2][1] <= '9') level = atoi(argv[2] + 1); for (int i = level < 0 ? 2 : 3; i < argc; ++i) testFile(argv[i], level < 0 ? 2 : level, &stats); printf("---\n"); printf("%d files: vtx %.3f", int(stats.count), exp(stats.ratio / stats.count)); if (stats.testz) printf(", vtx+lz4 %.3f, vtx+zstd %.3f\n", exp(stats.ratio_lz4 / stats.count), exp(stats.ratio_zstd / stats.count)); else printf("\n"); printf("total: %d files, raw %.2f MB, vtx %.2f MB", int(stats.count), stats.size / 1024 / 1024, stats.total / 1024 / 1024); if (stats.testz) printf(", vtx+lz4 %.2f MB, vtx+zstd %.2f MB\n", stats.total_lz4 / 1024 / 1024, stats.total_zstd / 1024 / 1024); else printf("\n"); return 0; } if (argc < 2 || argc > 3 || atoi(argv[1]) <= 0) { fprintf(stderr, "Usage: %s <stride> [<count>]\n", argv[0]); return 1; } size_t stride = atoi(argv[1]); std::vector<unsigned char> input; unsigned char buffer[4096]; size_t bytes_read; while ((bytes_read = fread(buffer, 1, sizeof(buffer), stdin)) > 0) input.insert(input.end(), buffer, buffer + bytes_read); if (argc == 3) { // if count is specified, we assume input is meshopt-encoded and decode it first size_t count = atoi(argv[2]); std::vector<unsigned char> decoded(count * stride); int res = meshopt_decodeVertexBuffer(&decoded[0], count, stride, &input[0], input.size()); if (res != 0) { fprintf(stderr, "Error decoding input: %d\n", res); return 2; } fwrite(decoded.data(), 1, decoded.size(), stdout); return 0; } else { size_t vertex_count = input.size() / stride; std::vector<unsigned char> output(meshopt_encodeVertexBufferBound(vertex_count, stride)); size_t output_size = meshopt_encodeVertexBuffer(output.data(), output.size(), input.data(), vertex_count, stride); #if TRACE printf("%d => %d\n", int(input.size()), int(output_size)); #else fwrite(output.data(), 1, output_size, stdout); #endif return 0; } }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/gltfbasis.py
Python
#!/usr/bin/python3 import argparse import concurrent.futures import matplotlib.pyplot as plt import os import os.path import re import subprocess argp = argparse.ArgumentParser() argp.add_argument('--basisu', type=str, required=True) argp.add_argument('--graph', type=str, default="basisu.png") argp.add_argument('--etcbase', action='store_true') argp.add_argument('files', type=str, nargs='+') args = argp.parse_args() def compress(path, flags): temp_path = "/dev/null" if os.name == "posix" else "NUL" output = subprocess.check_output([args.basisu, "-file", path, "-output_file", temp_path, "-stats", "-ktx2"] + flags) for line in output.splitlines(): if m := re.match(r".*source image.*?(\d+)x(\d+)", line.decode()): pixels = int(m.group(1)) * int(m.group(2)) elif m := re.match(r".*Compression succeeded.*size (\d+) bytes", line.decode()): bytes = int(m.group(1)) elif m := re.match(r"\.basis RGB Avg:.*RMS: (\d+\.\d+) PSNR: (\d+\.\d+)", line.decode()): rms = float(m.group(1)) psnr = float(m.group(2)) return {'path': path, 'bpp': bytes * 8 / pixels, 'rms': rms, 'psnr': psnr} def stats(path): with concurrent.futures.ThreadPoolExecutor(16) as executor: futures = [] for i in range(0, 26): rdo_l = i / 5 flags = ["-uastc", "-uastc_level", "1", "-uastc_rdo_l", str(rdo_l), "-uastc_rdo_d", "1024"] futures.append((executor.submit(compress, path, flags), rdo_l)) concurrent.futures.wait([f for (f, r) in futures]) results = [] bppbase = 0 for future, rdo_l in futures: res = future.result() if rdo_l == 0: bppbase = res['bpp'] res['rdo_l'] = rdo_l res['ratio'] = res['bpp'] / bppbase results.append(res) return results fields = ['bpp', 'rms', 'psnr', 'ratio'] fig, axs = plt.subplots(1, len(fields) + 1, layout='constrained') fig.set_figwidth(5 * (len(fields) + 1)) lines = [] for path in args.files: print('Processing', path) results = stats(path) etcbase = compress(path, ["-q", "192"]) if args.etcbase else None for idx, field in enumerate(fields): line, = axs[idx].plot([r['rdo_l'] for r in results], [r[field] for r in results]) if etcbase and field in etcbase: axs[idx].axhline(etcbase[field], color=line.get_color(), linestyle='dotted') if idx == 0: lines.append(line) axs[len(fields)].scatter([r['ratio'] for r in results], [r['psnr'] for r in results], color=line.get_color()) for idx, field in enumerate(fields): axs[idx].set_title(field) axs[len(fields)].set_title('psnr vs ratio') fig.legend(lines, [os.path.basename(path) for path in args.files], loc='outside right upper') plt.savefig(args.graph)
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/objloader.cpp
C++
#ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif #define FAST_OBJ_IMPLEMENTATION #include "../extern/fast_obj.h"
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/simplifyfuzz.cpp
C++
#include "../src/meshoptimizer.h" #include <float.h> #include <stdint.h> #include <stdlib.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* buffer, size_t size) { if (size == 0) return 0; srand(buffer[0]); float vb[100][4]; for (int i = 0; i < 100; ++i) { vb[i][0] = rand() % 10; vb[i][1] = rand() % 10; vb[i][2] = rand() % 10; vb[i][3] = rand() % 10; } unsigned int ib[999]; int indices = (size - 1) < 999 ? (size - 1) / 3 * 3 : 999; for (int i = 0; i < indices; ++i) ib[i] = buffer[1 + i] % 100; unsigned int res[999]; meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, 1e-1f, 0, NULL); meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, FLT_MAX, 0, NULL); meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, FLT_MAX, meshopt_SimplifyLockBorder, NULL); meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, FLT_MAX, meshopt_SimplifySparse, NULL); meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, FLT_MAX, meshopt_SimplifyPrune, NULL); meshopt_simplify(res, ib, indices, vb[0], 100, sizeof(float) * 4, 0, FLT_MAX, meshopt_SimplifyPermissive, NULL); float aw = 1; meshopt_simplifyWithAttributes(res, ib, indices, vb[0], 100, sizeof(float) * 4, vb[0] + 3, sizeof(float) * 4, &aw, 1, NULL, 0, FLT_MAX, 0, NULL); // must be last, as it modifies all inputs in place meshopt_simplifyWithUpdate(ib, indices, vb[0], 100, sizeof(float) * 4, vb[0] + 3, sizeof(float) * 4, &aw, 1, NULL, 0, FLT_MAX, 0, NULL); return 0; }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/vcachetester.cpp
C++
#ifdef _WIN32 #include <assert.h> #include <d3d11.h> #include <d3dcompiler.h> #include <stdio.h> #include <cassert> #include <cmath> #include <algorithm> #include <vector> #include "../extern/fast_obj.h" #include "../src/meshoptimizer.h" #pragma comment(lib, "d3d11.lib") #pragma comment(lib, "d3dcompiler.lib") #pragma comment(lib, "dxgi.lib") void stripGen(std::vector<unsigned int>& indices, int x0, int x1, int y0, int y1, int width, bool prefetch) { if (prefetch) { for (int x = x0; x < x1; x++) { indices.push_back(x + 0); indices.push_back(x + 0); indices.push_back(x + 1); } } for (int y = y0; y < y1; y++) { for (int x = x0; x < x1; x++) { indices.push_back((width + 1) * (y + 0) + (x + 0)); indices.push_back((width + 1) * (y + 1) + (x + 0)); indices.push_back((width + 1) * (y + 0) + (x + 1)); indices.push_back((width + 1) * (y + 0) + (x + 1)); indices.push_back((width + 1) * (y + 1) + (x + 0)); indices.push_back((width + 1) * (y + 1) + (x + 1)); } } } void gridGen(std::vector<unsigned int>& indices, int x0, int x1, int y0, int y1, int width, int cacheSize, bool prefetch) { if (x1 - x0 + 1 < cacheSize) { bool prefetchStrip = 2 * (x1 - x0) + 1 > cacheSize && prefetch; stripGen(indices, x0, x1, y0, y1, width, prefetchStrip); } else { int xm = x0 + cacheSize - 2; gridGen(indices, x0, xm, y0, y1, width, cacheSize, prefetch); gridGen(indices, xm, x1, y0, y1, width, cacheSize, prefetch); } } unsigned int queryVSInvocations(ID3D11Device* device, ID3D11DeviceContext* context, const unsigned int* indices, size_t index_count) { if (index_count == 0) return 0; ID3D11Buffer* ib = 0; { D3D11_BUFFER_DESC bd = {}; bd.Usage = D3D11_USAGE_DYNAMIC; bd.ByteWidth = index_count * 4; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; device->CreateBuffer(&bd, 0, &ib); D3D11_MAPPED_SUBRESOURCE ms; context->Map(ib, 0, D3D11_MAP_WRITE_DISCARD, 0, &ms); memcpy(ms.pData, indices, index_count * 4); context->Unmap(ib, 0); } context->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetIndexBuffer(ib, DXGI_FORMAT_R32_UINT, 0); D3D11_QUERY_DESC qdesc = {D3D11_QUERY_PIPELINE_STATISTICS}; ID3D11Query* query = 0; device->CreateQuery(&qdesc, &query); context->Begin(query); context->DrawIndexed(index_count, 0, 0); context->End(query); D3D11_QUERY_DATA_PIPELINE_STATISTICS stats = {}; while (S_FALSE == context->GetData(query, &stats, sizeof(stats), 0)) ; query->Release(); ib->Release(); assert(stats.IAVertices == index_count); return stats.VSInvocations; } void setupShaders(ID3D11Device* device, ID3D11DeviceContext* context) { // load and compile the two shaders const char* shaders = "#define ATTRIBUTES 5\n" "struct Foo { float4 v[ATTRIBUTES]; };" "float4 VS(uint index: SV_VertexId, out Foo foo: FOO): SV_Position { uint i = index % 3; [unroll] for (int j = 0; j < ATTRIBUTES; j++) foo.v[j] = j; return float4(i != 0, i != 2, 0, 1); }" "float4 PS(Foo foo: FOO): SV_Target { float4 result = 0; [unroll] for (int j = 0; j < ATTRIBUTES; j++) result += foo.v[j]; return result; }"; ID3DBlob* vsblob = 0; ID3DBlob* psblob = 0; D3DCompile(shaders, strlen(shaders), 0, 0, 0, "VS", "vs_5_0", 0, 0, &vsblob, 0); D3DCompile(shaders, strlen(shaders), 0, 0, 0, "PS", "ps_5_0", 0, 0, &psblob, 0); ID3D11VertexShader* vs = 0; ID3D11PixelShader* ps = 0; device->CreateVertexShader(vsblob->GetBufferPointer(), vsblob->GetBufferSize(), 0, &vs); device->CreatePixelShader(psblob->GetBufferPointer(), psblob->GetBufferSize(), 0, &ps); context->VSSetShader(vs, 0, 0); context->PSSetShader(ps, 0, 0); } template <typename Cache> void inspectCache(Cache cache) { unsigned int max_cache_size = 200; unsigned int grid_size = 100; for (unsigned int cache_size = 3; cache_size <= max_cache_size; cache_size += 1) { std::vector<unsigned int> grid1; gridGen(grid1, 0, grid_size, 0, grid_size, grid_size, cache_size, true); std::vector<unsigned int> grid2; gridGen(grid2, 0, grid_size, 0, grid_size, grid_size, cache_size, false); std::vector<unsigned int> grid3; gridGen(grid3, 0, grid_size, 0, grid_size, grid_size, grid_size * 4, false); // this generates a simple indexed grid without striping/degenerate triangles meshopt_optimizeVertexCacheFifo(&grid3[0], &grid3[0], grid3.size(), (grid_size + 1) * (grid_size + 1), cache_size); std::vector<unsigned int> grid4; gridGen(grid4, 0, grid_size, 0, grid_size, grid_size, grid_size * 4, false); // this generates a simple indexed grid without striping/degenerate triangles meshopt_optimizeVertexCache(&grid4[0], &grid4[0], grid4.size(), (grid_size + 1) * (grid_size + 1)); unsigned int invocations1 = cache(&grid1[0], grid1.size()); unsigned int invocations2 = cache(&grid2[0], grid2.size()); unsigned int invocations3 = cache(&grid3[0], grid3.size()); unsigned int invocations4 = cache(&grid4[0], grid4.size()); unsigned int ideal_invocations = (grid_size + 1) * (grid_size + 1); printf("%d, %f, %f, %f, %f\n", cache_size, double(invocations1) / double(ideal_invocations), double(invocations2) / double(ideal_invocations), double(invocations3) / double(ideal_invocations), double(invocations4) / double(ideal_invocations)); } } void testCache(IDXGIAdapter* adapter) { ID3D11Device* device = 0; ID3D11DeviceContext* context = 0; D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, 0, 0, 0, 0, D3D11_SDK_VERSION, &device, 0, &context); setupShaders(device, context); inspectCache([&](const unsigned int* indices, size_t index_count) { return queryVSInvocations(device, context, indices, index_count); }); } void testCacheSequence(IDXGIAdapter* adapter, int argc, char** argv) { ID3D11Device* device = 0; ID3D11DeviceContext* context = 0; D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, 0, 0, 0, 0, D3D11_SDK_VERSION, &device, 0, &context); setupShaders(device, context); std::vector<unsigned int> ib; for (int i = 2; i < argc; ++i) { char* end; int i0 = strtol(argv[i], &end, 10); if (end[0] == '-') { int i1 = strtol(end + 1, &end, 10); if (end[0] != 0) { printf("Unrecognized index range: %s\n", argv[i]); return; } if (i0 < i1) { for (int ii = i0; ii <= i1; ++ii) ib.push_back(ii); } else { for (int ii = i0; ii >= i1; --ii) ib.push_back(ii); } } else if (end[0] == '*') { int i1 = strtol(end + 1, &end, 10); if (end[0] != 0 || i1 == 0) { printf("Unrecognized index range: %s\n", argv[i]); return; } for (int ii = 0; ii < i1; ++ii) ib.push_back(i0); } else if (end[0] == 'x') { int i1 = strtol(end + 1, &end, 10); if (end[0] != 0) { printf("Unrecognized index range: %s\n", argv[i]); return; } stripGen(ib, 0, i0, 0, i1, i0, true); } else if (end[0] == 0) { ib.push_back(i0); } else { printf("Unrecognized index range: %s\n", argv[i]); return; } } if (ib.size() % 3) ib.resize(ib.size() - ib.size() % 3); std::vector<bool> xformed(ib.size()); for (size_t i = 0; i < ib.size(); i += 3) { unsigned int inv0 = i == 0 ? 0 : queryVSInvocations(device, context, ib.data(), i); unsigned int inv1 = queryVSInvocations(device, context, ib.data(), i + 3); assert(inv0 <= inv1); assert(inv0 + 3 >= inv1); switch (inv1 - inv0) { case 0: xformed[i + 0] = xformed[i + 1] = xformed[i + 2] = false; break; case 3: xformed[i + 0] = xformed[i + 1] = xformed[i + 2] = true; break; case 1: case 2: { unsigned int a = ib[i + 0]; unsigned int b = ib[i + 1]; unsigned int c = ib[i + 2]; ib[i + 0] = ib[i + 1] = ib[i + 2] = a; unsigned int inva = queryVSInvocations(device, context, ib.data(), i + 3); ib[i + 1] = ib[i + 2] = b; unsigned int invb = queryVSInvocations(device, context, ib.data(), i + 3); ib[i + 2] = c; unsigned int invc = queryVSInvocations(device, context, ib.data(), i + 3); assert(inv0 <= inva && inva <= inv1); assert(inv0 <= invb && invb <= inv1); assert(inv0 <= invc && invc <= inv1); if (inv1 - inv0 == 1 && a == c && inva == inv1 && invb == inv0 && invc == inv1) { xformed[i + 0] = false; xformed[i + 1] = false; xformed[i + 2] = true; } else { assert(inva <= invb); assert(invb <= invc); xformed[i + 0] = inva == inv0 + 1; xformed[i + 1] = invb == inva + 1; xformed[i + 2] = invc == invb + 1; } break; } } } unsigned int xformed_total = 0; for (size_t i = 0; i < ib.size(); ++i) xformed_total += xformed[i]; printf("// Sequence: %d indices", int(ib.size())); for (size_t i = 0; i < ib.size(); ++i) { if (i % 12 == 0) { printf("\n// %3d*3:", int(i / 3)); } if (xformed[i]) printf(" %3d*", ib[i]); else printf(" %3d ", ib[i]); } printf("\n"); std::vector<unsigned int> cached; for (size_t i = 0; i < ib.size(); ++i) { unsigned int index = ib[i]; unsigned int inv0 = queryVSInvocations(device, context, ib.data(), ib.size()); ib.push_back(index); ib.push_back(index); ib.push_back(index); unsigned int inv1 = queryVSInvocations(device, context, ib.data(), ib.size()); ib.resize(ib.size() - 3); if (inv1 == inv0) cached.push_back(index); } std::sort(cached.begin(), cached.end()); cached.erase(std::unique(cached.begin(), cached.end()), cached.end()); printf("// Cached :"); for (size_t i = 0; i < cached.size(); ++i) printf(" %d", cached[i]); printf(" (%d)\n", int(cached.size())); unsigned int invocations = queryVSInvocations(device, context, ib.data(), ib.size()); printf("// Invocations: %d\n", invocations); assert(xformed_total == invocations); } void testCacheMeshes(IDXGIAdapter* adapter, int argc, char** argv) { ID3D11Device* device = 0; ID3D11DeviceContext* context = 0; D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, 0, 0, 0, 0, D3D11_SDK_VERSION, &device, 0, &context); setupShaders(device, context); bool stat = false; double atvr_sum = 0; double atvr_count = 0; unsigned int total_invocations = 0; unsigned int total_vertices = 0; for (int i = 1; i < argc; ++i) { const char* path = argv[i]; if (strcmp(path, "--stat") == 0) { stat = true; continue; } fastObjMesh* obj = fast_obj_read(path); if (!obj) { printf("Error loading %s: file not found\n", path); continue; } std::vector<unsigned int> ib1; size_t index_offset = 0; for (unsigned int i = 0; i < obj->face_count; ++i) { if (obj->face_vertices[i] <= 2) continue; for (unsigned int j = 0; j < obj->face_vertices[i]; ++j) { fastObjIndex gi = obj->indices[index_offset + j]; // triangulate polygon on the fly; offset-3 is always the first polygon vertex if (j >= 3) { unsigned int i0 = ib1[ib1.size() - 3]; unsigned int i1 = ib1[ib1.size() - 1]; ib1.push_back(i0); ib1.push_back(i1); } ib1.push_back(gi.p); } index_offset += obj->face_vertices[i]; } unsigned int vertex_count = obj->position_count; unsigned int index_count = ib1.size(); unsigned int invocations1 = queryVSInvocations(device, context, ib1.data(), index_count); if (stat) { std::vector<unsigned int> ib2(ib1.size()); meshopt_optimizeVertexCache(&ib2[0], &ib1[0], ib1.size(), vertex_count); unsigned int invocations = queryVSInvocations(device, context, ib2.data(), index_count); atvr_sum += double(invocations) / double(vertex_count); atvr_count += 1; total_invocations += invocations; total_vertices += vertex_count; } else { printf("%s: baseline %f\n", path, double(invocations1) / double(vertex_count)); std::vector<unsigned int> ib3(ib1.size()); meshopt_optimizeVertexCache(&ib3[0], &ib1[0], ib1.size(), vertex_count); unsigned int invocations3 = queryVSInvocations(device, context, ib3.data(), index_count); printf("%s: forsyth %f\n", path, double(invocations3) / double(vertex_count)); for (unsigned int cache_size = 12; cache_size <= 24; ++cache_size) { std::vector<unsigned int> ib2(ib1.size()); meshopt_optimizeVertexCacheFifo(&ib2[0], &ib1[0], ib1.size(), vertex_count, cache_size); unsigned int invocations2 = queryVSInvocations(device, context, ib2.data(), index_count); printf("%s: tipsify(%d) %f\n", path, cache_size, double(invocations2) / double(vertex_count)); } } } if (stat) { printf("ATVR: average %f cumulative %f; %d vertices\n", atvr_sum / atvr_count, double(total_invocations) / double(total_vertices), total_vertices); } } int main(int argc, char** argv) { IDXGIFactory1* factory = 0; CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&factory); IDXGIAdapter* adapter = NULL; for (unsigned int index = 0; SUCCEEDED(factory->EnumAdapters(index, &adapter)); ++index) { DXGI_ADAPTER_DESC ad = {}; adapter->GetDesc(&ad); if (ad.VendorId == 0x1414 && ad.DeviceId == 0x8c) continue; // Skip Microsoft Basic Render Driver printf("// GPU %d: %S (Vendor %04x Device %04x)\n", index, ad.Description, ad.VendorId, ad.DeviceId); if (argc == 1) { testCache(adapter); } else if (argc > 1 && strcmp(argv[1], "--") == 0) { testCacheSequence(adapter, argc, argv); } else { testCacheMeshes(adapter, argc, argv); } } } #endif
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/vcachetuner.cpp
C++
#include "../extern/fast_obj.h" #include "../src/meshoptimizer.h" #define SDEFL_IMPLEMENTATION #include "../extern/sdefl.h" #include <algorithm> #include <functional> #include <vector> #include <cmath> #include <cstdint> #include <cstdio> #include <cstring> const int kCacheSizeMax = 16; const int kValenceMax = 8; namespace meshopt { struct VertexScoreTable { float cache[1 + kCacheSizeMax]; float live[1 + kValenceMax]; }; } // namespace meshopt void meshopt_optimizeVertexCacheTable(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const meshopt::VertexScoreTable* table); struct Profile { float weight; int cache, warp, triangle; // vcache tuning parameters int compression; }; Profile profiles[] = { {1.f, 0, 0, 0, 0}, // Compression {1.f, 0, 0, 0, 1}, // Compression w/deflate // {1.f, 14, 64, 128}, // AMD GCN // {1.f, 32, 32, 32}, // NVidia Pascal // {1.f, 16, 32, 32}, // NVidia Kepler, Maxwell // {1.f, 128, 0, 0}, // Intel }; const int Profile_Count = sizeof(profiles) / sizeof(profiles[0]); struct pcg32_random_t { uint64_t state; uint64_t inc; }; #define PCG32_INITIALIZER {0x853c49e6748fea9bULL, 0xda3e39cb94b95bdbULL} uint32_t pcg32_random_r(pcg32_random_t* rng) { uint64_t oldstate = rng->state; // Advance internal state rng->state = oldstate * 6364136223846793005ULL + (rng->inc | 1); // Calculate output function (XSH RR), uses old state for max ILP uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; uint32_t rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); } pcg32_random_t rngstate = PCG32_INITIALIZER; float rand01() { return pcg32_random_r(&rngstate) / float(1ull << 32); } uint32_t rand32() { return pcg32_random_r(&rngstate); } struct State { float cache[kCacheSizeMax]; float live[kValenceMax]; float fitness; }; struct Mesh { const char* name; size_t vertex_count; std::vector<unsigned int> indices; float metric_base[Profile_Count]; }; Mesh gridmesh(unsigned int N) { Mesh result; result.name = "grid"; result.vertex_count = (N + 1) * (N + 1); result.indices.reserve(N * N * 6); for (unsigned int y = 0; y < N; ++y) for (unsigned int x = 0; x < N; ++x) { result.indices.push_back((y + 0) * (N + 1) + (x + 0)); result.indices.push_back((y + 0) * (N + 1) + (x + 1)); result.indices.push_back((y + 1) * (N + 1) + (x + 0)); result.indices.push_back((y + 1) * (N + 1) + (x + 0)); result.indices.push_back((y + 0) * (N + 1) + (x + 1)); result.indices.push_back((y + 1) * (N + 1) + (x + 1)); } return result; } Mesh objmesh(const char* path) { fastObjMesh* obj = fast_obj_read(path); if (!obj) { printf("Error loading %s: file not found\n", path); return Mesh(); } size_t total_indices = 0; for (unsigned int i = 0; i < obj->face_count; ++i) if (obj->face_vertices[i] > 2) total_indices += 3 * (obj->face_vertices[i] - 2); struct Vertex { float px, py, pz; float nx, ny, nz; float tx, ty; }; std::vector<Vertex> vertices(total_indices); size_t vertex_offset = 0; size_t index_offset = 0; for (unsigned int i = 0; i < obj->face_count; ++i) { if (obj->face_vertices[i] <= 2) continue; for (unsigned int j = 0; j < obj->face_vertices[i]; ++j) { fastObjIndex gi = obj->indices[index_offset + j]; Vertex v = { obj->positions[gi.p * 3 + 0], obj->positions[gi.p * 3 + 1], obj->positions[gi.p * 3 + 2], obj->normals[gi.n * 3 + 0], obj->normals[gi.n * 3 + 1], obj->normals[gi.n * 3 + 2], obj->texcoords[gi.t * 2 + 0], obj->texcoords[gi.t * 2 + 1], }; // triangulate polygon on the fly; offset-3 is always the first polygon vertex if (j >= 3) { vertices[vertex_offset + 0] = vertices[vertex_offset - 3]; vertices[vertex_offset + 1] = vertices[vertex_offset - 1]; vertex_offset += 2; } vertices[vertex_offset] = v; vertex_offset++; } index_offset += obj->face_vertices[i]; } fast_obj_destroy(obj); Mesh result; result.name = path; std::vector<unsigned int> remap(total_indices); size_t total_vertices = meshopt_generateVertexRemap(&remap[0], NULL, total_indices, &vertices[0], total_indices, sizeof(Vertex)); result.indices.resize(total_indices); meshopt_remapIndexBuffer(&result.indices[0], NULL, total_indices, &remap[0]); result.vertex_count = total_vertices; return result; } template <typename T> size_t compress(const std::vector<T>& data, int level = SDEFL_LVL_DEF) { std::vector<unsigned char> cbuf(sdefl_bound(int(data.size() * sizeof(T)))); sdefl s = {}; return sdeflate(&s, &cbuf[0], reinterpret_cast<const unsigned char*>(&data[0]), int(data.size() * sizeof(T)), level); } void compute_metric(const State* state, const Mesh& mesh, float result[Profile_Count]) { std::vector<unsigned int> indices(mesh.indices.size()); if (state) { meshopt::VertexScoreTable table = {}; memcpy(table.cache + 1, state->cache, kCacheSizeMax * sizeof(float)); memcpy(table.live + 1, state->live, kValenceMax * sizeof(float)); meshopt_optimizeVertexCacheTable(&indices[0], &mesh.indices[0], mesh.indices.size(), mesh.vertex_count, &table); } else { meshopt_optimizeVertexCache(&indices[0], &mesh.indices[0], mesh.indices.size(), mesh.vertex_count); } meshopt_optimizeVertexFetch(NULL, &indices[0], indices.size(), NULL, mesh.vertex_count, 0); std::vector<unsigned char> ibuf; for (int profile = 0; profile < Profile_Count; ++profile) { if (profiles[profile].cache == 0) { ibuf.resize(meshopt_encodeIndexBufferBound(indices.size(), mesh.vertex_count)); ibuf.resize(meshopt_encodeIndexBuffer(&ibuf[0], ibuf.size(), &indices[0], indices.size())); } } for (int profile = 0; profile < Profile_Count; ++profile) { if (profiles[profile].cache) { meshopt_VertexCacheStatistics stats = meshopt_analyzeVertexCache(&indices[0], indices.size(), mesh.vertex_count, profiles[profile].cache, profiles[profile].warp, profiles[profile].triangle); result[profile] = stats.atvr; } else { // take into account both pre-deflate and post-deflate size but focus a bit more on post-deflate size_t csize = profiles[profile].compression ? compress(ibuf) : ibuf.size(); result[profile] = double(csize) / double(indices.size() / 3); } } } float fitness_score(const State& state, const std::vector<Mesh>& meshes) { float result = 0; float count = 0; for (auto& mesh : meshes) { float metric[Profile_Count]; compute_metric(&state, mesh, metric); for (int profile = 0; profile < Profile_Count; ++profile) { result += mesh.metric_base[profile] / metric[profile] * profiles[profile].weight; count += profiles[profile].weight; } } return result / count; } std::vector<State> gen0(size_t count, const std::vector<Mesh>& meshes) { std::vector<State> result; for (size_t i = 0; i < count; ++i) { State state = {}; for (int j = 0; j < kCacheSizeMax; ++j) state.cache[j] = rand01(); for (int j = 0; j < kValenceMax; ++j) state.live[j] = rand01(); state.fitness = fitness_score(state, meshes); result.push_back(state); } return result; } // https://en.wikipedia.org/wiki/Differential_evolution // Good Parameters for Differential Evolution. Magnus Erik Hvass Pedersen, 2010 std::pair<State, float> genN(std::vector<State>& seed, const std::vector<Mesh>& meshes, float crossover = 0.8803f, float weight = 0.4717f) { std::vector<State> result(seed.size()); for (size_t i = 0; i < seed.size(); ++i) { for (;;) { int a = rand32() % seed.size(); int b = rand32() % seed.size(); int c = rand32() % seed.size(); if (a == b || a == c || b == c || a == int(i) || b == int(i) || c == int(i)) continue; int rc = rand32() % kCacheSizeMax; int rl = rand32() % kValenceMax; for (int j = 0; j < kCacheSizeMax; ++j) { float r = rand01(); if (r < crossover || j == rc) result[i].cache[j] = std::max(0.f, std::min(1.f, seed[a].cache[j] + weight * (seed[b].cache[j] - seed[c].cache[j]))); else result[i].cache[j] = seed[i].cache[j]; } for (int j = 0; j < kValenceMax; ++j) { float r = rand01(); if (r < crossover || j == rl) result[i].live[j] = std::max(0.f, std::min(1.f, seed[a].live[j] + weight * (seed[b].live[j] - seed[c].live[j]))); else result[i].live[j] = seed[i].live[j]; } break; } } #pragma omp parallel for for (size_t i = 0; i < seed.size(); ++i) { result[i].fitness = fitness_score(result[i], meshes); } State best = {}; float bestfit = 0; for (size_t i = 0; i < seed.size(); ++i) { if (result[i].fitness > seed[i].fitness) seed[i] = result[i]; if (seed[i].fitness > bestfit) { best = seed[i]; bestfit = seed[i].fitness; } } return std::make_pair(best, bestfit); } bool load_state(const char* path, std::vector<State>& result) { FILE* file = fopen(path, "rb"); if (!file) return false; State state; result.clear(); while (fread(&state, sizeof(State), 1, file) == 1) result.push_back(state); fclose(file); return true; } bool save_state(const char* path, const std::vector<State>& result) { FILE* file = fopen(path, "wb"); if (!file) return false; for (auto& state : result) { if (fwrite(&state, sizeof(State), 1, file) != 1) { fclose(file); return false; } } return fclose(file) == 0; } void dump_state(const State& state) { printf("cache:"); for (int i = 0; i < kCacheSizeMax; ++i) { printf(" %.3f", state.cache[i]); } printf("\n"); printf("live:"); for (int i = 0; i < kValenceMax; ++i) { printf(" %.3f", state.live[i]); } printf("\n"); } void dump_stats(const State& state, const std::vector<Mesh>& meshes) { float improvement[Profile_Count] = {}; for (size_t i = 0; i < meshes.size(); ++i) { float metric[Profile_Count]; compute_metric(&state, meshes[i], metric); printf(" %s", meshes[i].name); for (int profile = 0; profile < Profile_Count; ++profile) printf(" %f", metric[profile]); for (int profile = 0; profile < Profile_Count; ++profile) improvement[profile] += meshes[i].metric_base[profile] / metric[profile]; } printf("; improvement"); for (int profile = 0; profile < Profile_Count; ++profile) printf(" %f", improvement[profile] / float(meshes.size())); printf("\n"); } int main(int argc, char** argv) { meshopt_encodeIndexVersion(1); std::vector<Mesh> meshes; meshes.push_back(gridmesh(50)); for (int i = 1; i < argc; ++i) meshes.push_back(objmesh(argv[i])); size_t total_triangles = 0; for (auto& mesh : meshes) { compute_metric(nullptr, mesh, mesh.metric_base); total_triangles += mesh.indices.size() / 3; } std::vector<State> pop; size_t gen = 0; if (load_state("mutator.state", pop)) { printf("Loaded %d state vectors\n", int(pop.size())); } else { pop = gen0(95, meshes); } printf("%d meshes, %.1fM triangles\n", int(meshes.size()), double(total_triangles) / 1e6); for (;;) { auto best = genN(pop, meshes); gen++; if (gen % 10 == 0) { printf("%d: fitness %f;", int(gen), best.second); dump_stats(best.first, meshes); } else { printf("%d: fitness %f\n", int(gen), best.second); } dump_state(best.first); if (save_state("mutator.state-temp", pop) && rename("mutator.state-temp", "mutator.state") == 0) { } else { printf("ERROR: Can't save state\n"); } } }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/wasmpack.py
Python
#!/usr/bin/python3 import re import sys # regenerate with wasmpack.py generate table = [32, 0, 65, 2, 1, 106, 34, 33, 3, 128, 11, 4, 13, 64, 6, 253, 10, 7, 15, 116, 127, 5, 8, 12, 40, 16, 19, 54, 20, 9, 27, 255, 113, 17, 42, 67, 24, 23, 146, 148, 18, 14, 22, 45, 70, 69, 56, 114, 101, 21, 25, 63, 75, 136, 108, 28, 118, 29, 73, 115] palette = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:;"; def encode(buffer): result = '' for ch in buffer.read(): if ch in table: index = table.index(ch) result += palette[index] else: result += palette[60 + ch // 64] result += palette[ch % 64] return result def stats(buffer): hist = [0] * 256 for ch in buffer.read(): hist[ch] += 1 result = [i for i in range(256)] result.sort(key=lambda i: hist[i], reverse=True) return result def patch(target, stem, code): with open(target, 'r') as f: content = f.read() pattern = r'(["\']).*\1(;\s*//\s*embed! ' + stem + r')' result = re.sub(pattern, r'\1' + re.escape(code) + r'\1\2', content) with open(target, 'w') as f: f.write(result) if len(sys.argv) >= 2 and sys.argv[1] == 'generate': print(stats(sys.stdin.buffer)[:60]) elif len(sys.argv) >= 2 and sys.argv[1] == 'patch': code = encode(sys.stdin.buffer) patch(sys.argv[2], sys.argv[3], code) else: print(encode(sys.stdin.buffer))
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
tools/wasmstubs.cpp
C++
#ifndef __wasi__ #error This file contains libc stubs for WASI SDK and should only be used in non-Emscripten WebAssembly builds #endif #include <assert.h> #include <stddef.h> #include <stdint.h> extern unsigned char __heap_base; static intptr_t sbrkp = intptr_t(&__heap_base); static const int WASM_PAGE_SIZE = 64 * 1024; extern "C" void* sbrk(intptr_t increment) { intptr_t sbrko = sbrkp; increment = (increment + 3) & ~3; sbrkp += increment; size_t heap_size = __builtin_wasm_memory_size(0) * WASM_PAGE_SIZE; if (size_t(sbrkp) > heap_size) { size_t diff = (sbrkp - heap_size + WASM_PAGE_SIZE - 1) / WASM_PAGE_SIZE; if (__builtin_wasm_memory_grow(0, diff) == size_t(-1)) return (void*)-1; } return (void*)sbrko; } extern "C" void* memcpy(void* destination, const void* source, size_t num) { char* d = (char*)destination; const char* s = (const char*)source; if (((uintptr_t(d) | uintptr_t(s)) & 3) == 0) { while (num > 15) { ((uint32_t*)d)[0] = ((uint32_t*)s)[0]; ((uint32_t*)d)[1] = ((uint32_t*)s)[1]; ((uint32_t*)d)[2] = ((uint32_t*)s)[2]; ((uint32_t*)d)[3] = ((uint32_t*)s)[3]; d += 16; s += 16; num -= 16; } while (num > 3) { ((uint32_t*)d)[0] = ((uint32_t*)s)[0]; d += 4; s += 4; num -= 4; } } while (num > 0) { *d++ = *s++; num--; } return destination; } extern "C" void* memset(void* ptr, int value, size_t num) { uint32_t v32 = ~0u / 255 * uint8_t(value); char* d = (char*)ptr; if ((uintptr_t(d) & 3) == 0) { while (num > 15) { ((uint32_t*)d)[0] = v32; ((uint32_t*)d)[1] = v32; ((uint32_t*)d)[2] = v32; ((uint32_t*)d)[3] = v32; d += 16; num -= 16; } while (num > 3) { ((uint32_t*)d)[0] = v32; d += 4; num -= 4; } } while (num > 0) { *d++ = char(value); num--; } return ptr; } void* operator new(size_t size) { return sbrk((size + 7) & ~7); } void operator delete(void* ptr) throw() { void* brk = reinterpret_cast<void*>(sbrkp); assert(ptr <= brk); sbrk((char*)ptr - (char*)brk); }
zeux/meshoptimizer
7,278
Mesh optimization library that makes meshes smaller and faster to render
C++
zeux
Arseny Kapoulkine
src/common.h
C/C++ Header
#pragma once #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <volk.h> #include <vector> #define VK_CHECK(call) \ do \ { \ VkResult result_ = call; \ assert(result_ == VK_SUCCESS); \ } while (0) #define VK_CHECK_FORCE(call) \ do \ { \ VkResult result_ = call; \ if (result_ != VK_SUCCESS) \ { \ fprintf(stderr, "%s:%d: %s failed with error %d\n", __FILE__, __LINE__, #call, result_); \ abort(); \ } \ } while (0) #define VK_CHECK_SWAPCHAIN(call) \ do \ { \ VkResult result_ = call; \ assert(result_ == VK_SUCCESS || result_ == VK_SUBOPTIMAL_KHR || result_ == VK_ERROR_OUT_OF_DATE_KHR); \ } while (0) #define VK_CHECK_QUERY(call) \ do \ { \ VkResult result_ = call; \ assert(result_ == VK_SUCCESS || result_ == VK_NOT_READY); \ } while (0) template <typename T, size_t Size> char (*countof_helper(T (&_Array)[Size]))[Size]; #define COUNTOF(array) (sizeof(*countof_helper(array)) + 0)
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/config.h
C/C++ Header
// Workgroup size for task shader; each task shader thread produces up to one meshlet #define TASK_WGSIZE 64 // Workgroup size for mesh shader; mesh shader workgroup processes the entire meshlet in parallel #define MESH_WGSIZE 64 // Should we do meshlet frustum, occlusion and backface culling in task shader? #define TASK_CULL 1 // Should we do triangle frustum and backface culling in mesh shader? #define MESH_CULL 0 // Maximum number of vertices and triangles in a meshlet #define MESH_MAXVTX 64 #define MESH_MAXTRI 96 // Meshlet build configuration for raster/RT #define MESHLET_CONE_WEIGHT 0.25f #define MESHLET_FILL_WEIGHT 0.5f // Number of clusters along X dimension in a 3D tiled dispatch (must be a divisor of 256) #define CLUSTER_TILE 16 // Maximum number of total task shader workgroups; 4M workgroups ~= 256M meshlets ~= 16B triangles if TASK_WGSIZE=64 and MESH_MAXTRI=64 #define TASK_WGLIMIT (1 << 22) // Maximum number of total visible clusters; 16M meshlets ~= 64MB buffer with cluster indices #define CLUSTER_LIMIT (1 << 24) // Maximum number of frames in flight #define MAX_FRAMES 2 // Minimum number of images in flight #define MIN_IMAGES 3 // Should we enable vertical sync during presentation? Worth setting to 0 when doing perf profiling to avoid GPU downclock during idle #define CONFIG_VSYNC 1 // Should we enable validation layers in release? (they are always enabled in debug) #define CONFIG_RELVAL 0 // Should we enable synchronization validation? Worth running with 1 occasionally to check correctness. #define CONFIG_SYNCVAL 0 // Maximum number of resource descriptors allocated statically #define DESCRIPTOR_LIMIT 65536 // Maximum number of resource descriptors submitted per frame via push #define DESCRIPTOR_LIMIT_FRAME 1024 // Maximum number of sampler descriptors #define DESCRIPTOR_LIMIT_SAMPLERS 16
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/device.cpp
C++
#include "common.h" #include "device.h" #include "config.h" #include "swapchain.h" #include <stdio.h> #include <stdlib.h> #include <string.h> // Validation is enabled by default in Debug #ifndef NDEBUG #define KHR_VALIDATION 1 #else #define KHR_VALIDATION CONFIG_RELVAL #endif // Synchronization validation is disabled by default in Debug since it's rather slow #define SYNC_VALIDATION CONFIG_SYNCVAL // We have a strict requirement for latest Vulkan version to be available #define API_VERSION VK_API_VERSION_1_4 #ifdef _WIN32 #include <Windows.h> #endif static bool isLayerSupported(const char* name) { uint32_t propertyCount = 0; VK_CHECK(vkEnumerateInstanceLayerProperties(&propertyCount, 0)); std::vector<VkLayerProperties> properties(propertyCount); VK_CHECK(vkEnumerateInstanceLayerProperties(&propertyCount, properties.data())); for (uint32_t i = 0; i < propertyCount; ++i) if (strcmp(name, properties[i].layerName) == 0) return true; return false; } bool isInstanceExtensionSupported(const char* name) { uint32_t propertyCount = 0; VK_CHECK(vkEnumerateInstanceExtensionProperties(NULL, &propertyCount, 0)); std::vector<VkExtensionProperties> properties(propertyCount); VK_CHECK(vkEnumerateInstanceExtensionProperties(NULL, &propertyCount, properties.data())); for (uint32_t i = 0; i < propertyCount; ++i) if (strcmp(name, properties[i].extensionName) == 0) return true; return false; } VkInstance createInstance() { if (volkGetInstanceVersion() < API_VERSION) { fprintf(stderr, "ERROR: Vulkan 1.%d instance not found\n", VK_VERSION_MINOR(API_VERSION)); return 0; } VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO }; appInfo.apiVersion = API_VERSION; VkInstanceCreateInfo createInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO }; createInfo.pApplicationInfo = &appInfo; #if KHR_VALIDATION || SYNC_VALIDATION const char* debugLayers[] = { "VK_LAYER_KHRONOS_validation", }; if (isLayerSupported("VK_LAYER_KHRONOS_validation")) { createInfo.ppEnabledLayerNames = debugLayers; createInfo.enabledLayerCount = sizeof(debugLayers) / sizeof(debugLayers[0]); printf("Enabled Vulkan validation layers (sync validation %s)\n", SYNC_VALIDATION ? "enabled" : "disabled"); } else { printf("Warning: Vulkan debug layers are not available\n"); } #if SYNC_VALIDATION VkValidationFeatureEnableEXT enabledValidationFeatures[] = { VK_VALIDATION_FEATURE_ENABLE_SYNCHRONIZATION_VALIDATION_EXT, }; VkValidationFeaturesEXT validationFeatures = { VK_STRUCTURE_TYPE_VALIDATION_FEATURES_EXT }; validationFeatures.enabledValidationFeatureCount = sizeof(enabledValidationFeatures) / sizeof(enabledValidationFeatures[0]); validationFeatures.pEnabledValidationFeatures = enabledValidationFeatures; createInfo.pNext = &validationFeatures; #endif #endif std::vector<const char*> extensions; // Query Vulkan instance extensions required by GLFW for creating Vulkan surfaces for GLFW windows. uint32_t swapchainExtensionCount; if (const char** swapchainExtensions = getSwapchainExtensions(&swapchainExtensionCount)) extensions.insert(extensions.end(), swapchainExtensions, swapchainExtensions + swapchainExtensionCount); if (isInstanceExtensionSupported(VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); createInfo.ppEnabledExtensionNames = extensions.data(); createInfo.enabledExtensionCount = extensions.size(); #ifdef VK_USE_PLATFORM_METAL_EXT createInfo.flags |= VK_INSTANCE_CREATE_ENUMERATE_PORTABILITY_BIT_KHR; #endif VkInstance instance = 0; VK_CHECK(vkCreateInstance(&createInfo, 0, &instance)); return instance; } static VkBool32 VKAPI_CALL debugUtilsCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT types, const VkDebugUtilsMessengerCallbackDataEXT* callbackData, void* userData) { if (severity < VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) return VK_FALSE; // Works around https://github.com/KhronosGroup/Vulkan-Docs/issues/2677 - unclear if we'll need a deeper fix if (strstr(callbackData->pMessage, "VUID-RuntimeSpirv-MeshEXT-10883")) return VK_FALSE; const char* type = (severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) ? "ERROR" : "WARNING"; char message[4096]; snprintf(message, COUNTOF(message), "%s: %s\n", type, callbackData->pMessage); printf("%s", message); #ifdef _WIN32 OutputDebugStringA(message); #endif if (severity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) assert(!"Validation error encountered!"); return VK_FALSE; } VkDebugUtilsMessengerEXT registerDebugCallback(VkInstance instance) { if (!vkCreateDebugUtilsMessengerEXT) return nullptr; VkDebugUtilsMessengerCreateInfoEXT createInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT }; createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; createInfo.pfnUserCallback = debugUtilsCallback; VkDebugUtilsMessengerEXT messenger = 0; VK_CHECK(vkCreateDebugUtilsMessengerEXT(instance, &createInfo, 0, &messenger)); return messenger; } uint32_t getGraphicsFamilyIndex(VkPhysicalDevice physicalDevice) { uint32_t queueCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, 0); std::vector<VkQueueFamilyProperties> queues(queueCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueCount, queues.data()); for (uint32_t i = 0; i < queueCount; ++i) if (queues[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) return i; return VK_QUEUE_FAMILY_IGNORED; } static bool supportsPresentation(VkPhysicalDevice physicalDevice, uint32_t familyIndex) { #if defined(VK_USE_PLATFORM_WIN32_KHR) return !!vkGetPhysicalDeviceWin32PresentationSupportKHR(physicalDevice, familyIndex); #else return true; #endif } VkPhysicalDevice pickPhysicalDevice(VkPhysicalDevice* physicalDevices, uint32_t physicalDeviceCount) { VkPhysicalDevice preferred = 0; VkPhysicalDevice fallback = 0; const char* ngpu = getenv("NGPU"); for (uint32_t i = 0; i < physicalDeviceCount; ++i) { VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(physicalDevices[i], &props); if (props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) continue; printf("GPU%d: %s (Vulkan 1.%d)\n", i, props.deviceName, VK_VERSION_MINOR(props.apiVersion)); uint32_t familyIndex = getGraphicsFamilyIndex(physicalDevices[i]); if (familyIndex == VK_QUEUE_FAMILY_IGNORED) continue; if (!supportsPresentation(physicalDevices[i], familyIndex)) continue; if (props.apiVersion < API_VERSION) continue; if (ngpu && atoi(ngpu) == i) { preferred = physicalDevices[i]; } if (!preferred && props.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) { preferred = physicalDevices[i]; } if (!fallback) { fallback = physicalDevices[i]; } } VkPhysicalDevice result = preferred ? preferred : fallback; if (result) { VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(result, &props); printf("Selected GPU %s\n", props.deviceName); } else { fprintf(stderr, "ERROR: No compatible GPU found\n"); } return result; } VkDevice createDevice(VkInstance instance, VkPhysicalDevice physicalDevice, uint32_t familyIndex, bool meshShadingSupported, bool raytracingSupported, bool clusterrtSupported, bool descheapSupported) { float queuePriorities[] = { 1.0f }; VkDeviceQueueCreateInfo queueInfo = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO }; queueInfo.queueFamilyIndex = familyIndex; queueInfo.queueCount = 1; queueInfo.pQueuePriorities = queuePriorities; std::vector<const char*> extensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME, }; if (meshShadingSupported) extensions.push_back(VK_EXT_MESH_SHADER_EXTENSION_NAME); if (raytracingSupported) { extensions.push_back(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); extensions.push_back(VK_KHR_RAY_QUERY_EXTENSION_NAME); extensions.push_back(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); } #ifdef VK_NV_cluster_acceleration_structure if (clusterrtSupported) extensions.push_back(VK_NV_CLUSTER_ACCELERATION_STRUCTURE_EXTENSION_NAME); #endif #ifdef VK_EXT_descriptor_heap if (descheapSupported) extensions.push_back(VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME); #endif VkPhysicalDeviceFeatures2 features = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2 }; features.features.multiDrawIndirect = true; features.features.pipelineStatisticsQuery = true; features.features.shaderInt16 = true; features.features.shaderInt64 = true; features.features.samplerAnisotropy = true; VkPhysicalDeviceVulkan11Features features11 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES }; features11.storageBuffer16BitAccess = true; features11.shaderDrawParameters = true; VkPhysicalDeviceVulkan12Features features12 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES }; features12.drawIndirectCount = true; features12.storageBuffer8BitAccess = true; features12.uniformAndStorageBuffer8BitAccess = true; features12.shaderFloat16 = true; features12.shaderInt8 = true; features12.samplerFilterMinmax = true; features12.scalarBlockLayout = true; // required for raytracing & descriptor heaps features12.bufferDeviceAddress = true; features12.descriptorIndexing = true; features12.shaderSampledImageArrayNonUniformIndexing = true; features12.descriptorBindingSampledImageUpdateAfterBind = true; features12.descriptorBindingUpdateUnusedWhilePending = true; features12.descriptorBindingPartiallyBound = true; features12.descriptorBindingVariableDescriptorCount = true; features12.runtimeDescriptorArray = true; VkPhysicalDeviceVulkan13Features features13 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES }; features13.dynamicRendering = true; features13.synchronization2 = true; features13.maintenance4 = true; features13.shaderDemoteToHelperInvocation = true; // required for discard; under new glslang rules VkPhysicalDeviceVulkan14Features features14 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_4_FEATURES }; features14.maintenance5 = true; features14.maintenance6 = true; features14.pushDescriptor = true; // This will only be used if meshShadingSupported=true (see below) VkPhysicalDeviceMeshShaderFeaturesEXT featuresMesh = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT }; featuresMesh.taskShader = true; featuresMesh.meshShader = true; // This will only be used if raytracingSupported=true (see below) VkPhysicalDeviceRayQueryFeaturesKHR featuresRayQueries = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR }; featuresRayQueries.rayQuery = true; // This will only be used if raytracingSupported=true (see below) VkPhysicalDeviceAccelerationStructureFeaturesKHR featuresAccelerationStructure = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR }; featuresAccelerationStructure.accelerationStructure = true; // This will only be used if clusterrtSupported=true (see below) VkPhysicalDeviceClusterAccelerationStructureFeaturesNV featuresClusterAcceleration = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CLUSTER_ACCELERATION_STRUCTURE_FEATURES_NV }; featuresClusterAcceleration.clusterAccelerationStructure = true; #if VK_EXT_descriptor_heap // This will only be used if descheapSupported=true (see below) VkPhysicalDeviceDescriptorHeapFeaturesEXT featuresDescriptorHeap = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_FEATURES_EXT }; featuresDescriptorHeap.descriptorHeap = true; #endif VkDeviceCreateInfo createInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO }; createInfo.queueCreateInfoCount = 1; createInfo.pQueueCreateInfos = &queueInfo; createInfo.ppEnabledExtensionNames = extensions.data(); createInfo.enabledExtensionCount = uint32_t(extensions.size()); createInfo.pNext = &features; features.pNext = &features11; features11.pNext = &features12; features12.pNext = &features13; features13.pNext = &features14; void** ppNext = &features14.pNext; if (meshShadingSupported) { *ppNext = &featuresMesh; ppNext = &featuresMesh.pNext; } if (raytracingSupported) { *ppNext = &featuresRayQueries; ppNext = &featuresRayQueries.pNext; *ppNext = &featuresAccelerationStructure; ppNext = &featuresAccelerationStructure.pNext; } if (clusterrtSupported) { *ppNext = &featuresClusterAcceleration; ppNext = &featuresClusterAcceleration.pNext; } #if VK_EXT_descriptor_heap if (descheapSupported) { *ppNext = &featuresDescriptorHeap; ppNext = &featuresDescriptorHeap.pNext; } #endif VkDevice device = 0; VK_CHECK(vkCreateDevice(physicalDevice, &createInfo, 0, &device)); return device; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/device.h
C/C++ Header
#pragma once bool isInstanceExtensionSupported(const char* name); VkInstance createInstance(); VkDebugUtilsMessengerEXT registerDebugCallback(VkInstance instance); uint32_t getGraphicsFamilyIndex(VkPhysicalDevice physicalDevice); VkPhysicalDevice pickPhysicalDevice(VkPhysicalDevice* physicalDevices, uint32_t physicalDeviceCount); VkDevice createDevice(VkInstance instance, VkPhysicalDevice physicalDevice, uint32_t familyIndex, bool meshShadingSupported, bool raytracingSupported, bool clusterrtSupported, bool descheapSupported);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/extern.cpp
C++
#define FAST_OBJ_IMPLEMENTATION #include "fast_obj.h" #define CGLTF_IMPLEMENTATION #include "cgltf.h"
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/fileutils.cpp
C++
#include "fileutils.h" #include <assert.h> #include <stdint.h> #ifdef _WIN32 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <Windows.h> #else #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #endif #ifdef _WIN32 void* mmapFile(const char* path, size_t* outSize) { *outSize = 0; HANDLE file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, // allow others to read NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (file == INVALID_HANDLE_VALUE) return NULL; LARGE_INTEGER liSize; if (!GetFileSizeEx(file, &liSize) || liSize.QuadPart == 0 || liSize.QuadPart > SIZE_MAX) { CloseHandle(file); return NULL; } HANDLE map = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, NULL); if (!map) { CloseHandle(file); return NULL; } void* view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0); // safe to close mapping handle & file handle after mapping the view; the kernel keeps track of the association via the mapped pointer CloseHandle(map); CloseHandle(file); if (!view) return NULL; *outSize = size_t(liSize.QuadPart); return view; } void unmapFile(void* data, size_t size) { (void)size; BOOL ok = UnmapViewOfFile(data); assert(ok); (void)ok; } #else void* mmapFile(const char* path, size_t* outSize) { *outSize = 0; int fd = open(path, O_RDONLY); if (fd == -1) return NULL; struct stat sb; if (fstat(fd, &sb) == -1 || sb.st_size == 0 || sb.st_size > SIZE_MAX) { close(fd); return NULL; } void* mapped = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (mapped == MAP_FAILED) { close(fd); return NULL; } close(fd); *outSize = sb.st_size; return mapped; } void unmapFile(void* data, size_t size) { int rc = munmap(data, size); assert(rc == 0); (void)rc; } #endif
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/fileutils.h
C/C++ Header
#include <stddef.h> void* mmapFile(const char* path, size_t* outSize); void unmapFile(void* data, size_t size);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/math.h
C/C++ Header
#pragma once #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat2x2.hpp> #include <glm/mat3x3.hpp> #include <glm/mat4x4.hpp> #include <glm/ext/quaternion_float.hpp> #include <glm/ext/quaternion_transform.hpp> #include <glm/gtc/quaternion.hpp> using glm::mat2; using glm::mat3; using glm::mat4; using glm::quat; using glm::vec2; using glm::vec3; using glm::vec4;
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/niagara.cpp
C++
#include "common.h" #include "device.h" #include "resources.h" #include "textures.h" #include "shaders.h" #include "swapchain.h" #include "config.h" #include "math.h" #include "scene.h" #include "scenert.h" #include <stdarg.h> #include <stdio.h> #include <string.h> #include <algorithm> #include <string> #include <vector> #include <GLFW/glfw3.h> #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif bool meshShadingEnabled = true; bool cullingEnabled = true; bool lodEnabled = true; bool occlusionEnabled = true; bool clusterOcclusionEnabled = true; bool taskShadingEnabled = false; // disabled to have good performance on AMD HW bool shadowsEnabled = true; bool shadowblurEnabled = true; bool shadowCheckerboard = false; int shadowQuality = 1; bool animationEnabled = false; int debugGuiMode = 1; int debugLodStep = 0; bool debugSleep = false; bool reloadShaders = false; uint32_t reloadShadersColor = 0xffffffff; double reloadShadersTimer = 0; VkSemaphore createSemaphore(VkDevice device) { VkSemaphoreCreateInfo createInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO }; VkSemaphore semaphore = 0; VK_CHECK(vkCreateSemaphore(device, &createInfo, 0, &semaphore)); return semaphore; } VkFence createFence(VkDevice device) { VkFenceCreateInfo createInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO }; VkFence fence = 0; VK_CHECK(vkCreateFence(device, &createInfo, 0, &fence)); return fence; } VkCommandPool createCommandPool(VkDevice device, uint32_t familyIndex) { VkCommandPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO }; createInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT; createInfo.queueFamilyIndex = familyIndex; VkCommandPool commandPool = 0; VK_CHECK(vkCreateCommandPool(device, &createInfo, 0, &commandPool)); return commandPool; } VkQueryPool createQueryPool(VkDevice device, uint32_t queryCount, VkQueryType queryType) { VkQueryPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO }; createInfo.queryType = queryType; createInfo.queryCount = queryCount; if (queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) { createInfo.pipelineStatistics = VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT; } VkQueryPool queryPool = 0; VK_CHECK(vkCreateQueryPool(device, &createInfo, 0, &queryPool)); return queryPool; } struct FrameDescriptors { VkDevice device; void* descriptorHeap; size_t descriptorSize; uint32_t descriptorOffset; uint32_t descriptorOffsetEnd; }; template <typename PushConstants> void pushConstants(VkCommandBuffer commandBuffer, FrameDescriptors& framedesc, const Program& program, const PushConstants& constants) { assert(program.pushConstantSize == sizeof(constants)); if (program.descriptorSize) { #if VK_EXT_descriptor_heap VkPushDataInfoEXT pushDataInfo = { VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT }; pushDataInfo.data.address = &constants; pushDataInfo.data.size = sizeof(constants); vkCmdPushDataEXT(commandBuffer, &pushDataInfo); #endif } else vkCmdPushConstants(commandBuffer, program.layout, program.pushConstantStages, 0, sizeof(constants), &constants); } template <size_t PushDescriptors> void pushDescriptors(VkCommandBuffer commandBuffer, FrameDescriptors& framedesc, const Program& program, const DescriptorInfo (&descriptors)[PushDescriptors]) { assert(program.pushDescriptorCount == PushDescriptors); if (program.descriptorSize) { #if VK_EXT_descriptor_heap assert(framedesc.descriptorOffset + program.pushDescriptorCount <= framedesc.descriptorOffsetEnd); uint32_t descriptorOffset = framedesc.descriptorOffset; VkPushDataInfoEXT pushDataInfo = { VK_STRUCTURE_TYPE_PUSH_DATA_INFO_EXT }; pushDataInfo.offset = program.pushConstantSize; pushDataInfo.data.address = &descriptorOffset; pushDataInfo.data.size = sizeof(descriptorOffset); vkCmdPushDataEXT(commandBuffer, &pushDataInfo); for (int i = 0; i < 32; ++i) if (program.resourceMask & (1 << i)) { const DescriptorInfo& info = descriptors[i]; char descriptor[128]; switch (program.resourceTypes[i]) { case VK_DESCRIPTOR_TYPE_SAMPLER: { // mapped via constant offsets... sloppily continue; } case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: { const Image* image = static_cast<const Image*>(info.resource); assert(image); uint32_t mipLevel = (info.resourceMip < 0) ? 0 : uint32_t(info.resourceMip); uint32_t levelCount = (info.resourceMip < 0) ? VK_REMAINING_MIP_LEVELS : 1; getDescriptor(framedesc.device, image->image, image->format, mipLevel, levelCount, program.resourceTypes[i], descriptor, framedesc.descriptorSize); break; } case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: { const Buffer* buffer = static_cast<const Buffer*>(info.resource); assert(buffer); getDescriptor(framedesc.device, buffer->address, buffer->size, program.resourceTypes[i], descriptor, framedesc.descriptorSize); break; } case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: { VkAccelerationStructureDeviceAddressInfoKHR addressInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR }; addressInfo.accelerationStructure = info.accelerationStructure; VkDeviceAddress address = vkGetAccelerationStructureDeviceAddressKHR(framedesc.device, &addressInfo); getDescriptor(framedesc.device, address, 0, program.resourceTypes[i], descriptor, framedesc.descriptorSize); break; } default: assert(!"Unsupported descriptor type"); } memcpy(static_cast<char*>(framedesc.descriptorHeap) + (framedesc.descriptorOffset + i) * framedesc.descriptorSize, descriptor, framedesc.descriptorSize); } framedesc.descriptorOffset += program.pushDescriptorCount; #endif } else vkCmdPushDescriptorSetWithTemplate(commandBuffer, program.updateTemplate, program.layout, 0, descriptors); } template <typename PushConstants, size_t PushDescriptors> void dispatch(VkCommandBuffer commandBuffer, FrameDescriptors& framedesc, const Program& program, uint32_t threadCountX, uint32_t threadCountY, const PushConstants& constants, const DescriptorInfo (&descriptors)[PushDescriptors]) { assert(program.pushConstantSize == sizeof(constants)); assert(program.pushDescriptorCount == PushDescriptors); pushConstants(commandBuffer, framedesc, program, constants); if (program.pushDescriptorCount) pushDescriptors(commandBuffer, framedesc, program, descriptors); vkCmdDispatch(commandBuffer, getGroupCount(threadCountX, program.localSizeX), getGroupCount(threadCountY, program.localSizeY), 1); } struct MeshDrawCommand { uint32_t drawId; VkDrawIndexedIndirectCommand indirect; // 5 uint32_t }; struct MeshTaskCommand { uint32_t drawId; uint32_t taskOffset; uint32_t taskCount; uint32_t lateDrawVisibility; uint32_t meshletVisibilityOffset; }; struct alignas(16) CullData { mat4 view; float P00, P11, znear, zfar; // symmetric projection parameters float frustum[4]; // data for left/right/top/bottom frustum planes float lodTarget; // lod target error at z=1 float pyramidWidth, pyramidHeight; // depth pyramid size in texels uint32_t drawCount; int cullingEnabled; int lodEnabled; int occlusionEnabled; int clusterOcclusionEnabled; int clusterBackfaceEnabled; uint32_t postPass; }; struct alignas(16) Globals { mat4 projection; CullData cullData; float screenWidth, screenHeight; }; struct alignas(16) ShadowData { vec3 sunDirection; float sunJitter; mat4 inverseViewProjection; vec2 imageSize; unsigned int checkerboard; }; struct alignas(16) ShadeData { vec3 cameraPosition; float pad0; vec3 sunDirection; int shadowsEnabled; mat4 inverseViewProjection; vec2 imageSize; }; struct alignas(16) TextData { int offsetX, offsetY; int scale; unsigned int color; char data[112]; }; DescriptorInfo::DescriptorInfo(const struct Buffer& buffer) : DescriptorInfo(buffer.buffer) { resource = &buffer; } DescriptorInfo::DescriptorInfo(const struct Image& image) : DescriptorInfo(image.imageView) { resource = &image; } DescriptorInfo::DescriptorInfo(const struct Image& image, VkImageView mipView, int mipIndex) : DescriptorInfo(mipView) { resource = &image; resourceMip = mipIndex; } void errorCallback(int error_code, const char* description) { fprintf(stderr, "GLFW ERROR (%d): %s\n", error_code, description); } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { if (key == GLFW_KEY_M) { meshShadingEnabled = !meshShadingEnabled; } if (key == GLFW_KEY_C) { cullingEnabled = !cullingEnabled; } if (key == GLFW_KEY_O) { occlusionEnabled = !occlusionEnabled; } if (key == GLFW_KEY_K) { clusterOcclusionEnabled = !clusterOcclusionEnabled; } if (key == GLFW_KEY_L) { lodEnabled = !lodEnabled; } if (key == GLFW_KEY_T) { taskShadingEnabled = !taskShadingEnabled; } if (key == GLFW_KEY_F) { shadowsEnabled = !shadowsEnabled; } if (key == GLFW_KEY_B) { shadowblurEnabled = !shadowblurEnabled; } if (key == GLFW_KEY_X) { shadowCheckerboard = !shadowCheckerboard; } if (key == GLFW_KEY_Q) { shadowQuality = 1 - shadowQuality; } if (key >= GLFW_KEY_0 && key <= GLFW_KEY_9) { debugLodStep = key - GLFW_KEY_0; } if (key == GLFW_KEY_R) { reloadShaders = !reloadShaders; reloadShadersTimer = 0; } if (key == GLFW_KEY_G) { debugGuiMode++; } if (key == GLFW_KEY_SPACE) { animationEnabled = !animationEnabled; } if (key == GLFW_KEY_Z) { debugSleep = !debugSleep; } if (key == GLFW_KEY_ESCAPE) { glfwSetWindowShouldClose(window, true); } } } void mouseCallback(GLFWwindow* window, int button, int action, int mods) { if (action == GLFW_PRESS && button == GLFW_MOUSE_BUTTON_RIGHT) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetCursorPos(window, 0, 0); } else if (action == GLFW_RELEASE && button == GLFW_MOUSE_BUTTON_RIGHT) { glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); } } mat4 perspectiveProjection(float fovY, float aspectWbyH, float zNear) { float f = 1.0f / tanf(fovY / 2.0f); return mat4( f / aspectWbyH, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, zNear, 0.0f); } vec4 normalizePlane(vec4 p) { return p / length(vec3(p)); } uint32_t previousPow2(uint32_t v) { uint32_t r = 1; while (r * 2 < v) r *= 2; return r; } struct pcg32_random_t { uint64_t state; uint64_t inc; }; #define PCG32_INITIALIZER \ { \ 0x853c49e6748fea9bULL, 0xda3e39cb94b95bdbULL \ } uint32_t pcg32_random_r(pcg32_random_t* rng) { uint64_t oldstate = rng->state; // Advance internal state rng->state = oldstate * 6364136223846793005ULL + (rng->inc | 1); // Calculate output function (XSH RR), uses old state for max ILP uint32_t xorshifted = uint32_t(((oldstate >> 18u) ^ oldstate) >> 27u); uint32_t rot = oldstate >> 59u; return (xorshifted >> rot) | (xorshifted << ((32 - rot) & 31)); } pcg32_random_t rngstate = PCG32_INITIALIZER; double rand01() { return pcg32_random_r(&rngstate) / double(1ull << 32); } uint32_t rand32() { return pcg32_random_r(&rngstate); } int main(int argc, const char** argv) { if (argc < 2) { printf("Usage: %s [mesh list]\n", argv[0]); return 1; } VK_CHECK(volkInitialize()); #ifdef __linux // If both Wayland & X11 are supported, GLFW will default to Wayland; ask it for X11 if we can't use Wayland extension (when launched via RenderDoc) if (!isInstanceExtensionSupported("VK_KHR_wayland_surface")) glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_X11); #endif glfwInitVulkanLoader(vkGetInstanceProcAddr); // used for glfwCreateWindowSurface glfwSetErrorCallback(errorCallback); int rc = glfwInit(); assert(rc); glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); VkInstance instance = createInstance(); if (!instance) return -1; volkLoadInstanceOnly(instance); VkDebugUtilsMessengerEXT debugCallback = registerDebugCallback(instance); VkPhysicalDevice physicalDevices[16]; uint32_t physicalDeviceCount = sizeof(physicalDevices) / sizeof(physicalDevices[0]); VK_CHECK(vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices)); VkPhysicalDevice physicalDevice = pickPhysicalDevice(physicalDevices, physicalDeviceCount); if (!physicalDevice) { if (debugCallback) vkDestroyDebugUtilsMessengerEXT(instance, debugCallback, 0); vkDestroyInstance(instance, 0); return -1; } uint32_t extensionCount = 0; VK_CHECK(vkEnumerateDeviceExtensionProperties(physicalDevice, 0, &extensionCount, 0)); std::vector<VkExtensionProperties> extensions(extensionCount); VK_CHECK(vkEnumerateDeviceExtensionProperties(physicalDevice, 0, &extensionCount, extensions.data())); bool meshShadingSupported = false; bool raytracingSupported = false; bool clusterrtSupported = false; bool descheapSupported = false; bool unifiedlayoutsSupported = false; for (auto& ext : extensions) { meshShadingSupported = meshShadingSupported || strcmp(ext.extensionName, VK_EXT_MESH_SHADER_EXTENSION_NAME) == 0; raytracingSupported = raytracingSupported || strcmp(ext.extensionName, VK_KHR_RAY_QUERY_EXTENSION_NAME) == 0; unifiedlayoutsSupported = unifiedlayoutsSupported || strcmp(ext.extensionName, "VK_KHR_unified_image_layouts") == 0; #ifdef VK_NV_cluster_acceleration_structure clusterrtSupported = clusterrtSupported || strcmp(ext.extensionName, VK_NV_CLUSTER_ACCELERATION_STRUCTURE_EXTENSION_NAME) == 0; #endif #ifdef VK_EXT_descriptor_heap descheapSupported = descheapSupported || strcmp(ext.extensionName, VK_EXT_DESCRIPTOR_HEAP_EXTENSION_NAME) == 0; #endif } if (!unifiedlayoutsSupported) printf("WARNING: KHR_unified_image_layouts is not supported; barrier setup may be inefficient\n"); if (descheapSupported) printf("WARNING: EXT_descriptor_heap support code is being used\n"); meshShadingEnabled = meshShadingSupported; VkPhysicalDeviceProperties2 props2 = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 }; #if VK_EXT_descriptor_heap VkPhysicalDeviceDescriptorHeapPropertiesEXT descheapProperties = { VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_HEAP_PROPERTIES_EXT }; if (descheapSupported) props2.pNext = &descheapProperties; #endif vkGetPhysicalDeviceProperties2(physicalDevice, &props2); #if VK_EXT_descriptor_heap size_t resourceDescriptorSize = std::max(descheapProperties.imageDescriptorSize, descheapProperties.bufferDescriptorSize); #else size_t resourceDescriptorSize = 0; #endif VkPhysicalDeviceProperties props = props2.properties; assert(props.limits.timestampComputeAndGraphics); uint32_t familyIndex = getGraphicsFamilyIndex(physicalDevice); assert(familyIndex != VK_QUEUE_FAMILY_IGNORED); VkDevice device = createDevice(instance, physicalDevice, familyIndex, meshShadingSupported, raytracingSupported, clusterrtSupported, descheapSupported); assert(device); volkLoadDevice(device); VkSemaphore acquireSemaphores[MAX_FRAMES] = {}; VkFence frameFences[MAX_FRAMES] = {}; for (int i = 0; i < MAX_FRAMES; ++i) { acquireSemaphores[i] = createSemaphore(device); frameFences[i] = createFence(device); assert(acquireSemaphores[i] && frameFences[i]); } VkQueue queue = 0; vkGetDeviceQueue(device, familyIndex, 0, &queue); VkSampler textureSampler = createSampler(device, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_REPEAT); VkSampler depthSampler = createSampler(device, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_REDUCTION_MODE_MIN); VkFormat depthFormat = VK_FORMAT_D32_SFLOAT; static const size_t gbufferCount = 2; const VkFormat gbufferFormats[gbufferCount] = { VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32, }; VkPipelineRenderingCreateInfo gbufferInfo = { VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO }; gbufferInfo.colorAttachmentCount = gbufferCount; gbufferInfo.pColorAttachmentFormats = gbufferFormats; gbufferInfo.depthAttachmentFormat = depthFormat; ShaderSet shaders; bool rcs = loadShaders(shaders, argv[0], "spirv/"); assert(rcs); VkDescriptorSetLayout textureSetLayout = createDescriptorArrayLayout(device); VkPipelineCache pipelineCache = 0; Program debugtextProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["debugtext.comp"] }, sizeof(TextData), resourceDescriptorSize); Program drawcullProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["drawcull.comp"] }, sizeof(CullData)); Program tasksubmitProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["tasksubmit.comp"] }, 0); Program clustersubmitProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["clustersubmit.comp"] }, 0); Program clustercullProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["clustercull.comp"] }, sizeof(CullData)); Program depthreduceProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["depthreduce.comp"] }, sizeof(vec4)); Program meshProgram = createProgram(device, VK_PIPELINE_BIND_POINT_GRAPHICS, { &shaders["mesh.vert"], &shaders["mesh.frag"] }, sizeof(Globals), 0, textureSetLayout); Program meshtaskProgram = {}; Program clusterProgram = {}; if (meshShadingSupported) { meshtaskProgram = createProgram(device, VK_PIPELINE_BIND_POINT_GRAPHICS, { &shaders["meshlet.task"], &shaders["meshlet.mesh"], &shaders["mesh.frag"] }, sizeof(Globals), 0, textureSetLayout); clusterProgram = createProgram(device, VK_PIPELINE_BIND_POINT_GRAPHICS, { &shaders["meshlet.mesh"], &shaders["mesh.frag"] }, sizeof(Globals), 0, textureSetLayout); } Program finalProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["final.comp"] }, sizeof(ShadeData), resourceDescriptorSize); Program shadowProgram = {}; Program shadowfillProgram = {}; Program shadowblurProgram = {}; if (raytracingSupported) { shadowProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["shadow.comp"] }, sizeof(ShadowData), 0, textureSetLayout); shadowfillProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["shadowfill.comp"] }, sizeof(vec4)); shadowblurProgram = createProgram(device, VK_PIPELINE_BIND_POINT_COMPUTE, { &shaders["shadowblur.comp"] }, sizeof(vec4)); } VkPipeline debugtextPipeline = 0; VkPipeline drawcullPipeline = 0; VkPipeline drawculllatePipeline = 0; VkPipeline taskcullPipeline = 0; VkPipeline taskculllatePipeline = 0; VkPipeline tasksubmitPipeline = 0; VkPipeline clustersubmitPipeline = 0; VkPipeline clustercullPipeline = 0; VkPipeline clusterculllatePipeline = 0; VkPipeline depthreducePipeline = 0; VkPipeline meshPipeline = 0; VkPipeline meshpostPipeline = 0; VkPipeline meshtaskPipeline = 0; VkPipeline meshtasklatePipeline = 0; VkPipeline meshtaskpostPipeline = 0; VkPipeline clusterPipeline = 0; VkPipeline clusterpostPipeline = 0; VkPipeline blitPipeline = 0; VkPipeline finalPipeline = 0; VkPipeline shadowlqPipeline = 0; VkPipeline shadowhqPipeline = 0; VkPipeline shadowfillPipeline = 0; VkPipeline shadowblurPipeline = 0; std::vector<VkPipeline> pipelines; auto createPipelines = [&]() { auto replace = [&](VkPipeline& pipeline, VkPipeline newPipeline) { if (pipeline) vkDestroyPipeline(device, pipeline, 0); assert(newPipeline); pipeline = newPipeline; pipelines.push_back(newPipeline); }; pipelines.clear(); replace(debugtextPipeline, createComputePipeline(device, pipelineCache, debugtextProgram)); replace(drawcullPipeline, createComputePipeline(device, pipelineCache, drawcullProgram, { /* LATE= */ false, /* TASK= */ false })); replace(drawculllatePipeline, createComputePipeline(device, pipelineCache, drawcullProgram, { /* LATE= */ true, /* TASK= */ false })); replace(taskcullPipeline, createComputePipeline(device, pipelineCache, drawcullProgram, { /* LATE= */ false, /* TASK= */ true })); replace(taskculllatePipeline, createComputePipeline(device, pipelineCache, drawcullProgram, { /* LATE= */ true, /* TASK= */ true })); replace(tasksubmitPipeline, createComputePipeline(device, pipelineCache, tasksubmitProgram)); replace(clustersubmitPipeline, createComputePipeline(device, pipelineCache, clustersubmitProgram)); replace(clustercullPipeline, createComputePipeline(device, pipelineCache, clustercullProgram, { /* LATE= */ false })); replace(clusterculllatePipeline, createComputePipeline(device, pipelineCache, clustercullProgram, { /* LATE= */ true })); replace(depthreducePipeline, createComputePipeline(device, pipelineCache, depthreduceProgram)); replace(meshPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, meshProgram)); replace(meshpostPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, meshProgram, { /* LATE= */ false, /* TASK= */ false, /* POST= */ 1 })); if (meshShadingSupported) { replace(meshtaskPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, meshtaskProgram, { /* LATE= */ false, /* TASK= */ true })); replace(meshtasklatePipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, meshtaskProgram, { /* LATE= */ true, /* TASK= */ true })); replace(meshtaskpostPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, meshtaskProgram, { /* LATE= */ true, /* TASK= */ true, /* POST= */ 1 })); replace(clusterPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, clusterProgram, { /* LATE= */ false, /* TASK= */ false })); replace(clusterpostPipeline, createGraphicsPipeline(device, pipelineCache, gbufferInfo, clusterProgram, { /* LATE= */ false, /* TASK= */ false, /* POST= */ 1 })); } replace(finalPipeline, createComputePipeline(device, pipelineCache, finalProgram)); if (raytracingSupported) { replace(shadowlqPipeline, createComputePipeline(device, pipelineCache, shadowProgram, { /* QUALITY= */ 0 })); replace(shadowhqPipeline, createComputePipeline(device, pipelineCache, shadowProgram, { /* QUALITY= */ 1 })); replace(shadowfillPipeline, createComputePipeline(device, pipelineCache, shadowfillProgram)); replace(shadowblurPipeline, createComputePipeline(device, pipelineCache, shadowblurProgram)); } }; createPipelines(); VkQueryPool queryPoolsTimestamp[MAX_FRAMES] = {}; VkQueryPool queryPoolsPipeline[MAX_FRAMES] = {}; for (int i = 0; i < MAX_FRAMES; ++i) { queryPoolsTimestamp[i] = createQueryPool(device, 128, VK_QUERY_TYPE_TIMESTAMP); queryPoolsPipeline[i] = createQueryPool(device, 4, VK_QUERY_TYPE_PIPELINE_STATISTICS); assert(queryPoolsTimestamp[i] && queryPoolsPipeline[i]); } VkCommandPool commandPools[MAX_FRAMES] = {}; VkCommandBuffer commandBuffers[MAX_FRAMES] = {}; for (int i = 0; i < MAX_FRAMES; ++i) { commandPools[i] = createCommandPool(device, familyIndex); assert(commandPools[i]); VkCommandBufferAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO }; allocateInfo.commandPool = commandPools[i]; allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocateInfo.commandBufferCount = 1; VK_CHECK(vkAllocateCommandBuffers(device, &allocateInfo, &commandBuffers[i])); } VkPhysicalDeviceMemoryProperties memoryProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties); #if VK_EXT_descriptor_heap Buffer resourceHeap = {}; Buffer samplerHeap = {}; if (descheapSupported) { size_t resourceDescriptorCount = DESCRIPTOR_LIMIT + MAX_FRAMES * DESCRIPTOR_LIMIT_FRAME; createBuffer(resourceHeap, device, memoryProperties, resourceDescriptorCount * resourceDescriptorSize + descheapProperties.minResourceHeapReservedRange, VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); createBuffer(samplerHeap, device, memoryProperties, DESCRIPTOR_LIMIT_SAMPLERS * descheapProperties.samplerDescriptorSize + descheapProperties.minSamplerHeapReservedRange, VK_BUFFER_USAGE_DESCRIPTOR_HEAP_BIT_EXT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); // fill sampler[0] with texture sampler and sampler[1] with depth sampler getDescriptor(device, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_LINEAR, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE, static_cast<char*>(samplerHeap.data) + 0 * descheapProperties.samplerDescriptorSize, descheapProperties.samplerDescriptorSize); getDescriptor(device, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_NEAREST, VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, VK_SAMPLER_REDUCTION_MODE_MIN, static_cast<char*>(samplerHeap.data) + 1 * descheapProperties.samplerDescriptorSize, descheapProperties.samplerDescriptorSize); } #endif Buffer scratch = {}; createBuffer(scratch, device, memoryProperties, 128 * 1024 * 1024, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); Geometry geometry; std::vector<Material> materials; std::vector<MeshDraw> draws; std::vector<Animation> animations; std::vector<std::string> texturePaths; // material index 0 is always dummy materials.resize(1); materials[0].diffuseFactor = vec4(1); Camera camera; camera.position = { 0.0f, 0.0f, 0.0f }; camera.orientation = { 0.0f, 0.0f, 0.0f, 1.0f }; camera.fovY = glm::radians(70.f); camera.znear = 0.1f; vec3 sunDirection = normalize(vec3(1.0f, 1.0f, 1.0f)); bool sceneMode = false; bool fastMode = getenv("FAST") && atoi(getenv("FAST")); bool clrtMode = getenv("CLRT") && atoi(getenv("CLRT")); bool compressed = !getenv("COMPRESSED") || atoi(getenv("COMPRESSED")); // enabled by default bool verbose = getenv("VERBOSE") && atoi(getenv("VERBOSE")); if (argc == 2) { const char* ext = strrchr(argv[1], '.'); if (ext && (strcmp(ext, ".gltf") == 0 || strcmp(ext, ".glb") == 0)) { std::string cachePath = std::string(argv[1]) + ".cache"; double sceneTimer = glfwGetTime(); if (!loadSceneCache(cachePath.c_str(), geometry, materials, draws, texturePaths, camera, sunDirection, clrtMode)) { printf("Loading scene from %s\n", argv[1]); if (!loadScene(geometry, materials, draws, texturePaths, animations, camera, sunDirection, argv[1], /* buildMeshlets= */ true, /* fastMode= */ false, clrtMode)) { printf("Error: scene %s failed to load\n", argv[1]); return 1; } if (!saveSceneCache(cachePath.c_str(), geometry, materials, draws, texturePaths, camera, sunDirection, clrtMode, compressed, verbose)) { printf("Error: scene cache %s failed to save\n", cachePath.c_str()); return 1; } } else { printf("Loaded scene from cache %s in %.2f sec\n", cachePath.c_str(), glfwGetTime() - sceneTimer); } sceneMode = true; } } VkCommandPool initCommandPool = commandPools[0]; VkCommandBuffer initCommandBuffer = commandBuffers[0]; std::vector<Image> images; size_t imageMemory = 0; double imageTimer = glfwGetTime(); for (size_t i = 0; i < texturePaths.size(); ++i) { Image image; if (!loadImage(image, device, initCommandPool, initCommandBuffer, queue, memoryProperties, scratch, texturePaths[i].c_str())) { printf("Error: image %s failed to load\n", texturePaths[i].c_str()); return 1; } VkMemoryRequirements memoryRequirements = {}; vkGetImageMemoryRequirements(device, image.image, &memoryRequirements); imageMemory += memoryRequirements.size; images.push_back(image); } printf("Loaded %d textures (%.2f MB) in %.2f sec\n", int(images.size()), double(imageMemory) / 1e6, glfwGetTime() - imageTimer); uint32_t descriptorCount = uint32_t(texturePaths.size() + 1); std::pair<VkDescriptorPool, VkDescriptorSet> textureSet = createDescriptorArray(device, textureSetLayout, descriptorCount); for (size_t i = 0; i < texturePaths.size(); ++i) { VkDescriptorImageInfo imageInfo = {}; imageInfo.imageView = images[i].imageView; imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkWriteDescriptorSet write = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET }; write.dstSet = textureSet.second; write.dstBinding = 0; write.dstArrayElement = uint32_t(i + 1); write.descriptorCount = 1; write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; write.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &write, 0, nullptr); if (descheapSupported) getDescriptor(device, images[i].image, images[i].format, 0, VK_REMAINING_MIP_LEVELS, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, static_cast<char*>(resourceHeap.data) + (1 + i) * resourceDescriptorSize, resourceDescriptorSize); } if (!sceneMode) { for (int i = 1; i < argc; ++i) { if (!loadMesh(geometry, argv[i], meshShadingSupported, fastMode, clrtMode)) { printf("Error: mesh %s failed to load\n", argv[i]); return 1; } } } if (geometry.meshes.empty()) { printf("Error: no meshes loaded!\n"); return 1; } printf("Geometry: VB %.2f MB, IB %.2f MB, meshlets %.2f MB\n", double(geometry.vertices.size() * sizeof(Vertex)) / 1e6, double(geometry.indices.size() * sizeof(uint32_t)) / 1e6, double(geometry.meshlets.size() * sizeof(Meshlet) + geometry.meshletdata.size() * sizeof(uint32_t)) / 1e6); if (draws.empty()) { rngstate.state = 0x42; uint32_t drawCount = 1000000; draws.resize(drawCount); float sceneRadius = 300; for (uint32_t i = 0; i < drawCount; ++i) { MeshDraw& draw = draws[i]; size_t meshIndex = rand32() % geometry.meshes.size(); const Mesh& mesh = geometry.meshes[meshIndex]; draw.position[0] = float(rand01()) * sceneRadius * 2 - sceneRadius; draw.position[1] = float(rand01()) * sceneRadius * 2 - sceneRadius; draw.position[2] = float(rand01()) * sceneRadius * 2 - sceneRadius; draw.scale = float(rand01()) + 1; draw.scale *= 2; vec3 axis = normalize(vec3(float(rand01()) * 2 - 1, float(rand01()) * 2 - 1, float(rand01()) * 2 - 1)); float angle = glm::radians(float(rand01()) * 90.f); draw.orientation = quat(cosf(angle * 0.5f), axis * sinf(angle * 0.5f)); draw.meshIndex = uint32_t(meshIndex); } } float drawDistance = 200; uint32_t meshletVisibilityCount = 0; uint32_t meshPostPasses = 0; for (size_t i = 0; i < draws.size(); ++i) { MeshDraw& draw = draws[i]; const Mesh& mesh = geometry.meshes[draw.meshIndex]; draw.meshletVisibilityOffset = meshletVisibilityCount; uint32_t meshletCount = 0; for (uint32_t i = 0; i < mesh.lodCount; ++i) meshletCount = std::max(meshletCount, mesh.lods[i].meshletCount); meshletVisibilityCount += meshletCount; meshPostPasses |= 1 << draw.postPass; } uint32_t meshletVisibilityBytes = (meshletVisibilityCount + 31) / 32 * sizeof(uint32_t); uint32_t raytracingBufferFlags = raytracingSupported ? VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0; Buffer mb = {}; createBuffer(mb, device, memoryProperties, geometry.meshes.size() * sizeof(Mesh), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer mtb = {}; createBuffer(mtb, device, memoryProperties, materials.size() * sizeof(Material), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer vb = {}; createBuffer(vb, device, memoryProperties, geometry.vertices.size() * sizeof(Vertex), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | raytracingBufferFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer ib = {}; createBuffer(ib, device, memoryProperties, geometry.indices.size() * sizeof(uint32_t), VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | raytracingBufferFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer mlb = {}; Buffer mdb = {}; if (meshShadingSupported) { createBuffer(mlb, device, memoryProperties, geometry.meshlets.size() * sizeof(Meshlet), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); createBuffer(mdb, device, memoryProperties, geometry.meshletdata.size() * sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | raytracingBufferFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } uploadBuffer(device, initCommandPool, initCommandBuffer, queue, mb, scratch, geometry.meshes.data(), geometry.meshes.size() * sizeof(Mesh)); uploadBuffer(device, initCommandPool, initCommandBuffer, queue, mtb, scratch, materials.data(), materials.size() * sizeof(Material)); uploadBuffer(device, initCommandPool, initCommandBuffer, queue, vb, scratch, geometry.vertices.data(), geometry.vertices.size() * sizeof(Vertex)); uploadBuffer(device, initCommandPool, initCommandBuffer, queue, ib, scratch, geometry.indices.data(), geometry.indices.size() * sizeof(uint32_t)); if (meshShadingSupported) { uploadBuffer(device, initCommandPool, initCommandBuffer, queue, mlb, scratch, geometry.meshlets.data(), geometry.meshlets.size() * sizeof(Meshlet)); uploadBuffer(device, initCommandPool, initCommandBuffer, queue, mdb, scratch, geometry.meshletdata.data(), geometry.meshletdata.size() * sizeof(uint32_t)); } Buffer db = {}; createBuffer(db, device, memoryProperties, draws.size() * sizeof(MeshDraw), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); Buffer dvb = {}; createBuffer(dvb, device, memoryProperties, draws.size() * sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); bool dvbCleared = false; Buffer dcb = {}; createBuffer(dcb, device, memoryProperties, TASK_WGLIMIT * sizeof(MeshTaskCommand), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer dccb = {}; createBuffer(dccb, device, memoryProperties, 16, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); // TODO: there's a way to implement cluster visibility persistence *without* using bitwise storage at all, which may be beneficial on the balance, so we should try that. // *if* we do that, we can drop meshletVisibilityOffset et al from everywhere Buffer mvb = {}; bool mvbCleared = false; if (meshShadingSupported) { createBuffer(mvb, device, memoryProperties, meshletVisibilityBytes, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } Buffer cib = {}; Buffer ccb = {}; if (meshShadingSupported) { createBuffer(cib, device, memoryProperties, CLUSTER_LIMIT * sizeof(uint32_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); createBuffer(ccb, device, memoryProperties, 16, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } uploadBuffer(device, initCommandPool, initCommandBuffer, queue, db, scratch, draws.data(), draws.size() * sizeof(MeshDraw)); std::vector<VkAccelerationStructureKHR> blas; std::vector<VkDeviceAddress> blasAddresses; VkAccelerationStructureKHR tlas = nullptr; bool tlasNeedsRebuild = true; Buffer blasBuffer = {}; Buffer tlasBuffer = {}; Buffer tlasScratchBuffer = {}; Buffer tlasInstanceBuffer = {}; if (raytracingSupported) { if (clusterrtSupported && clrtMode) { Buffer vxb = {}; createBuffer(vxb, device, memoryProperties, geometry.meshletvtx0.size() * sizeof(uint16_t), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | raytracingBufferFlags, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); memcpy(vxb.data, geometry.meshletvtx0.data(), geometry.meshletvtx0.size() * sizeof(uint16_t)); buildCBLAS(device, geometry.meshes, geometry.meshlets, vxb, mdb, blas, blasBuffer, initCommandPool, initCommandBuffer, queue, memoryProperties); destroyBuffer(vxb, device); } else { std::vector<VkDeviceSize> compactedSizes; buildBLAS(device, geometry.meshes, vb, ib, blas, compactedSizes, blasBuffer, initCommandPool, initCommandBuffer, queue, memoryProperties); compactBLAS(device, blas, compactedSizes, blasBuffer, initCommandPool, initCommandBuffer, queue, memoryProperties); } blasAddresses.resize(blas.size()); for (size_t i = 0; i < blas.size(); ++i) { VkAccelerationStructureDeviceAddressInfoKHR info = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_DEVICE_ADDRESS_INFO_KHR }; info.accelerationStructure = blas[i]; blasAddresses[i] = vkGetAccelerationStructureDeviceAddressKHR(device, &info); } createBuffer(tlasInstanceBuffer, device, memoryProperties, sizeof(VkAccelerationStructureInstanceKHR) * draws.size(), VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); for (size_t i = 0; i < draws.size(); ++i) { const MeshDraw& draw = draws[i]; assert(draw.meshIndex < blas.size()); VkAccelerationStructureInstanceKHR instance = {}; fillInstanceRT(instance, draw, uint32_t(i), blasAddresses[draw.meshIndex]); memcpy(static_cast<VkAccelerationStructureInstanceKHR*>(tlasInstanceBuffer.data) + i, &instance, sizeof(VkAccelerationStructureInstanceKHR)); } tlas = createTLAS(device, tlasBuffer, tlasScratchBuffer, tlasInstanceBuffer, draws.size(), memoryProperties); } // Make sure we don't accidentally reuse the init command pool because that would require extra synchronization initCommandPool = VK_NULL_HANDLE; initCommandBuffer = VK_NULL_HANDLE; Image gbufferTargets[gbufferCount] = {}; Image depthTarget = {}; Image shadowTarget = {}; Image shadowblurTarget = {}; Image depthPyramid = {}; VkImageView depthPyramidMips[16] = {}; uint32_t depthPyramidWidth = 0; uint32_t depthPyramidHeight = 0; uint32_t depthPyramidLevels = 0; GLFWwindow* window = glfwCreateWindow(1024, 768, "niagara", 0, 0); assert(window); glfwSetKeyCallback(window, keyCallback); glfwSetMouseButtonCallback(window, mouseCallback); VkSurfaceKHR surface = createSurface(instance, window); assert(surface); VkBool32 presentSupported = 0; VK_CHECK(vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, familyIndex, surface, &presentSupported)); assert(presentSupported); VkFormat swapchainFormat = getSwapchainFormat(physicalDevice, surface); Swapchain swapchain; createSwapchain(swapchain, physicalDevice, device, surface, familyIndex, window, swapchainFormat); std::vector<VkSemaphore> presentSemaphores(swapchain.imageCount); for (uint32_t i = 0; i < swapchain.imageCount; ++i) { presentSemaphores[i] = createSemaphore(device); assert(presentSemaphores[i]); } std::vector<VkImageView> swapchainImageViews(swapchain.imageCount); double frameCpuAvg = 0; double frameGpuAvg = 0; uint64_t frameIndex = 0; double frameTimestamp = glfwGetTime(); double animationTime = 0; uint64_t timestampResults[23] = {}; uint64_t pipelineResults[3] = {}; while (!glfwWindowShouldClose(window)) { double frameDelta = glfwGetTime() - frameTimestamp; frameTimestamp = glfwGetTime(); double frameCpuBegin = glfwGetTime() * 1000; glfwPollEvents(); if (glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_DISABLED) { double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); bool cameraBoost = (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS); vec2 cameraMotion = vec2(glfwGetKey(window, GLFW_KEY_W), glfwGetKey(window, GLFW_KEY_D)) - vec2(glfwGetKey(window, GLFW_KEY_S), glfwGetKey(window, GLFW_KEY_A)); vec2 cameraRotation = vec2(xpos, ypos); float cameraMotionSpeed = cameraBoost ? 10.f : 3.0f; float cameraRotationSpeed = glm::radians(10.f); camera.position += float(cameraMotion.y * frameDelta * cameraMotionSpeed) * (camera.orientation * vec3(1, 0, 0)); camera.position += float(cameraMotion.x * frameDelta * cameraMotionSpeed) * (camera.orientation * vec3(0, 0, -1)); camera.orientation = glm::rotate(glm::quat(0, 0, 0, 1), float(-cameraRotation.x * frameDelta * cameraRotationSpeed), vec3(0, 1, 0)) * camera.orientation; camera.orientation = glm::rotate(glm::quat(0, 0, 0, 1), float(-cameraRotation.y * frameDelta * cameraRotationSpeed), camera.orientation * vec3(1, 0, 0)) * camera.orientation; glfwSetCursorPos(window, 0, 0); } if (reloadShaders && glfwGetTime() >= reloadShadersTimer) { bool changed = false; int rc = system("ninja --quiet compile_shaders"); if (rc == 0) { for (Shader& shader : shaders.shaders) { std::vector<char> oldSpirv = std::move(shader.spirv); rcs = loadShader(shader, argv[0], ("spirv/" + shader.name + ".spv").c_str()); assert(rcs); changed |= oldSpirv != shader.spirv; } if (changed) { VK_CHECK(vkDeviceWaitIdle(device)); createPipelines(); reloadShadersColor = 0x00ff00; } else { reloadShadersColor = 0xffffff; } } else { reloadShadersColor = 0xff0000; } reloadShadersTimer = glfwGetTime() + 1; } SwapchainStatus swapchainStatus = updateSwapchain(swapchain, physicalDevice, device, surface, familyIndex, window, swapchainFormat); if (swapchainStatus == Swapchain_NotReady) continue; if (swapchainStatus == Swapchain_Resized || !depthTarget.image) { printf("Swapchain: %dx%d\n", swapchain.width, swapchain.height); for (Image& image : gbufferTargets) if (image.image) destroyImage(image, device); if (depthTarget.image) destroyImage(depthTarget, device); if (depthPyramid.image) { for (uint32_t i = 0; i < depthPyramidLevels; ++i) vkDestroyImageView(device, depthPyramidMips[i], 0); destroyImage(depthPyramid, device); } if (shadowTarget.image) destroyImage(shadowTarget, device); if (shadowblurTarget.image) destroyImage(shadowblurTarget, device); for (uint32_t i = 0; i < gbufferCount; ++i) createImage(gbufferTargets[i], device, memoryProperties, swapchain.width, swapchain.height, 1, gbufferFormats[i], VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); createImage(depthTarget, device, memoryProperties, swapchain.width, swapchain.height, 1, depthFormat, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); createImage(shadowTarget, device, memoryProperties, swapchain.width, swapchain.height, 1, VK_FORMAT_R8_UNORM, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); createImage(shadowblurTarget, device, memoryProperties, swapchain.width, swapchain.height, 1, VK_FORMAT_R8_UNORM, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); // Note: previousPow2 makes sure all reductions are at most by 2x2 which makes sure they are conservative depthPyramidWidth = previousPow2(swapchain.width); depthPyramidHeight = previousPow2(swapchain.height); depthPyramidLevels = getImageMipLevels(depthPyramidWidth, depthPyramidHeight); createImage(depthPyramid, device, memoryProperties, depthPyramidWidth, depthPyramidHeight, depthPyramidLevels, VK_FORMAT_R32_SFLOAT, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT); for (uint32_t i = 0; i < depthPyramidLevels; ++i) { depthPyramidMips[i] = createImageView(device, depthPyramid.image, VK_FORMAT_R32_SFLOAT, i, 1); assert(depthPyramidMips[i]); } for (uint32_t i = 0; i < swapchain.imageCount; ++i) { if (swapchainImageViews[i]) vkDestroyImageView(device, swapchainImageViews[i], 0); swapchainImageViews[i] = createImageView(device, swapchain.images[i], swapchainFormat, 0, 1); } } // TODO: this code races the GPU reading the transforms from both TLAS and draw buffers, which can cause rendering issues if (animationEnabled) { animationTime += frameDelta; for (Animation& animation : animations) { double index = (animationTime - animation.startTime) / animation.period; if (index < 0) continue; index = fmod(index, double(animation.keyframes.size())); int index0 = int(index) % animation.keyframes.size(); int index1 = (index0 + 1) % animation.keyframes.size(); double t = index - floor(index); const Keyframe& keyframe0 = animation.keyframes[index0]; const Keyframe& keyframe1 = animation.keyframes[index1]; MeshDraw& draw = draws[animation.drawIndex]; draw.position = glm::mix(keyframe0.translation, keyframe1.translation, float(t)); draw.scale = glm::mix(keyframe0.scale, keyframe1.scale, float(t)); draw.orientation = glm::slerp(keyframe0.rotation, keyframe1.rotation, float(t)); MeshDraw& gpuDraw = static_cast<MeshDraw*>(db.data)[animation.drawIndex]; memcpy(&gpuDraw, &draw, sizeof(draw)); if (raytracingSupported) { VkAccelerationStructureInstanceKHR instance = {}; fillInstanceRT(instance, draw, uint32_t(animation.drawIndex), blasAddresses[draw.meshIndex]); memcpy(static_cast<VkAccelerationStructureInstanceKHR*>(tlasInstanceBuffer.data) + animation.drawIndex, &instance, sizeof(VkAccelerationStructureInstanceKHR)); } } } FrameDescriptors framedesc = {}; #if VK_EXT_descriptor_heap framedesc.device = device; framedesc.descriptorHeap = resourceHeap.data; framedesc.descriptorSize = resourceDescriptorSize; framedesc.descriptorOffset = DESCRIPTOR_LIMIT + (frameIndex % MAX_FRAMES) * DESCRIPTOR_LIMIT_FRAME; framedesc.descriptorOffsetEnd = framedesc.descriptorOffset + DESCRIPTOR_LIMIT_FRAME; #endif VkCommandPool commandPool = commandPools[frameIndex % MAX_FRAMES]; VkCommandBuffer commandBuffer = commandBuffers[frameIndex % MAX_FRAMES]; VkSemaphore acquireSemaphore = acquireSemaphores[frameIndex % MAX_FRAMES]; VkFence frameFence = frameFences[frameIndex % MAX_FRAMES]; VkQueryPool queryPoolTimestamp = queryPoolsTimestamp[frameIndex % MAX_FRAMES]; VkQueryPool queryPoolPipeline = queryPoolsPipeline[frameIndex % MAX_FRAMES]; uint32_t imageIndex = 0; VkResult acquireResult = vkAcquireNextImageKHR(device, swapchain.swapchain, ~0ull, acquireSemaphore, VK_NULL_HANDLE, &imageIndex); if (acquireResult == VK_ERROR_OUT_OF_DATE_KHR) { swapchain.dirty = true; continue; // attempting to render to an out-of-date swapchain would break semaphore synchronization } VK_CHECK_SWAPCHAIN(acquireResult); VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); vkCmdResetQueryPool(commandBuffer, queryPoolTimestamp, 0, 128); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, 0); if (!dvbCleared) { // TODO: this is stupidly redundant vkCmdFillBuffer(commandBuffer, dvb.buffer, 0, sizeof(uint32_t) * draws.size(), 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); dvbCleared = true; } if (!mvbCleared && meshShadingSupported) { // TODO: this is stupidly redundant vkCmdFillBuffer(commandBuffer, mvb.buffer, 0, meshletVisibilityBytes, 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_EXT); mvbCleared = true; } if (raytracingSupported) { uint32_t timestamp = 21; vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); if (tlasNeedsRebuild) { buildTLAS(device, commandBuffer, tlas, tlasBuffer, tlasScratchBuffer, tlasInstanceBuffer, draws.size(), VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR); tlasNeedsRebuild = false; } else if (animationEnabled) buildTLAS(device, commandBuffer, tlas, tlasBuffer, tlasScratchBuffer, tlasInstanceBuffer, draws.size(), VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); } mat4 view = glm::mat4_cast(camera.orientation); view[3] = vec4(camera.position, 1.0f); view = inverse(view); view = glm::scale(glm::identity<glm::mat4>(), vec3(1, 1, -1)) * view; mat4 projection = perspectiveProjection(camera.fovY, float(swapchain.width) / float(swapchain.height), camera.znear); mat4 projectionT = transpose(projection); vec4 frustumX = normalizePlane(projectionT[3] + projectionT[0]); // x + w < 0 vec4 frustumY = normalizePlane(projectionT[3] + projectionT[1]); // y + w < 0 CullData cullData = {}; cullData.view = view; cullData.P00 = projection[0][0]; cullData.P11 = projection[1][1]; cullData.znear = camera.znear; cullData.zfar = drawDistance; cullData.frustum[0] = frustumX.x; cullData.frustum[1] = frustumX.z; cullData.frustum[2] = frustumY.y; cullData.frustum[3] = frustumY.z; cullData.drawCount = uint32_t(draws.size()); cullData.cullingEnabled = cullingEnabled; cullData.lodEnabled = lodEnabled; cullData.occlusionEnabled = occlusionEnabled; cullData.lodTarget = (2 / cullData.P11) * (1.f / float(swapchain.height)) * (1 << debugLodStep); // 1px cullData.pyramidWidth = float(depthPyramidWidth); cullData.pyramidHeight = float(depthPyramidHeight); cullData.clusterOcclusionEnabled = occlusionEnabled && clusterOcclusionEnabled && meshShadingSupported && meshShadingEnabled; Globals globals = {}; globals.projection = projection; globals.cullData = cullData; globals.screenWidth = float(swapchain.width); globals.screenHeight = float(swapchain.height); bool taskSubmit = meshShadingSupported && meshShadingEnabled; // TODO; refactor this to be false when taskShadingEnabled is false bool clusterSubmit = meshShadingSupported && meshShadingEnabled && !taskShadingEnabled; auto cull = [&](VkPipeline pipeline, uint32_t timestamp, const char* phase, bool late, unsigned int postPass = 0) { uint32_t rasterizationStage = taskSubmit ? VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_EXT | VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT : VK_PIPELINE_STAGE_VERTEX_SHADER_BIT; vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); vkCmdFillBuffer(commandBuffer, dccb.buffer, 0, 4, 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | rasterizationStage | VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); { CullData passData = cullData; passData.clusterBackfaceEnabled = postPass == 0; passData.postPass = postPass; vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); DescriptorInfo descriptors[] = { db, mb, dcb, dccb, dvb, depthPyramid, depthSampler }; dispatch(commandBuffer, framedesc, drawcullProgram, uint32_t(draws.size()), 1, passData, descriptors); } if (taskSubmit) { stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, tasksubmitPipeline); DescriptorInfo descriptors[] = { dccb, dcb }; pushDescriptors(commandBuffer, framedesc, tasksubmitProgram, descriptors); vkCmdDispatch(commandBuffer, 1, 1, 1); } stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | rasterizationStage); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); }; auto render = [&](bool late, const VkClearColorValue& colorClear, const VkClearDepthStencilValue& depthClear, uint32_t query, uint32_t timestamp, const char* phase, unsigned int postPass = 0) { vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); vkCmdBeginQuery(commandBuffer, queryPoolPipeline, query, 0); if (clusterSubmit) { stageBarrier(commandBuffer, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT); vkCmdFillBuffer(commandBuffer, ccb.buffer, 0, 4, 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, late ? clusterculllatePipeline : clustercullPipeline); DescriptorInfo descriptors[] = { dcb, db, mlb, mvb, depthPyramid, cib, ccb, depthSampler }; pushDescriptors(commandBuffer, framedesc, clustercullProgram, descriptors); CullData passData = cullData; passData.postPass = postPass; pushConstants(commandBuffer, framedesc, clustercullProgram, passData); vkCmdDispatchIndirect(commandBuffer, dccb.buffer, 4); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, clustersubmitPipeline); DescriptorInfo descriptors2[] = { ccb, cib }; pushDescriptors(commandBuffer, framedesc, clustersubmitProgram, descriptors2); vkCmdDispatch(commandBuffer, 1, 1, 1); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_MESH_SHADER_BIT_EXT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT); } VkRenderingAttachmentInfo gbufferAttachments[gbufferCount] = {}; for (uint32_t i = 0; i < gbufferCount; ++i) { gbufferAttachments[i].sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO; gbufferAttachments[i].imageView = gbufferTargets[i].imageView; gbufferAttachments[i].imageLayout = VK_IMAGE_LAYOUT_GENERAL; gbufferAttachments[i].loadOp = late ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_CLEAR; gbufferAttachments[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE; gbufferAttachments[i].clearValue.color = colorClear; } VkRenderingAttachmentInfo depthAttachment = { VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO }; depthAttachment.imageView = depthTarget.imageView; depthAttachment.imageLayout = VK_IMAGE_LAYOUT_GENERAL; depthAttachment.loadOp = late ? VK_ATTACHMENT_LOAD_OP_LOAD : VK_ATTACHMENT_LOAD_OP_CLEAR; depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; depthAttachment.clearValue.depthStencil = depthClear; VkRenderingInfo passInfo = { VK_STRUCTURE_TYPE_RENDERING_INFO }; passInfo.renderArea.extent.width = swapchain.width; passInfo.renderArea.extent.height = swapchain.height; passInfo.layerCount = 1; passInfo.colorAttachmentCount = gbufferCount; passInfo.pColorAttachments = gbufferAttachments; passInfo.pDepthAttachment = &depthAttachment; vkCmdBeginRendering(commandBuffer, &passInfo); VkViewport viewport = { 0, float(swapchain.height), float(swapchain.width), -float(swapchain.height), 0, 1 }; VkRect2D scissor = { { 0, 0 }, { uint32_t(swapchain.width), uint32_t(swapchain.height) } }; vkCmdSetViewport(commandBuffer, 0, 1, &viewport); vkCmdSetScissor(commandBuffer, 0, 1, &scissor); vkCmdSetCullMode(commandBuffer, postPass == 0 ? VK_CULL_MODE_BACK_BIT : VK_CULL_MODE_NONE); vkCmdSetDepthBias(commandBuffer, postPass == 0 ? 0 : 16, 0, postPass == 0 ? 0 : 1); Globals passGlobals = globals; passGlobals.cullData.postPass = postPass; if (clusterSubmit) { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, postPass >= 1 ? clusterpostPipeline : clusterPipeline); DescriptorInfo descriptors[] = { dcb, db, mlb, mdb, vb, cib, DescriptorInfo(), textureSampler, mtb }; pushDescriptors(commandBuffer, framedesc, clusterProgram, descriptors); if (!clusterProgram.descriptorSize) vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, clusterProgram.layout, 1, 1, &textureSet.second, 0, nullptr); pushConstants(commandBuffer, framedesc, clusterProgram, passGlobals); vkCmdDrawMeshTasksIndirectEXT(commandBuffer, ccb.buffer, 4, 1, 0); } else if (taskSubmit) { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, postPass >= 1 ? meshtaskpostPipeline : late ? meshtasklatePipeline : meshtaskPipeline); DescriptorInfo descriptors[] = { dcb, db, mlb, mdb, vb, mvb, depthPyramid, textureSampler, mtb, depthSampler }; pushDescriptors(commandBuffer, framedesc, meshtaskProgram, descriptors); if (!meshtaskProgram.descriptorSize) vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, meshtaskProgram.layout, 1, 1, &textureSet.second, 0, nullptr); pushConstants(commandBuffer, framedesc, meshtaskProgram, passGlobals); vkCmdDrawMeshTasksIndirectEXT(commandBuffer, dccb.buffer, 4, 1, 0); } else { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, postPass >= 1 ? meshpostPipeline : meshPipeline); DescriptorInfo descriptors[] = { dcb, db, vb, DescriptorInfo(), DescriptorInfo(), DescriptorInfo(), DescriptorInfo(), textureSampler, mtb }; pushDescriptors(commandBuffer, framedesc, meshProgram, descriptors); if (!meshProgram.descriptorSize) vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, meshProgram.layout, 1, 1, &textureSet.second, 0, nullptr); vkCmdBindIndexBuffer(commandBuffer, ib.buffer, 0, VK_INDEX_TYPE_UINT32); pushConstants(commandBuffer, framedesc, meshProgram, passGlobals); vkCmdDrawIndexedIndirectCount(commandBuffer, dcb.buffer, offsetof(MeshDrawCommand, indirect), dccb.buffer, 0, uint32_t(draws.size()), sizeof(MeshDrawCommand)); } vkCmdEndRendering(commandBuffer); vkCmdEndQuery(commandBuffer, queryPoolPipeline, query); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); }; auto pyramid = [&](uint32_t timestamp) { vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, depthreducePipeline); DescriptorInfo mipSource = depthTarget; for (uint32_t i = 0; i < depthPyramidLevels; ++i) { DescriptorInfo mipTarget(depthPyramid, depthPyramidMips[i], int(i)); DescriptorInfo descriptors[] = { mipTarget, mipSource, depthSampler }; uint32_t levelWidth = std::max(1u, depthPyramidWidth >> i); uint32_t levelHeight = std::max(1u, depthPyramidHeight >> i); vec4 reduceData = vec4(levelWidth, levelHeight, 0, 0); dispatch(commandBuffer, framedesc, depthreduceProgram, levelWidth, levelHeight, reduceData, descriptors); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); mipSource = mipTarget; } stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); }; // transition everything we write to during the frame from undefined to general invalidateBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, { swapchain.images[imageIndex], depthPyramid.image, shadowTarget.image, shadowblurTarget.image, gbufferTargets[0].image, gbufferTargets[1].image }, { depthTarget.image }); vkCmdResetQueryPool(commandBuffer, queryPoolPipeline, 0, 4); VkClearColorValue colorClear = { 135.f / 255.f, 206.f / 255.f, 250.f / 255.f, 15.f / 255.f }; VkClearDepthStencilValue depthClear = { 0.f, 0 }; // early cull: frustum cull & fill objects that *were* visible last frame cull(taskSubmit ? taskcullPipeline : drawcullPipeline, 2, "early cull", /* late= */ false); // early render: render objects that were visible last frame render(/* late= */ false, colorClear, depthClear, 0, 4, "early render"); // depth pyramid generation pyramid(6); // late cull: frustum + occlusion cull & fill objects that were *not* visible last frame cull(taskSubmit ? taskculllatePipeline : drawculllatePipeline, 8, "late cull", /* late= */ true); // late render: render objects that are visible this frame but weren't drawn in the early pass render(/* late= */ true, colorClear, depthClear, 1, 10, "late render"); // we can skip post passes if no draw call needs them if (meshPostPasses >> 1) { // post cull: frustum + occlusion cull & fill extra objects cull(taskSubmit ? taskculllatePipeline : drawculllatePipeline, 12, "post cull", /* late= */ true, /* postPass= */ 1); // post render: render extra objects render(/* late= */ true, colorClear, depthClear, 2, 14, "post render", /* postPass= */ 1); } stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); if (raytracingSupported && shadowsEnabled) { uint32_t timestamp = 16; // checkerboard rendering: we dispatch half as many columns and xform them to fill the screen int shadowWidthCB = shadowCheckerboard ? (swapchain.width + 1) / 2 : swapchain.width; int shadowCheckerboardF = shadowCheckerboard ? 1 : 0; vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, shadowQuality == 0 ? shadowlqPipeline : shadowhqPipeline); if (!shadowProgram.descriptorSize) vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, shadowProgram.layout, 1, 1, &textureSet.second, 0, nullptr); DescriptorInfo descriptors[] = { shadowTarget, depthTarget, tlas, db, mb, mtb, vb, ib, textureSampler }; ShadowData shadowData = {}; shadowData.sunDirection = sunDirection; shadowData.sunJitter = shadowblurEnabled ? 1e-2f : 0; shadowData.inverseViewProjection = inverse(projection * view); shadowData.imageSize = vec2(float(swapchain.width), float(swapchain.height)); shadowData.checkerboard = shadowCheckerboardF; dispatch(commandBuffer, framedesc, shadowProgram, shadowWidthCB, swapchain.height, shadowData, descriptors); } vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); if (shadowCheckerboard) { stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, shadowfillPipeline); DescriptorInfo descriptors[] = { shadowTarget, depthTarget }; vec4 fillData = vec4(float(swapchain.width), float(swapchain.height), 0, 0); memcpy(&fillData.z, &shadowCheckerboardF, sizeof(shadowCheckerboardF)); dispatch(commandBuffer, framedesc, shadowfillProgram, shadowWidthCB, swapchain.height, fillData, descriptors); } for (int pass = 0; pass < (shadowblurEnabled ? 2 : 0); ++pass) { const Image& blurFrom = pass == 0 ? shadowTarget : shadowblurTarget; const Image& blurTo = pass == 0 ? shadowblurTarget : shadowTarget; stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, shadowblurPipeline); DescriptorInfo descriptors[] = { blurTo, blurFrom, depthTarget }; vec4 blurData = vec4(float(swapchain.width), float(swapchain.height), pass == 0 ? 1 : 0, camera.znear); dispatch(commandBuffer, framedesc, shadowblurProgram, swapchain.width, swapchain.height, blurData, descriptors); } stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 2); } else { uint32_t timestamp = 16; // todo: we need an actual profiler vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 2); } #ifdef VK_EXT_descriptor_heap if (descheapSupported) { VkBindHeapInfoEXT bindSamplerHeap = { VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT }; bindSamplerHeap.heapRange.address = samplerHeap.address; bindSamplerHeap.heapRange.size = samplerHeap.size; bindSamplerHeap.reservedRangeOffset = samplerHeap.size - descheapProperties.minSamplerHeapReservedRange; bindSamplerHeap.reservedRangeSize = descheapProperties.minSamplerHeapReservedRange; VkBindHeapInfoEXT bindResourceHeap = { VK_STRUCTURE_TYPE_BIND_HEAP_INFO_EXT }; bindResourceHeap.heapRange.address = resourceHeap.address; bindResourceHeap.heapRange.size = resourceHeap.size; bindResourceHeap.reservedRangeOffset = resourceHeap.size - descheapProperties.minResourceHeapReservedRange; bindResourceHeap.reservedRangeSize = descheapProperties.minResourceHeapReservedRange; vkCmdBindSamplerHeapEXT(commandBuffer, &bindSamplerHeap); vkCmdBindResourceHeapEXT(commandBuffer, &bindResourceHeap); } #endif Image fakeSwapchainImage = { swapchain.images[imageIndex], swapchainFormat, swapchainImageViews[imageIndex], VK_NULL_HANDLE }; { uint32_t timestamp = 19; vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 0); { vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, finalPipeline); DescriptorInfo descriptors[] = { fakeSwapchainImage, gbufferTargets[0], gbufferTargets[1], depthTarget, shadowTarget }; ShadeData shadeData = {}; shadeData.cameraPosition = camera.position; shadeData.sunDirection = sunDirection; shadeData.shadowsEnabled = shadowsEnabled; shadeData.inverseViewProjection = inverse(projection * view); shadeData.imageSize = vec2(float(swapchain.width), float(swapchain.height)); dispatch(commandBuffer, framedesc, finalProgram, swapchain.width, swapchain.height, shadeData, descriptors); } vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, timestamp + 1); } if (debugGuiMode % 3) { auto debugtext = [&](int line, uint32_t color, const char* format, ...) #ifdef __GNUC__ __attribute__((format(printf, 4, 5))) #endif { TextData textData = {}; textData.offsetX = 1; textData.offsetY = line + 1; textData.scale = 2; textData.color = color; va_list args; va_start(args, format); vsnprintf(textData.data, sizeof(textData.data), format, args); va_end(args); pushConstants(commandBuffer, framedesc, debugtextProgram, textData); vkCmdDispatch(commandBuffer, strlen(textData.data), 1, 1); }; stageBarrier(commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, debugtextPipeline); DescriptorInfo descriptors[] = { fakeSwapchainImage }; pushDescriptors(commandBuffer, framedesc, debugtextProgram, descriptors); // debug text goes here! uint64_t triangleCount = pipelineResults[0] + pipelineResults[1] + pipelineResults[2]; double frameGpuBegin = double(timestampResults[0]) * props.limits.timestampPeriod * 1e-6; double frameGpuEnd = double(timestampResults[1]) * props.limits.timestampPeriod * 1e-6; double cullGpuTime = double(timestampResults[3] - timestampResults[2]) * props.limits.timestampPeriod * 1e-6; double renderGpuTime = double(timestampResults[5] - timestampResults[4]) * props.limits.timestampPeriod * 1e-6; double pyramidGpuTime = double(timestampResults[7] - timestampResults[6]) * props.limits.timestampPeriod * 1e-6; double culllateGpuTime = double(timestampResults[9] - timestampResults[8]) * props.limits.timestampPeriod * 1e-6; double renderlateGpuTime = double(timestampResults[11] - timestampResults[10]) * props.limits.timestampPeriod * 1e-6; double cullpostGpuTime = double(timestampResults[13] - timestampResults[12]) * props.limits.timestampPeriod * 1e-6; double renderpostGpuTime = double(timestampResults[15] - timestampResults[14]) * props.limits.timestampPeriod * 1e-6; double shadowsGpuTime = double(timestampResults[17] - timestampResults[16]) * props.limits.timestampPeriod * 1e-6; double shadowblurGpuTime = double(timestampResults[18] - timestampResults[17]) * props.limits.timestampPeriod * 1e-6; double shadeGpuTime = double(timestampResults[20] - timestampResults[19]) * props.limits.timestampPeriod * 1e-6; double tlasGpuTime = double(timestampResults[22] - timestampResults[21]) * props.limits.timestampPeriod * 1e-6; double trianglesPerSec = double(triangleCount) / double(frameGpuAvg * 1e-3); double drawsPerSec = double(draws.size()) / double(frameGpuAvg * 1e-3); debugtext(0, ~0u, "%scpu: %.2f ms (%+.2f); gpu: %.2f ms", reloadShaders ? " " : "", frameCpuAvg, frameDelta * 1000 - frameCpuAvg, frameGpuAvg); if (reloadShaders) debugtext(0, reloadShadersColor, "R*"); if (debugGuiMode % 3 == 2) { debugtext(2, ~0u, "cull: %.2f ms, pyramid: %.2f ms, render: %.2f ms, final: %.2f ms", cullGpuTime + culllateGpuTime + cullpostGpuTime, pyramidGpuTime, renderGpuTime + renderlateGpuTime + renderpostGpuTime, shadeGpuTime); debugtext(3, ~0u, "render breakdown: early %.2f ms, late %.2f ms, post %.2f ms", renderGpuTime, renderlateGpuTime, renderpostGpuTime); debugtext(4, ~0u, "tlas: %.2f ms, shadows: %.2f ms, shadow blur: %.2f ms", tlasGpuTime, shadowsGpuTime, shadowblurGpuTime); debugtext(5, ~0u, "triangles %.2fM; %.1fB tri / sec, %.1fM draws / sec", double(triangleCount) * 1e-6, trianglesPerSec * 1e-9, drawsPerSec * 1e-6); debugtext(7, ~0u, "frustum culling %s, occlusion culling %s, level-of-detail %s", cullingEnabled ? "ON" : "OFF", occlusionEnabled ? "ON" : "OFF", lodEnabled ? "ON" : "OFF"); debugtext(8, ~0u, "mesh shading %s, task shading %s, cluster occlusion culling %s", taskSubmit ? "ON" : "OFF", taskSubmit && taskShadingEnabled ? "ON" : "OFF", clusterOcclusionEnabled ? "ON" : "OFF"); debugtext(10, ~0u, "RT shadows: %s, blur %s, quality %d, checkerboard %s", raytracingSupported && shadowsEnabled ? "ON" : "OFF", raytracingSupported && shadowblurEnabled ? "ON" : "OFF", shadowQuality, shadowCheckerboard ? "ON" : "OFF"); } } VkImageMemoryBarrier2 presentBarrier = imageBarrier(swapchain.images[imageIndex], VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL, 0, 0, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR); pipelineBarrier(commandBuffer, VK_DEPENDENCY_BY_REGION_BIT, 0, nullptr, 1, &presentBarrier); vkCmdWriteTimestamp(commandBuffer, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, queryPoolTimestamp, 1); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSemaphore presentSemaphore = presentSemaphores[imageIndex]; VkPipelineStageFlags submitStageMask = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &acquireSemaphore; submitInfo.pWaitDstStageMask = &submitStageMask; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &presentSemaphore; VK_CHECK_FORCE(vkQueueSubmit(queue, 1, &submitInfo, frameFence)); VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR }; presentInfo.waitSemaphoreCount = 1; presentInfo.pWaitSemaphores = &presentSemaphore; presentInfo.swapchainCount = 1; presentInfo.pSwapchains = &swapchain.swapchain; presentInfo.pImageIndices = &imageIndex; VK_CHECK_SWAPCHAIN(vkQueuePresentKHR(queue, &presentInfo)); if (frameIndex >= MAX_FRAMES - 1) { int waitIndex = (frameIndex + 1) % MAX_FRAMES; VkFence waitFence = frameFences[waitIndex]; VK_CHECK(vkWaitForFences(device, 1, &waitFence, VK_TRUE, ~0ull)); VK_CHECK(vkResetFences(device, 1, &waitFence)); VK_CHECK_QUERY(vkGetQueryPoolResults(device, queryPoolsTimestamp[waitIndex], 0, COUNTOF(timestampResults), sizeof(timestampResults), timestampResults, sizeof(timestampResults[0]), VK_QUERY_RESULT_64_BIT)); VK_CHECK_QUERY(vkGetQueryPoolResults(device, queryPoolsPipeline[waitIndex], 0, COUNTOF(pipelineResults), sizeof(pipelineResults), pipelineResults, sizeof(pipelineResults[0]), VK_QUERY_RESULT_64_BIT)); double frameGpuBegin = double(timestampResults[0]) * props.limits.timestampPeriod * 1e-6; double frameGpuEnd = double(timestampResults[1]) * props.limits.timestampPeriod * 1e-6; frameGpuAvg = frameGpuAvg * 0.95 + (frameGpuEnd - frameGpuBegin) * 0.05; } double frameCpuEnd = glfwGetTime() * 1000; frameCpuAvg = frameCpuAvg * 0.95 + (frameCpuEnd - frameCpuBegin) * 0.05; frameIndex++; if (debugSleep) { #ifdef _WIN32 Sleep(20); #else usleep(20 * 1000); #endif } } VK_CHECK(vkDeviceWaitIdle(device)); vkDestroyDescriptorPool(device, textureSet.first, 0); for (Image& image : images) destroyImage(image, device); for (Image& image : gbufferTargets) if (image.image) destroyImage(image, device); if (depthTarget.image) destroyImage(depthTarget, device); if (depthPyramid.image) { for (uint32_t i = 0; i < depthPyramidLevels; ++i) vkDestroyImageView(device, depthPyramidMips[i], 0); destroyImage(depthPyramid, device); } if (shadowTarget.image) destroyImage(shadowTarget, device); if (shadowblurTarget.image) destroyImage(shadowblurTarget, device); for (uint32_t i = 0; i < swapchain.imageCount; ++i) if (swapchainImageViews[i]) vkDestroyImageView(device, swapchainImageViews[i], 0); destroyBuffer(mb, device); destroyBuffer(mtb, device); destroyBuffer(db, device); destroyBuffer(dvb, device); destroyBuffer(dcb, device); destroyBuffer(dccb, device); if (meshShadingSupported) { destroyBuffer(mlb, device); destroyBuffer(mdb, device); destroyBuffer(mvb, device); destroyBuffer(cib, device); destroyBuffer(ccb, device); } if (raytracingSupported) { vkDestroyAccelerationStructureKHR(device, tlas, 0); for (VkAccelerationStructureKHR as : blas) vkDestroyAccelerationStructureKHR(device, as, 0); destroyBuffer(tlasBuffer, device); destroyBuffer(blasBuffer, device); destroyBuffer(tlasScratchBuffer, device); destroyBuffer(tlasInstanceBuffer, device); } destroyBuffer(ib, device); destroyBuffer(vb, device); destroyBuffer(scratch, device); #if VK_EXT_descriptor_heap destroyBuffer(samplerHeap, device); destroyBuffer(resourceHeap, device); #endif for (VkCommandPool pool : commandPools) vkDestroyCommandPool(device, pool, 0); for (VkQueryPool pool : queryPoolsTimestamp) vkDestroyQueryPool(device, pool, 0); for (VkQueryPool pool : queryPoolsPipeline) vkDestroyQueryPool(device, pool, 0); for (VkSemaphore semaphore : presentSemaphores) vkDestroySemaphore(device, semaphore, 0); destroySwapchain(device, swapchain); for (VkPipeline pipeline : pipelines) vkDestroyPipeline(device, pipeline, 0); destroyProgram(device, debugtextProgram); destroyProgram(device, drawcullProgram); destroyProgram(device, tasksubmitProgram); destroyProgram(device, clustersubmitProgram); destroyProgram(device, clustercullProgram); destroyProgram(device, depthreduceProgram); destroyProgram(device, meshProgram); if (meshShadingSupported) { destroyProgram(device, meshtaskProgram); destroyProgram(device, clusterProgram); } destroyProgram(device, finalProgram); if (raytracingSupported) { destroyProgram(device, shadowProgram); destroyProgram(device, shadowfillProgram); destroyProgram(device, shadowblurProgram); } vkDestroyDescriptorSetLayout(device, textureSetLayout, 0); vkDestroySampler(device, textureSampler, 0); vkDestroySampler(device, depthSampler, 0); for (VkFence fence : frameFences) vkDestroyFence(device, fence, 0); for (VkSemaphore semaphore : acquireSemaphores) vkDestroySemaphore(device, semaphore, 0); vkDestroySurfaceKHR(instance, surface, 0); glfwDestroyWindow(window); vkDestroyDevice(device, 0); if (debugCallback) vkDestroyDebugUtilsMessengerEXT(instance, debugCallback, 0); vkDestroyInstance(instance, 0); volkFinalize(); }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/resources.cpp
C++
#include "common.h" #include "resources.h" #include <string.h> VkImageMemoryBarrier2 imageBarrier(VkImage image, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkImageLayout oldLayout, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask, VkImageLayout newLayout, VkImageAspectFlags aspectMask, uint32_t baseMipLevel, uint32_t levelCount) { VkImageMemoryBarrier2 result = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2 }; result.srcStageMask = srcStageMask; result.srcAccessMask = srcAccessMask; result.dstStageMask = dstStageMask; result.dstAccessMask = dstAccessMask; result.oldLayout = oldLayout; result.newLayout = newLayout; result.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; result.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; result.image = image; result.subresourceRange.aspectMask = aspectMask; result.subresourceRange.baseMipLevel = baseMipLevel; result.subresourceRange.levelCount = levelCount; result.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; return result; } VkBufferMemoryBarrier2 bufferBarrier(VkBuffer buffer, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask) { VkBufferMemoryBarrier2 result = { VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER_2 }; result.srcStageMask = srcStageMask; result.srcAccessMask = srcAccessMask; result.dstStageMask = dstStageMask; result.dstAccessMask = dstAccessMask; result.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; result.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; result.buffer = buffer; result.offset = 0; result.size = VK_WHOLE_SIZE; return result; } void pipelineBarrier(VkCommandBuffer commandBuffer, VkDependencyFlags dependencyFlags, size_t bufferBarrierCount, const VkBufferMemoryBarrier2* bufferBarriers, size_t imageBarrierCount, const VkImageMemoryBarrier2* imageBarriers) { VkDependencyInfo dependencyInfo = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO }; dependencyInfo.dependencyFlags = dependencyFlags; dependencyInfo.bufferMemoryBarrierCount = unsigned(bufferBarrierCount); dependencyInfo.pBufferMemoryBarriers = bufferBarriers; dependencyInfo.imageMemoryBarrierCount = unsigned(imageBarrierCount); dependencyInfo.pImageMemoryBarriers = imageBarriers; vkCmdPipelineBarrier2(commandBuffer, &dependencyInfo); } void invalidateBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 stageMask, std::initializer_list<VkImage> colorImages, std::initializer_list<VkImage> depthImages) { VkImageMemoryBarrier2 imageBarriers[32]; assert(colorImages.size() + depthImages.size() <= sizeof(imageBarriers) / sizeof(imageBarriers[0])); VkAccessFlags2 accessFlags = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT; size_t imageBarrierCount = 0; for (VkImage image : colorImages) imageBarriers[imageBarrierCount++] = imageBarrier(image, stageMask, 0, VK_IMAGE_LAYOUT_UNDEFINED, stageMask, accessFlags, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_COLOR_BIT); for (VkImage image : depthImages) imageBarriers[imageBarrierCount++] = imageBarrier(image, stageMask, 0, VK_IMAGE_LAYOUT_UNDEFINED, stageMask, accessFlags, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_ASPECT_DEPTH_BIT); VkDependencyInfo dependencyInfo = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO }; dependencyInfo.imageMemoryBarrierCount = unsigned(imageBarrierCount); dependencyInfo.pImageMemoryBarriers = imageBarriers; vkCmdPipelineBarrier2(commandBuffer, &dependencyInfo); } void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask) { VkMemoryBarrier2 memoryBarrier = { VK_STRUCTURE_TYPE_MEMORY_BARRIER_2 }; memoryBarrier.srcStageMask = srcStageMask; memoryBarrier.srcAccessMask = srcAccessMask; memoryBarrier.dstStageMask = dstStageMask; memoryBarrier.dstAccessMask = dstAccessMask; VkDependencyInfo dependencyInfo = { VK_STRUCTURE_TYPE_DEPENDENCY_INFO }; dependencyInfo.memoryBarrierCount = 1; dependencyInfo.pMemoryBarriers = &memoryBarrier; vkCmdPipelineBarrier2(commandBuffer, &dependencyInfo); } void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 srcStageMask, VkPipelineStageFlags2 dstStageMask) { VkAccessFlags2 accessFlags = VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT; stageBarrier(commandBuffer, srcStageMask, accessFlags, dstStageMask, accessFlags); } void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 stageMask) { stageBarrier(commandBuffer, stageMask, stageMask); } static uint32_t selectMemoryType(const VkPhysicalDeviceMemoryProperties& memoryProperties, uint32_t memoryTypeBits, VkMemoryPropertyFlags flags) { for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; ++i) if ((memoryTypeBits & (1 << i)) != 0 && (memoryProperties.memoryTypes[i].propertyFlags & flags) == flags) return i; assert(!"No compatible memory type found"); return ~0u; } void createBuffer(Buffer& result, VkDevice device, const VkPhysicalDeviceMemoryProperties& memoryProperties, size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags memoryFlags) { VkBufferCreateInfo createInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO }; createInfo.size = size; createInfo.usage = usage | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; VkBuffer buffer = 0; VK_CHECK(vkCreateBuffer(device, &createInfo, 0, &buffer)); VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(device, buffer, &memoryRequirements); uint32_t memoryTypeIndex = selectMemoryType(memoryProperties, memoryRequirements.memoryTypeBits, memoryFlags); assert(memoryTypeIndex != ~0u); VkMemoryAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; allocateInfo.allocationSize = memoryRequirements.size; allocateInfo.memoryTypeIndex = memoryTypeIndex; VkMemoryAllocateFlagsInfo flagInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO }; flagInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; flagInfo.deviceMask = 1; allocateInfo.pNext = &flagInfo; VkDeviceMemory memory = 0; VK_CHECK(vkAllocateMemory(device, &allocateInfo, 0, &memory)); VK_CHECK(vkBindBufferMemory(device, buffer, memory, 0)); void* data = 0; if (memoryFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) VK_CHECK(vkMapMemory(device, memory, 0, size, 0, &data)); result.buffer = buffer; result.memory = memory; result.data = data; result.size = size; result.address = getBufferAddress(result, device); } void uploadBuffer(VkDevice device, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const Buffer& buffer, const Buffer& scratch, const void* data, size_t size) { // TODO: this function is submitting a command buffer and waiting for device idle for each buffer upload; this is obviously suboptimal and we'd need to batch this later assert(size > 0); assert(scratch.data); assert(scratch.size >= size); memcpy(scratch.data, data, size); VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); VkBufferCopy region = { 0, 0, VkDeviceSize(size) }; vkCmdCopyBuffer(commandBuffer, scratch.buffer, buffer.buffer, 1, &region); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); } void destroyBuffer(const Buffer& buffer, VkDevice device) { vkDestroyBuffer(device, buffer.buffer, 0); vkFreeMemory(device, buffer.memory, 0); } // TODO: replace this with direct access to Buffer::address VkDeviceAddress getBufferAddress(const Buffer& buffer, VkDevice device) { VkBufferDeviceAddressInfo info = { VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO }; info.buffer = buffer.buffer; VkDeviceAddress address = vkGetBufferDeviceAddress(device, &info); assert(address != 0); return address; } static VkImageViewCreateInfo getImageViewInfo(VkImage image, VkFormat format, uint32_t mipLevel, uint32_t levelCount) { VkImageAspectFlags aspectMask = (format == VK_FORMAT_D32_SFLOAT) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; VkImageViewCreateInfo createInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO }; createInfo.image = image; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = format; createInfo.subresourceRange.aspectMask = aspectMask; createInfo.subresourceRange.baseMipLevel = mipLevel; createInfo.subresourceRange.levelCount = levelCount; createInfo.subresourceRange.layerCount = 1; return createInfo; } VkImageView createImageView(VkDevice device, VkImage image, VkFormat format, uint32_t mipLevel, uint32_t levelCount) { VkImageViewCreateInfo createInfo = getImageViewInfo(image, format, mipLevel, levelCount); VkImageView view = 0; VK_CHECK(vkCreateImageView(device, &createInfo, 0, &view)); return view; } void createImage(Image& result, VkDevice device, const VkPhysicalDeviceMemoryProperties& memoryProperties, uint32_t width, uint32_t height, uint32_t mipLevels, VkFormat format, VkImageUsageFlags usage) { VkImageCreateInfo createInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO }; createInfo.imageType = VK_IMAGE_TYPE_2D; createInfo.format = format; createInfo.extent = { width, height, 1 }; createInfo.mipLevels = mipLevels; createInfo.arrayLayers = 1; createInfo.samples = VK_SAMPLE_COUNT_1_BIT; createInfo.tiling = VK_IMAGE_TILING_OPTIMAL; createInfo.usage = usage; createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkImage image = 0; VK_CHECK(vkCreateImage(device, &createInfo, 0, &image)); VkMemoryRequirements memoryRequirements; vkGetImageMemoryRequirements(device, image, &memoryRequirements); uint32_t memoryTypeIndex = selectMemoryType(memoryProperties, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); assert(memoryTypeIndex != ~0u); VkMemoryAllocateInfo allocateInfo = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO }; allocateInfo.allocationSize = memoryRequirements.size; allocateInfo.memoryTypeIndex = memoryTypeIndex; VkDeviceMemory memory = 0; VK_CHECK(vkAllocateMemory(device, &allocateInfo, 0, &memory)); VK_CHECK(vkBindImageMemory(device, image, memory, 0)); result.image = image; result.format = format; result.imageView = createImageView(device, image, format, 0, mipLevels); result.memory = memory; } void destroyImage(const Image& image, VkDevice device) { vkDestroyImageView(device, image.imageView, 0); vkDestroyImage(device, image.image, 0); vkFreeMemory(device, image.memory, 0); } uint32_t getImageMipLevels(uint32_t width, uint32_t height) { uint32_t result = 1; while (width > 1 || height > 1) { result++; width /= 2; height /= 2; } return result; } static VkSamplerCreateInfo getSamplerInfo(VkFilter filter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressMode) { VkSamplerCreateInfo createInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO }; createInfo.magFilter = filter; createInfo.minFilter = filter; createInfo.mipmapMode = mipmapMode; createInfo.addressModeU = addressMode; createInfo.addressModeV = addressMode; createInfo.addressModeW = addressMode; createInfo.minLod = 0; createInfo.maxLod = 16.f; createInfo.anisotropyEnable = mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR; createInfo.maxAnisotropy = mipmapMode == VK_SAMPLER_MIPMAP_MODE_LINEAR ? 4.f : 1.f; return createInfo; } VkSampler createSampler(VkDevice device, VkFilter filter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressMode, VkSamplerReductionModeEXT reductionMode) { VkSamplerCreateInfo createInfo = getSamplerInfo(filter, mipmapMode, addressMode); VkSamplerReductionModeCreateInfoEXT reductionInfo = { VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT }; reductionInfo.reductionMode = reductionMode; if (reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) createInfo.pNext = &reductionInfo; VkSampler sampler = 0; VK_CHECK(vkCreateSampler(device, &createInfo, 0, &sampler)); return sampler; } #if VK_EXT_descriptor_heap void getDescriptor(VkDevice device, VkImage image, VkFormat format, uint32_t mipLevel, uint32_t levelCount, VkDescriptorType type, void* descriptor, size_t descriptorSize) { VkImageAspectFlags aspectMask = (format == VK_FORMAT_D32_SFLOAT) ? VK_IMAGE_ASPECT_DEPTH_BIT : VK_IMAGE_ASPECT_COLOR_BIT; VkImageViewCreateInfo viewInfo = getImageViewInfo(image, format, mipLevel, levelCount); VkImageDescriptorInfoEXT imageInfo = { VK_STRUCTURE_TYPE_IMAGE_DESCRIPTOR_INFO_EXT }; imageInfo.pView = &viewInfo; imageInfo.layout = VK_IMAGE_LAYOUT_GENERAL; VkResourceDescriptorInfoEXT resourceInfo = { VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT }; resourceInfo.type = type; resourceInfo.data.pImage = &imageInfo; VkHostAddressRangeEXT descriptorRange = { descriptor, descriptorSize }; VK_CHECK(vkWriteResourceDescriptorsEXT(device, 1, &resourceInfo, &descriptorRange)); } void getDescriptor(VkDevice device, VkDeviceAddress address, VkDeviceSize size, VkDescriptorType type, void* descriptor, size_t descriptorSize) { VkDeviceAddressRangeEXT addressRange = { address, size }; VkResourceDescriptorInfoEXT resourceInfo = { VK_STRUCTURE_TYPE_RESOURCE_DESCRIPTOR_INFO_EXT }; resourceInfo.type = type; resourceInfo.data.pAddressRange = &addressRange; VkHostAddressRangeEXT descriptorRange = { descriptor, descriptorSize }; VK_CHECK(vkWriteResourceDescriptorsEXT(device, 1, &resourceInfo, &descriptorRange)); } void getDescriptor(VkDevice device, VkFilter filter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressMode, VkSamplerReductionModeEXT reductionMode, void* descriptor, size_t descriptorSize) { VkSamplerCreateInfo createInfo = getSamplerInfo(filter, mipmapMode, addressMode); VkSamplerReductionModeCreateInfoEXT reductionInfo = { VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT }; reductionInfo.reductionMode = reductionMode; if (reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT) createInfo.pNext = &reductionInfo; VkHostAddressRangeEXT descriptorRange = { descriptor, descriptorSize }; VK_CHECK(vkWriteSamplerDescriptorsEXT(device, 1, &createInfo, &descriptorRange)); } #endif
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/resources.h
C/C++ Header
#pragma once struct Buffer { VkBuffer buffer; VkDeviceMemory memory; void* data; size_t size; VkDeviceAddress address; }; struct Image { VkImage image; VkFormat format; VkImageView imageView; VkDeviceMemory memory; }; VkImageMemoryBarrier2 imageBarrier(VkImage image, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkImageLayout oldLayout, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask, VkImageLayout newLayout, VkImageAspectFlags aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, uint32_t baseMipLevel = 0, uint32_t levelCount = VK_REMAINING_MIP_LEVELS); VkBufferMemoryBarrier2 bufferBarrier(VkBuffer buffer, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask); void pipelineBarrier(VkCommandBuffer commandBuffer, VkDependencyFlags dependencyFlags, size_t bufferBarrierCount, const VkBufferMemoryBarrier2* bufferBarriers, size_t imageBarrierCount, const VkImageMemoryBarrier2* imageBarriers); void invalidateBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 stageMask, std::initializer_list<VkImage> colorImages, std::initializer_list<VkImage> depthImages = {}); void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 srcStageMask, VkAccessFlags2 srcAccessMask, VkPipelineStageFlags2 dstStageMask, VkAccessFlags2 dstAccessMask); void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 srcStageMask, VkPipelineStageFlags2 dstStageMask); void stageBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags2 stageMask); void createBuffer(Buffer& result, VkDevice device, const VkPhysicalDeviceMemoryProperties& memoryProperties, size_t size, VkBufferUsageFlags usage, VkMemoryPropertyFlags memoryFlags); void uploadBuffer(VkDevice device, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const Buffer& buffer, const Buffer& scratch, const void* data, size_t size); void destroyBuffer(const Buffer& buffer, VkDevice device); VkDeviceAddress getBufferAddress(const Buffer& buffer, VkDevice device); VkImageView createImageView(VkDevice device, VkImage image, VkFormat format, uint32_t mipLevel, uint32_t levelCount); void createImage(Image& result, VkDevice device, const VkPhysicalDeviceMemoryProperties& memoryProperties, uint32_t width, uint32_t height, uint32_t mipLevels, VkFormat format, VkImageUsageFlags usage); void destroyImage(const Image& image, VkDevice device); uint32_t getImageMipLevels(uint32_t width, uint32_t height); VkSampler createSampler(VkDevice device, VkFilter filter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressMode, VkSamplerReductionModeEXT reductionMode = VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT); void getDescriptor(VkDevice device, VkImage image, VkFormat format, uint32_t mipLevel, uint32_t levelCount, VkDescriptorType type, void* descriptor, size_t descriptorSize); void getDescriptor(VkDevice device, VkDeviceAddress address, VkDeviceSize size, VkDescriptorType type, void* descriptor, size_t descriptorSize); void getDescriptor(VkDevice device, VkFilter filter, VkSamplerMipmapMode mipmapMode, VkSamplerAddressMode addressMode, VkSamplerReductionModeEXT reductionMode, void* descriptor, size_t descriptorSize);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/scene.cpp
C++
#include "common.h" #include "scene.h" #include "config.h" #include <fast_obj.h> #include <cgltf.h> #include <meshoptimizer.h> #include <time.h> #include <algorithm> #include <memory> #include <cstring> static void appendMeshlet(Geometry& result, const meshopt_Meshlet& meshlet, const std::vector<vec3>& vertices, const std::vector<unsigned int>& meshlet_vertices, const std::vector<unsigned char>& meshlet_triangles, uint32_t baseVertex, bool lod0) { size_t dataOffset = result.meshletdata.size(); unsigned int minVertex = ~0u, maxVertex = 0; for (unsigned int i = 0; i < meshlet.vertex_count; ++i) { minVertex = std::min(meshlet_vertices[meshlet.vertex_offset + i], minVertex); maxVertex = std::max(meshlet_vertices[meshlet.vertex_offset + i], maxVertex); } bool shortRefs = maxVertex - minVertex < (1 << 16); for (unsigned int i = 0; i < meshlet.vertex_count; ++i) { unsigned int ref = meshlet_vertices[meshlet.vertex_offset + i] - minVertex; if (shortRefs && i % 2) result.meshletdata.back() |= ref << 16; else result.meshletdata.push_back(ref); } const unsigned int* indexGroups = reinterpret_cast<const unsigned int*>(&meshlet_triangles[0] + meshlet.triangle_offset); unsigned int indexGroupCount = (meshlet.triangle_count * 3 + 3) / 4; for (unsigned int i = 0; i < indexGroupCount; ++i) result.meshletdata.push_back(indexGroups[i]); if (lod0) { for (unsigned int i = 0; i < meshlet.vertex_count; ++i) { unsigned int vtx = meshlet_vertices[meshlet.vertex_offset + i]; unsigned short hx = meshopt_quantizeHalf(vertices[vtx].x); unsigned short hy = meshopt_quantizeHalf(vertices[vtx].y); unsigned short hz = meshopt_quantizeHalf(vertices[vtx].z); result.meshletvtx0.push_back(hx); result.meshletvtx0.push_back(hy); result.meshletvtx0.push_back(hz); result.meshletvtx0.push_back(0); } } meshopt_Bounds bounds = meshopt_computeMeshletBounds(&meshlet_vertices[meshlet.vertex_offset], &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count, &vertices[0].x, vertices.size(), sizeof(vec3)); Meshlet m = {}; m.dataOffset = uint32_t(dataOffset); m.baseVertex = baseVertex + minVertex; m.triangleCount = meshlet.triangle_count; m.vertexCount = meshlet.vertex_count; m.shortRefs = shortRefs; m.center[0] = meshopt_quantizeHalf(bounds.center[0]); m.center[1] = meshopt_quantizeHalf(bounds.center[1]); m.center[2] = meshopt_quantizeHalf(bounds.center[2]); m.radius = meshopt_quantizeHalf(bounds.radius); m.cone_axis[0] = bounds.cone_axis_s8[0]; m.cone_axis[1] = bounds.cone_axis_s8[1]; m.cone_axis[2] = bounds.cone_axis_s8[2]; m.cone_cutoff = bounds.cone_cutoff_s8; result.meshlets.push_back(m); } static size_t appendMeshlets(Geometry& result, const std::vector<vec3>& vertices, std::vector<uint32_t>& indices, uint32_t baseVertex, bool lod0, bool fast, bool clrt) { const size_t max_vertices = MESH_MAXVTX; const size_t min_triangles = MESH_MAXTRI / 4; const size_t max_triangles = MESH_MAXTRI; const float cone_weight = MESHLET_CONE_WEIGHT; const float fill_weight = MESHLET_FILL_WEIGHT; std::vector<meshopt_Meshlet> meshlets(meshopt_buildMeshletsBound(indices.size(), max_vertices, min_triangles)); std::vector<unsigned int> meshlet_vertices(indices.size()); std::vector<unsigned char> meshlet_triangles(indices.size()); if (fast) meshlets.resize(meshopt_buildMeshletsScan(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices.data(), indices.size(), vertices.size(), max_vertices, max_triangles)); else if (clrt && lod0) // only use spatial algo for lod0 as this is the only lod that is used for raytracing meshlets.resize(meshopt_buildMeshletsSpatial(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices.data(), indices.size(), &vertices[0].x, vertices.size(), sizeof(vec3), max_vertices, min_triangles, max_triangles, fill_weight)); else meshlets.resize(meshopt_buildMeshlets(meshlets.data(), meshlet_vertices.data(), meshlet_triangles.data(), indices.data(), indices.size(), &vertices[0].x, vertices.size(), sizeof(vec3), max_vertices, max_triangles, cone_weight)); for (auto& meshlet : meshlets) { meshopt_optimizeMeshlet(&meshlet_vertices[meshlet.vertex_offset], &meshlet_triangles[meshlet.triangle_offset], meshlet.triangle_count, meshlet.vertex_count); appendMeshlet(result, meshlet, vertices, meshlet_vertices, meshlet_triangles, baseVertex, lod0); } return meshlets.size(); } static bool loadObj(std::vector<Vertex>& vertices, const char* path) { fastObjMesh* obj = fast_obj_read(path); if (!obj) return false; size_t index_count = 0; for (unsigned int i = 0; i < obj->face_count; ++i) index_count += 3 * (obj->face_vertices[i] - 2); vertices.resize(index_count); size_t vertex_offset = 0; size_t index_offset = 0; for (unsigned int i = 0; i < obj->face_count; ++i) { for (unsigned int j = 0; j < obj->face_vertices[i]; ++j) { fastObjIndex gi = obj->indices[index_offset + j]; // triangulate polygon on the fly; offset-3 is always the first polygon vertex if (j >= 3) { vertices[vertex_offset + 0] = vertices[vertex_offset - 3]; vertices[vertex_offset + 1] = vertices[vertex_offset - 1]; vertex_offset += 2; } Vertex& v = vertices[vertex_offset++]; v.vx = meshopt_quantizeHalf(obj->positions[gi.p * 3 + 0]); v.vy = meshopt_quantizeHalf(obj->positions[gi.p * 3 + 1]); v.vz = meshopt_quantizeHalf(obj->positions[gi.p * 3 + 2]); v.tp = 0; v.np = (meshopt_quantizeSnorm(obj->normals[gi.n * 3 + 0], 10) + 511) | (meshopt_quantizeSnorm(obj->normals[gi.n * 3 + 1], 10) + 511) << 10 | (meshopt_quantizeSnorm(obj->normals[gi.n * 3 + 2], 10) + 511) << 20; v.tu = meshopt_quantizeHalf(obj->texcoords[gi.t * 2 + 0]); v.tv = meshopt_quantizeHalf(obj->texcoords[gi.t * 2 + 1]); } index_offset += obj->face_vertices[i]; } assert(vertex_offset == index_count); fast_obj_destroy(obj); return true; } static void appendMesh(Geometry& result, std::vector<Vertex>& vertices, std::vector<uint32_t>& indices, bool buildMeshlets, bool fast, bool clrt) { std::vector<uint32_t> remap(vertices.size()); size_t uniqueVertices = meshopt_generateVertexRemap(remap.data(), indices.data(), indices.size(), vertices.data(), vertices.size(), sizeof(Vertex)); meshopt_remapVertexBuffer(vertices.data(), vertices.data(), vertices.size(), sizeof(Vertex), remap.data()); meshopt_remapIndexBuffer(indices.data(), indices.data(), indices.size(), remap.data()); vertices.resize(uniqueVertices); if (fast) meshopt_optimizeVertexCacheFifo(indices.data(), indices.data(), indices.size(), vertices.size(), 16); else meshopt_optimizeVertexCache(indices.data(), indices.data(), indices.size(), vertices.size()); meshopt_optimizeVertexFetch(vertices.data(), indices.data(), indices.size(), vertices.data(), vertices.size(), sizeof(Vertex)); Mesh mesh = {}; mesh.vertexOffset = uint32_t(result.vertices.size()); mesh.vertexCount = uint32_t(vertices.size()); result.vertices.insert(result.vertices.end(), vertices.begin(), vertices.end()); std::vector<vec3> positions(vertices.size()); for (size_t i = 0; i < vertices.size(); ++i) { Vertex& v = vertices[i]; positions[i] = vec3(meshopt_dequantizeHalf(v.vx), meshopt_dequantizeHalf(v.vy), meshopt_dequantizeHalf(v.vz)); } std::vector<vec3> normals(vertices.size()); for (size_t i = 0; i < vertices.size(); ++i) { Vertex& v = vertices[i]; normals[i] = vec3((v.np & 1023) / 511.f - 1.f, ((v.np >> 10) & 1023) / 511.f - 1.f, ((v.np >> 20) & 1023) / 511.f - 1.f); } vec3 center = vec3(0); for (auto& v : positions) center += v; center /= float(vertices.size()); float radius = 0; for (auto& v : positions) radius = std::max(radius, distance(center, v)); mesh.center = center; mesh.radius = radius; float lodScale = meshopt_simplifyScale(&positions[0].x, vertices.size(), sizeof(vec3)); std::vector<uint32_t> lodIndices = indices; float lodError = 0.f; float normalWeights[3] = { 1.f, 1.f, 1.f }; while (mesh.lodCount < COUNTOF(mesh.lods)) { MeshLod& lod = mesh.lods[mesh.lodCount++]; lod.indexOffset = uint32_t(result.indices.size()); lod.indexCount = uint32_t(lodIndices.size()); result.indices.insert(result.indices.end(), lodIndices.begin(), lodIndices.end()); lod.meshletOffset = uint32_t(result.meshlets.size()); lod.meshletCount = buildMeshlets ? uint32_t(appendMeshlets(result, positions, lodIndices, mesh.vertexOffset, &lod == mesh.lods, fast, clrt)) : 0; lod.error = lodError * lodScale; if (mesh.lodCount < COUNTOF(mesh.lods)) { // note: we're using the same value for all LODs; if this changes, we need to remove/change 85% exit criteria below const float maxError = 1e-1f; const unsigned int options = meshopt_SimplifySparse; size_t nextIndicesTarget = (size_t(double(lodIndices.size()) * 0.6) / 3) * 3; float nextError = 0.f; size_t nextIndices = meshopt_simplifyWithAttributes(lodIndices.data(), lodIndices.data(), lodIndices.size(), &positions[0].x, vertices.size(), sizeof(vec3), &normals[0].x, sizeof(vec3), normalWeights, 3, NULL, nextIndicesTarget, maxError, options, &nextError); assert(nextIndices <= lodIndices.size()); // we've reached the error bound if (nextIndices == lodIndices.size() || nextIndices == 0) break; // while we could keep this LOD, it's too close to the last one (and it can't go below that due to constant error bound above) if (nextIndices >= size_t(double(lodIndices.size()) * 0.85)) break; lodIndices.resize(nextIndices); lodError = std::max(lodError * 1.5f, nextError); // important! since we start from last LOD, we need to accumulate the error if (fast) meshopt_optimizeVertexCacheFifo(lodIndices.data(), lodIndices.data(), lodIndices.size(), vertices.size(), 16); else meshopt_optimizeVertexCache(lodIndices.data(), lodIndices.data(), lodIndices.size(), vertices.size()); } } result.meshes.push_back(mesh); } bool loadMesh(Geometry& geometry, const char* path, bool buildMeshlets, bool fast, bool clrt) { std::vector<Vertex> vertices; if (!loadObj(vertices, path)) return false; std::vector<uint32_t> indices(vertices.size()); for (size_t i = 0; i < indices.size(); ++i) indices[i] = uint32_t(i); appendMesh(geometry, vertices, indices, buildMeshlets, fast, clrt); return true; } static void decomposeTransform(float translation[3], float rotation[4], float scale[3], const float* transform) { float m[4][4] = {}; memcpy(m, transform, 16 * sizeof(float)); // extract translation from last row translation[0] = m[3][0]; translation[1] = m[3][1]; translation[2] = m[3][2]; // compute determinant to determine handedness float det = m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); float sign = (det < 0.f) ? -1.f : 1.f; // recover scale from axis lengths scale[0] = sqrtf(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]) * sign; scale[1] = sqrtf(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]) * sign; scale[2] = sqrtf(m[2][0] * m[2][0] + m[2][1] * m[2][1] + m[2][2] * m[2][2]) * sign; // normalize axes to get a pure rotation matrix float rsx = (scale[0] == 0.f) ? 0.f : 1.f / scale[0]; float rsy = (scale[1] == 0.f) ? 0.f : 1.f / scale[1]; float rsz = (scale[2] == 0.f) ? 0.f : 1.f / scale[2]; float r00 = m[0][0] * rsx, r10 = m[1][0] * rsy, r20 = m[2][0] * rsz; float r01 = m[0][1] * rsx, r11 = m[1][1] * rsy, r21 = m[2][1] * rsz; float r02 = m[0][2] * rsx, r12 = m[1][2] * rsy, r22 = m[2][2] * rsz; // "branchless" version of Mike Day's matrix to quaternion conversion int qc = r22 < 0 ? (r00 > r11 ? 0 : 1) : (r00 < -r11 ? 2 : 3); float qs1 = qc & 2 ? -1.f : 1.f; float qs2 = qc & 1 ? -1.f : 1.f; float qs3 = (qc - 1) & 2 ? -1.f : 1.f; float qt = 1.f - qs3 * r00 - qs2 * r11 - qs1 * r22; float qs = 0.5f / sqrtf(qt); rotation[qc ^ 0] = qs * qt; rotation[qc ^ 1] = qs * (r01 + qs1 * r10); rotation[qc ^ 2] = qs * (r20 + qs2 * r02); rotation[qc ^ 3] = qs * (r12 + qs3 * r21); } static void loadVertices(std::vector<Vertex>& vertices, const cgltf_primitive& prim) { size_t vertexCount = vertices.size(); std::vector<float> scratch(vertexCount * 4); if (const cgltf_accessor* pos = cgltf_find_accessor(&prim, cgltf_attribute_type_position, 0)) { assert(cgltf_num_components(pos->type) == 3); cgltf_accessor_unpack_floats(pos, scratch.data(), vertexCount * 3); for (size_t j = 0; j < vertexCount; ++j) { vertices[j].vx = meshopt_quantizeHalf(scratch[j * 3 + 0]); vertices[j].vy = meshopt_quantizeHalf(scratch[j * 3 + 1]); vertices[j].vz = meshopt_quantizeHalf(scratch[j * 3 + 2]); } } if (const cgltf_accessor* nrm = cgltf_find_accessor(&prim, cgltf_attribute_type_normal, 0)) { assert(cgltf_num_components(nrm->type) == 3); cgltf_accessor_unpack_floats(nrm, scratch.data(), vertexCount * 3); for (size_t j = 0; j < vertexCount; ++j) { float nx = scratch[j * 3 + 0], ny = scratch[j * 3 + 1], nz = scratch[j * 3 + 2]; vertices[j].np = (meshopt_quantizeSnorm(nx, 10) + 511) | (meshopt_quantizeSnorm(ny, 10) + 511) << 10 | (meshopt_quantizeSnorm(nz, 10) + 511) << 20; } } if (const cgltf_accessor* tan = cgltf_find_accessor(&prim, cgltf_attribute_type_tangent, 0)) { assert(cgltf_num_components(tan->type) == 4); cgltf_accessor_unpack_floats(tan, scratch.data(), vertexCount * 4); for (size_t j = 0; j < vertexCount; ++j) { float tx = scratch[j * 4 + 0], ty = scratch[j * 4 + 1], tz = scratch[j * 4 + 2]; float tsum = fabsf(tx) + fabsf(ty) + fabsf(tz); float tu = tz >= 0 ? tx / tsum : (1 - fabsf(ty / tsum)) * (tx >= 0 ? 1 : -1); float tv = tz >= 0 ? ty / tsum : (1 - fabsf(tx / tsum)) * (ty >= 0 ? 1 : -1); vertices[j].tp = (meshopt_quantizeSnorm(tu, 8) + 127) | (meshopt_quantizeSnorm(tv, 8) + 127) << 8; vertices[j].np |= (scratch[j * 4 + 3] >= 0 ? 0 : 1) << 30; } } if (const cgltf_accessor* tex = cgltf_find_accessor(&prim, cgltf_attribute_type_texcoord, 0)) { assert(cgltf_num_components(tex->type) == 2); cgltf_accessor_unpack_floats(tex, scratch.data(), vertexCount * 2); for (size_t j = 0; j < vertexCount; ++j) { vertices[j].tu = meshopt_quantizeHalf(scratch[j * 2 + 0]); vertices[j].tv = meshopt_quantizeHalf(scratch[j * 2 + 1]); } } } bool loadScene(Geometry& geometry, std::vector<Material>& materials, std::vector<MeshDraw>& draws, std::vector<std::string>& texturePaths, std::vector<Animation>& animations, Camera& camera, vec3& sunDirection, const char* path, bool buildMeshlets, bool fast, bool clrt) { clock_t timer = clock(); cgltf_options options = {}; cgltf_data* data = NULL; cgltf_result res = cgltf_parse_file(&options, path, &data); if (res != cgltf_result_success) return false; std::unique_ptr<cgltf_data, void (*)(cgltf_data*)> dataPtr(data, &cgltf_free); res = cgltf_load_buffers(&options, data, path); if (res != cgltf_result_success) return false; res = cgltf_validate(data); if (res != cgltf_result_success) return false; std::vector<std::pair<unsigned int, unsigned int>> primitives; std::vector<cgltf_material*> primitiveMaterials; size_t firstMeshOffset = geometry.meshes.size(); for (size_t i = 0; i < data->meshes_count; ++i) { const cgltf_mesh& mesh = data->meshes[i]; size_t meshOffset = geometry.meshes.size(); for (size_t pi = 0; pi < mesh.primitives_count; ++pi) { const cgltf_primitive& prim = mesh.primitives[pi]; if (prim.type != cgltf_primitive_type_triangles || !prim.indices) continue; std::vector<Vertex> vertices(prim.attributes[0].data->count); loadVertices(vertices, prim); std::vector<uint32_t> indices(prim.indices->count); cgltf_accessor_unpack_indices(prim.indices, indices.data(), 4, indices.size()); appendMesh(geometry, vertices, indices, buildMeshlets, fast, clrt); primitiveMaterials.push_back(prim.material); } primitives.push_back(std::make_pair(unsigned(meshOffset), unsigned(geometry.meshes.size() - meshOffset))); } assert(primitiveMaterials.size() + firstMeshOffset == geometry.meshes.size()); std::vector<int> nodeDraws(data->nodes_count, -1); // for animations size_t materialOffset = materials.size(); assert(materialOffset > 0); // index 0 = dummy materials for (size_t i = 0; i < data->nodes_count; ++i) { const cgltf_node* node = &data->nodes[i]; if (node->mesh) { float matrix[16]; cgltf_node_transform_world(node, matrix); float translation[3]; float rotation[4]; float scale[3]; decomposeTransform(translation, rotation, scale, matrix); // TODO: better warnings for non-uniform or negative scale std::pair<unsigned int, unsigned int> range = primitives[cgltf_mesh_index(data, node->mesh)]; for (unsigned int j = 0; j < range.second; ++j) { MeshDraw draw = {}; draw.position = vec3(translation[0], translation[1], translation[2]); draw.scale = std::max(scale[0], std::max(scale[1], scale[2])); draw.orientation = quat(rotation[0], rotation[1], rotation[2], rotation[3]); draw.meshIndex = range.first + j; cgltf_material* material = primitiveMaterials[range.first + j - firstMeshOffset]; draw.materialIndex = material ? materialOffset + int(cgltf_material_index(data, material)) : 0; if (material && material->alpha_mode != cgltf_alpha_mode_opaque) draw.postPass = 1; if (material && material->has_transmission) draw.postPass = 2; nodeDraws[i] = int(draws.size()); draws.push_back(draw); } } if (node->camera) { float matrix[16]; cgltf_node_transform_world(node, matrix); float translation[3]; float rotation[4]; float scale[3]; decomposeTransform(translation, rotation, scale, matrix); assert(node->camera->type == cgltf_camera_type_perspective); camera.position = vec3(translation[0], translation[1], translation[2]); camera.orientation = quat(rotation[0], rotation[1], rotation[2], rotation[3]); camera.fovY = node->camera->data.perspective.yfov; } if (node->light && node->light->type == cgltf_light_type_directional) { float matrix[16]; cgltf_node_transform_world(node, matrix); sunDirection = vec3(matrix[8], matrix[9], matrix[10]); } } int textureOffset = 1 + int(texturePaths.size()); for (size_t i = 0; i < data->materials_count; ++i) { cgltf_material* material = &data->materials[i]; Material mat = {}; mat.diffuseFactor = vec4(1); if (material->has_pbr_specular_glossiness) { if (material->pbr_specular_glossiness.diffuse_texture.texture) mat.albedoTexture = textureOffset + int(cgltf_texture_index(data, material->pbr_specular_glossiness.diffuse_texture.texture)); mat.diffuseFactor = vec4(material->pbr_specular_glossiness.diffuse_factor[0], material->pbr_specular_glossiness.diffuse_factor[1], material->pbr_specular_glossiness.diffuse_factor[2], material->pbr_specular_glossiness.diffuse_factor[3]); if (material->pbr_specular_glossiness.specular_glossiness_texture.texture) mat.specularTexture = textureOffset + int(cgltf_texture_index(data, material->pbr_specular_glossiness.specular_glossiness_texture.texture)); mat.specularFactor = vec4(material->pbr_specular_glossiness.specular_factor[0], material->pbr_specular_glossiness.specular_factor[1], material->pbr_specular_glossiness.specular_factor[2], material->pbr_specular_glossiness.glossiness_factor); } else if (material->has_pbr_metallic_roughness) { if (material->pbr_metallic_roughness.base_color_texture.texture) mat.albedoTexture = textureOffset + int(cgltf_texture_index(data, material->pbr_metallic_roughness.base_color_texture.texture)); mat.diffuseFactor = vec4(material->pbr_metallic_roughness.base_color_factor[0], material->pbr_metallic_roughness.base_color_factor[1], material->pbr_metallic_roughness.base_color_factor[2], material->pbr_metallic_roughness.base_color_factor[3]); if (material->pbr_metallic_roughness.metallic_roughness_texture.texture) mat.specularTexture = textureOffset + int(cgltf_texture_index(data, material->pbr_metallic_roughness.metallic_roughness_texture.texture)); mat.specularFactor = vec4(1, 1, 1, 1 - material->pbr_metallic_roughness.roughness_factor); } if (material->normal_texture.texture) mat.normalTexture = textureOffset + int(cgltf_texture_index(data, material->normal_texture.texture)); if (material->emissive_texture.texture) mat.emissiveTexture = textureOffset + int(cgltf_texture_index(data, material->emissive_texture.texture)); mat.emissiveFactor = vec3(material->emissive_factor[0], material->emissive_factor[1], material->emissive_factor[2]); materials.push_back(mat); } for (size_t i = 0; i < data->textures_count; ++i) { cgltf_texture* texture = &data->textures[i]; assert(texture->image); cgltf_image* image = texture->image; assert(image->uri); std::string ipath = path; std::string::size_type pos = ipath.find_last_of("/\\"); if (pos == std::string::npos) ipath = ""; else ipath = ipath.substr(0, pos + 1); std::string uri = image->uri; uri.resize(cgltf_decode_uri(&uri[0])); std::string::size_type dot = uri.find_last_of('.'); if (dot != std::string::npos) uri.replace(dot, uri.size() - dot, ".dds"); texturePaths.push_back(ipath + uri); } std::vector<cgltf_animation_sampler*> samplersT(data->nodes_count); std::vector<cgltf_animation_sampler*> samplersR(data->nodes_count); std::vector<cgltf_animation_sampler*> samplersS(data->nodes_count); for (size_t i = 0; i < data->animations_count; ++i) { cgltf_animation* anim = &data->animations[i]; for (size_t j = 0; j < anim->channels_count; ++j) { cgltf_animation_channel* channel = &anim->channels[j]; cgltf_animation_sampler* sampler = channel->sampler; if (!channel->target_node) continue; if (channel->target_path == cgltf_animation_path_type_translation) samplersT[cgltf_node_index(data, channel->target_node)] = sampler; else if (channel->target_path == cgltf_animation_path_type_rotation) samplersR[cgltf_node_index(data, channel->target_node)] = sampler; else if (channel->target_path == cgltf_animation_path_type_scale) samplersS[cgltf_node_index(data, channel->target_node)] = sampler; } } for (size_t i = 0; i < data->nodes_count; ++i) { if (!samplersR[i] && !samplersT[i] && !samplersS[i]) continue; if (nodeDraws[i] == -1) { fprintf(stderr, "Warning: skipping animation for node %d without draw\n", int(i)); continue; } cgltf_accessor* input = 0; if (samplersT[i]) input = samplersT[i]->input; else if (samplersR[i]) input = samplersR[i]->input; else if (samplersS[i]) input = samplersS[i]->input; if ((samplersT[i] && samplersT[i]->input->count != input->count) || (samplersR[i] && samplersR[i]->input->count != input->count) || (samplersS[i] && samplersS[i]->input->count != input->count)) { fprintf(stderr, "Warning: skipping animation for node %d due to mismatched sampler counts\n", int(i)); continue; } if ((samplersT[i] && samplersT[i]->interpolation != cgltf_interpolation_type_linear) || (samplersR[i] && samplersR[i]->interpolation != cgltf_interpolation_type_linear) || (samplersS[i] && samplersS[i]->interpolation != cgltf_interpolation_type_linear)) { fprintf(stderr, "Warning: skipping animation for node %d due to mismatched sampler counts\n", int(i)); continue; } if (input->count < 2) { fprintf(stderr, "Warning: skipping animation for node %d with %d keyframes\n", int(i), int(input->count)); continue; } std::vector<float> times(input->count); cgltf_accessor_unpack_floats(input, times.data(), times.size()); Animation animation = {}; animation.drawIndex = nodeDraws[i]; animation.startTime = times[0]; animation.period = times[1] - times[0]; std::vector<float> valuesR, valuesT, valuesS; if (samplersT[i]) { valuesT.resize(samplersT[i]->output->count * 3); cgltf_accessor_unpack_floats(samplersT[i]->output, valuesT.data(), valuesT.size()); } if (samplersR[i]) { valuesR.resize(samplersR[i]->output->count * 4); cgltf_accessor_unpack_floats(samplersR[i]->output, valuesR.data(), valuesR.size()); } if (samplersS[i]) { valuesS.resize(samplersS[i]->output->count * 3); cgltf_accessor_unpack_floats(samplersS[i]->output, valuesS.data(), valuesS.size()); } cgltf_node nodeCopy = data->nodes[i]; for (size_t j = 0; j < input->count; ++j) { if (samplersT[i]) memcpy(nodeCopy.translation, &valuesT[j * 3], 3 * sizeof(float)); if (samplersR[i]) memcpy(nodeCopy.rotation, &valuesR[j * 4], 4 * sizeof(float)); if (samplersS[i]) memcpy(nodeCopy.scale, &valuesS[j * 3], 3 * sizeof(float)); float matrix[16]; cgltf_node_transform_world(&nodeCopy, matrix); float translation[3]; float rotation[4]; float scale[3]; decomposeTransform(translation, rotation, scale, matrix); Keyframe kf = {}; kf.translation = vec3(translation[0], translation[1], translation[2]); kf.rotation = quat(rotation[0], rotation[1], rotation[2], rotation[3]); kf.scale = std::max(scale[0], std::max(scale[1], scale[2])); animation.keyframes.push_back(kf); } animations.push_back(std::move(animation)); } printf("Loaded %s: %d meshes, %d draws, %d animations, %d vertices in %.2f sec\n", path, int(geometry.meshes.size()), int(draws.size()), int(animations.size()), int(geometry.vertices.size()), double(clock() - timer) / CLOCKS_PER_SEC); if (buildMeshlets) { unsigned int meshletVtxs = 0, meshletTris = 0; for (Meshlet& meshlet : geometry.meshlets) { meshletVtxs += meshlet.vertexCount; meshletTris += meshlet.triangleCount; } printf("Meshlets: %d meshlets, %d triangles, %d vertex refs\n", int(geometry.meshlets.size()), int(meshletTris), int(meshletVtxs)); } return true; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/scene.h
C/C++ Header
#pragma once #include "math.h" #include <stdint.h> #include <string> #include <vector> struct alignas(8) Meshlet { uint16_t center[3]; uint16_t radius; int8_t cone_axis[3]; int8_t cone_cutoff; uint32_t dataOffset; // dataOffset..dataOffset+vertexCount-1 stores vertex indices, we store indices packed in 4b units after that uint32_t baseVertex; uint8_t vertexCount; uint8_t triangleCount; uint8_t shortRefs; uint8_t padding; }; struct alignas(16) Material { int albedoTexture; int normalTexture; int specularTexture; int emissiveTexture; vec4 diffuseFactor; vec4 specularFactor; vec3 emissiveFactor; }; struct alignas(16) MeshDraw { vec3 position; float scale; quat orientation; uint32_t meshIndex; uint32_t meshletVisibilityOffset; uint32_t postPass; uint32_t materialIndex; }; struct Vertex { uint16_t vx, vy, vz; uint16_t tp; // packed tangent: 8-8 octahedral uint32_t np; // packed normal: 10-10-10-2 vector + bitangent sign uint16_t tu, tv; }; struct MeshLod { uint32_t indexOffset; uint32_t indexCount; uint32_t meshletOffset; uint32_t meshletCount; float error; }; struct alignas(16) Mesh { vec3 center; float radius; uint32_t vertexOffset; uint32_t vertexCount; uint32_t lodCount; MeshLod lods[8]; }; struct Geometry { // TODO: remove these vectors - they are just scratch copies that waste space std::vector<Vertex> vertices; std::vector<uint32_t> indices; std::vector<Meshlet> meshlets; std::vector<uint32_t> meshletdata; std::vector<uint16_t> meshletvtx0; // 4 position components per vertex referenced by meshlets in lod 0, packed tightly std::vector<Mesh> meshes; }; struct Camera { vec3 position; quat orientation; float fovY; float znear; }; struct Keyframe { vec3 translation; float scale; quat rotation; }; struct Animation { uint32_t drawIndex; float startTime; float period; std::vector<Keyframe> keyframes; }; bool loadMesh(Geometry& geometry, const char* path, bool buildMeshlets, bool fast = false, bool clrt = false); bool loadScene(Geometry& geometry, std::vector<Material>& materials, std::vector<MeshDraw>& draws, std::vector<std::string>& texturePaths, std::vector<Animation>& animations, Camera& camera, vec3& sunDirection, const char* path, bool buildMeshlets, bool fast = false, bool clrt = false); bool saveSceneCache(const char* path, const Geometry& geometry, const std::vector<Material>& materials, const std::vector<MeshDraw>& draws, const std::vector<std::string>& texturePaths, const Camera& camera, const vec3& sunDirection, bool clrtMode, bool compressed, bool verbose); bool loadSceneCache(const char* path, Geometry& geometry, std::vector<Material>& materials, std::vector<MeshDraw>& draws, std::vector<std::string>& texturePaths, Camera& camera, vec3& sunDirection, bool clrtMode);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/scenecache.cpp
C++
#include "common.h" #include "scene.h" #include "config.h" #include "fileutils.h" #include "meshoptimizer.h" #include <stdio.h> #include <string.h> const uint32_t kSceneCacheMagic = 0x434E4353; // 'SCNC' const uint32_t kSceneCacheVersion = 3; struct SceneHeader { uint32_t magic; uint32_t version; uint32_t meshletMaxVertices; uint32_t meshletMaxTriangles; bool clrtMode; bool compressed; uint32_t compressedVertexBytes; uint32_t compressedIndexBytes; uint32_t compressedMeshletDataBytes; uint32_t compressedMeshletVtx0Bytes; uint32_t vertexCount; uint32_t indexCount; uint32_t meshletCount; uint32_t meshletdataCount; uint32_t meshletvtx0Count; uint32_t meshCount; uint32_t materialCount; uint32_t drawCount; uint32_t texturePathCount; Camera camera; vec3 sunDirection; }; static size_t writeVertexCompressed(const void* vertices, size_t stride, size_t count, FILE* file, int level = 2) { size_t bound = meshopt_encodeVertexBufferBound(count, stride); std::vector<unsigned char> buf(bound); buf.resize(meshopt_encodeVertexBufferLevel(buf.data(), buf.size(), vertices, count, stride, level)); fwrite(buf.data(), 1, buf.size(), file); return buf.size(); } static size_t writeIndexCompressed(const uint32_t* indices, size_t count, FILE* file) { size_t bound = meshopt_encodeIndexBufferBound(count, ~0u); // TODO: vertex_count could be optional somehow std::vector<unsigned char> buf(bound); buf.resize(meshopt_encodeIndexBuffer(buf.data(), buf.size(), indices, count)); fwrite(buf.data(), 1, buf.size(), file); return buf.size(); } static size_t writeMeshletDataCompressed(const std::vector<Meshlet>& meshlets, const std::vector<uint32_t>& meshletdata, FILE* file) { std::vector<unsigned char> encoded(meshopt_encodeMeshletBound(MESH_MAXVTX, MESH_MAXTRI)); std::vector<unsigned int> refs(MESH_MAXVTX); size_t total = 0; for (const Meshlet& meshlet : meshlets) { const uint32_t* data = meshletdata.data() + meshlet.dataOffset; size_t vertexWords = meshlet.shortRefs ? (meshlet.vertexCount + 1) / 2 : meshlet.vertexCount; const unsigned int* vertices = data; if (meshlet.shortRefs) { const uint16_t* refs16 = reinterpret_cast<const uint16_t*>(data); for (unsigned int i = 0; i < meshlet.vertexCount; ++i) refs[i] = refs16[i]; vertices = refs.data(); } const unsigned char* triangles = reinterpret_cast<const unsigned char*>(data + vertexWords); size_t encodedSize = meshopt_encodeMeshlet(encoded.data(), encoded.size(), vertices, meshlet.vertexCount, triangles, meshlet.triangleCount); uint16_t encodedSize16 = uint16_t(encodedSize); fwrite(&encodedSize16, sizeof(encodedSize16), 1, file); fwrite(encoded.data(), 1, encodedSize, file); total += sizeof(encodedSize16) + encodedSize; } return total; } bool saveSceneCache(const char* path, const Geometry& geometry, const std::vector<Material>& materials, const std::vector<MeshDraw>& draws, const std::vector<std::string>& texturePaths, const Camera& camera, const vec3& sunDirection, bool clrtMode, bool compressed, bool verbose) { FILE* file = fopen(path, "wb"); if (!file) return false; SceneHeader header; memset(&header, 0, sizeof(header)); header.magic = kSceneCacheMagic; header.version = kSceneCacheVersion; header.meshletMaxVertices = MESH_MAXVTX; header.meshletMaxTriangles = MESH_MAXTRI; header.clrtMode = clrtMode; header.compressed = compressed; header.vertexCount = geometry.vertices.size(); header.indexCount = geometry.indices.size(); header.meshletCount = geometry.meshlets.size(); header.meshletdataCount = geometry.meshletdata.size(); header.meshletvtx0Count = geometry.meshletvtx0.size(); header.meshCount = geometry.meshes.size(); header.materialCount = materials.size(); header.drawCount = draws.size(); header.texturePathCount = texturePaths.size(); header.camera = camera; header.sunDirection = sunDirection; fwrite(&header, sizeof(header), 1, file); if (compressed) header.compressedVertexBytes = writeVertexCompressed(geometry.vertices.data(), sizeof(Vertex), geometry.vertices.size(), file); else fwrite(geometry.vertices.data(), sizeof(Vertex), geometry.vertices.size(), file); if (compressed) header.compressedIndexBytes = writeIndexCompressed(geometry.indices.data(), geometry.indices.size(), file); else fwrite(geometry.indices.data(), sizeof(uint32_t), geometry.indices.size(), file); fwrite(geometry.meshlets.data(), sizeof(Meshlet), geometry.meshlets.size(), file); if (compressed) header.compressedMeshletDataBytes = writeMeshletDataCompressed(geometry.meshlets, geometry.meshletdata, file); else fwrite(geometry.meshletdata.data(), sizeof(uint32_t), geometry.meshletdata.size(), file); if (compressed) header.compressedMeshletVtx0Bytes = writeVertexCompressed(geometry.meshletvtx0.data(), sizeof(uint16_t) * 4, geometry.meshletvtx0.size() / 4, file); else fwrite(geometry.meshletvtx0.data(), sizeof(uint16_t), geometry.meshletvtx0.size(), file); fwrite(geometry.meshes.data(), sizeof(Mesh), geometry.meshes.size(), file); fwrite(materials.data(), sizeof(Material), materials.size(), file); fwrite(draws.data(), sizeof(MeshDraw), draws.size(), file); for (const std::string& path : texturePaths) { char buf[128] = {}; strncpy(buf, path.c_str(), sizeof(buf) - 1); fwrite(buf, sizeof(buf), 1, file); } // fixup final header fseek(file, 0, SEEK_SET); fwrite(&header, sizeof(header), 1, file); fclose(file); if (verbose) { printf("Scene cache saved to %s\n", path); if (compressed) printf("Vertex data: %.2f MB (%.2f MB compressed)\n", double(geometry.vertices.size() * sizeof(Vertex)) / 1e6, double(header.compressedVertexBytes) / 1e6); else printf("Vertex data: %.2f MB\n", double(geometry.vertices.size() * sizeof(Vertex)) / 1e6); if (compressed) printf("Index data: %.2f MB (%.2f MB compressed)\n", double(geometry.indices.size() * sizeof(uint32_t)) / 1e6, double(header.compressedIndexBytes) / 1e6); else printf("Index data: %.2f MB\n", double(geometry.indices.size() * sizeof(uint32_t)) / 1e6); printf("Meshlet headers: %.2f MB\n", double(geometry.meshlets.size() * sizeof(Meshlet)) / 1e6); if (compressed) printf("Meshlet data: %.2f MB (%.2f MB compressed)\n", double(geometry.meshletdata.size() * sizeof(uint32_t)) / 1e6, double(header.compressedMeshletDataBytes) / 1e6); else printf("Meshlet data: %.2f MB\n", double(geometry.meshletdata.size() * sizeof(uint32_t)) / 1e6); if (compressed) printf("Meshlet RT data: %.2f MB (%.2f MB compressed)\n", double(geometry.meshletvtx0.size() * sizeof(uint16_t)) / 1e6, double(header.compressedMeshletVtx0Bytes) / 1e6); else printf("Meshlet RT data: %.2f MB\n", double(geometry.meshletvtx0.size() * sizeof(uint16_t)) / 1e6); } return true; } static void read(void* data, size_t size, size_t count, void* fileMemory, size_t& fileOffset) { memcpy(data, (char*)fileMemory + fileOffset, size * count); fileOffset += size * count; } static void readVertexCompressed(void* data, size_t size, size_t count, size_t compressedBytes, void* fileMemory, size_t& fileOffset) { meshopt_decodeVertexBuffer(data, count, size, (unsigned char*)fileMemory + fileOffset, compressedBytes); fileOffset += compressedBytes; } static void readIndexCompressed(unsigned int* data, size_t count, size_t compressedBytes, void* fileMemory, size_t& fileOffset) { meshopt_decodeIndexBuffer(data, count, (unsigned char*)fileMemory + fileOffset, compressedBytes); fileOffset += compressedBytes; } static void readMeshletDataCompressed(const std::vector<Meshlet>& meshlets, std::vector<uint32_t>& meshletdata, void* fileMemory, size_t& fileOffset) { for (const Meshlet& meshlet : meshlets) { uint16_t encodedSize = 0; read(&encodedSize, sizeof(encodedSize), 1, fileMemory, fileOffset); uint32_t* data = meshletdata.data() + meshlet.dataOffset; size_t vertexWords = meshlet.shortRefs ? (meshlet.vertexCount + 1) / 2 : meshlet.vertexCount; size_t vertexSize = meshlet.shortRefs ? 2 : 4; meshopt_decodeMeshlet(data, meshlet.vertexCount, vertexSize, data + vertexWords, meshlet.triangleCount, 3, (unsigned char*)fileMemory + fileOffset, encodedSize); fileOffset += encodedSize; } } bool loadSceneCache(const char* path, Geometry& geometry, std::vector<Material>& materials, std::vector<MeshDraw>& draws, std::vector<std::string>& texturePaths, Camera& camera, vec3& sunDirection, bool clrtMode) { size_t fileSize; void* file = mmapFile(path, &fileSize); if (!file || fileSize < sizeof(SceneHeader)) return false; SceneHeader header = {}; memcpy(&header, file, sizeof(header)); if (header.magic != kSceneCacheMagic || header.version != kSceneCacheVersion || header.meshletMaxVertices != MESH_MAXVTX || header.meshletMaxTriangles != MESH_MAXTRI || header.clrtMode != clrtMode) { unmapFile(file, fileSize); return false; } size_t fileOffset = sizeof(header); geometry.vertices.resize(header.vertexCount); geometry.indices.resize(header.indexCount); geometry.meshlets.resize(header.meshletCount); geometry.meshletdata.resize(header.meshletdataCount); geometry.meshletvtx0.resize(header.meshletvtx0Count); geometry.meshes.resize(header.meshCount); materials.resize(header.materialCount); draws.resize(header.drawCount); texturePaths.resize(header.texturePathCount); if (header.compressed) readVertexCompressed(geometry.vertices.data(), sizeof(Vertex), geometry.vertices.size(), header.compressedVertexBytes, file, fileOffset); else read(geometry.vertices.data(), sizeof(Vertex), geometry.vertices.size(), file, fileOffset); if (header.compressed) readIndexCompressed(geometry.indices.data(), geometry.indices.size(), header.compressedIndexBytes, file, fileOffset); else read(geometry.indices.data(), sizeof(uint32_t), geometry.indices.size(), file, fileOffset); read(geometry.meshlets.data(), sizeof(Meshlet), geometry.meshlets.size(), file, fileOffset); if (header.compressed) readMeshletDataCompressed(geometry.meshlets, geometry.meshletdata, file, fileOffset); else read(geometry.meshletdata.data(), sizeof(uint32_t), geometry.meshletdata.size(), file, fileOffset); if (header.compressed) readVertexCompressed(geometry.meshletvtx0.data(), sizeof(uint16_t) * 4, geometry.meshletvtx0.size() / 4, header.compressedMeshletVtx0Bytes, file, fileOffset); else read(geometry.meshletvtx0.data(), sizeof(uint16_t), geometry.meshletvtx0.size(), file, fileOffset); read(geometry.meshes.data(), sizeof(Mesh), geometry.meshes.size(), file, fileOffset); read(materials.data(), sizeof(Material), materials.size(), file, fileOffset); read(draws.data(), sizeof(MeshDraw), draws.size(), file, fileOffset); for (std::string& path : texturePaths) { char buf[128] = {}; read(buf, sizeof(buf), 1, file, fileOffset); buf[sizeof(buf) - 1] = 0; path = buf; } unmapFile(file, fileSize); camera = header.camera; sunDirection = header.sunDirection; return true; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/scenert.cpp
C++
#include "common.h" #include "scenert.h" #include "scene.h" #include "resources.h" #include "config.h" #include <string.h> const VkBuildAccelerationStructureFlagsKHR kBuildBLAS = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; const VkBuildAccelerationStructureFlagsKHR kBuildCLAS = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; const VkBuildAccelerationStructureFlagsKHR kBuildTLAS = VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR; void buildBLAS(VkDevice device, const std::vector<Mesh>& meshes, const Buffer& vb, const Buffer& ib, std::vector<VkAccelerationStructureKHR>& blas, std::vector<VkDeviceSize>& compactedSizes, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties) { std::vector<uint32_t> primitiveCounts(meshes.size()); std::vector<VkAccelerationStructureGeometryKHR> geometries(meshes.size()); std::vector<VkAccelerationStructureBuildGeometryInfoKHR> buildInfos(meshes.size()); const size_t kAlignment = 256; // required by spec for acceleration structures, could be smaller for scratch but it's a small waste const size_t kDefaultScratch = 32 * 1024 * 1024; // 32 MB scratch by default size_t totalAccelerationSize = 0; size_t totalPrimitiveCount = 0; size_t maxScratchSize = 0; std::vector<size_t> accelerationOffsets(meshes.size()); std::vector<size_t> accelerationSizes(meshes.size()); std::vector<size_t> scratchSizes(meshes.size()); VkDeviceAddress vbAddress = getBufferAddress(vb, device); VkDeviceAddress ibAddress = getBufferAddress(ib, device); for (size_t i = 0; i < meshes.size(); ++i) { const Mesh& mesh = meshes[i]; VkAccelerationStructureGeometryKHR& geo = geometries[i]; VkAccelerationStructureBuildGeometryInfoKHR& buildInfo = buildInfos[i]; unsigned int lodIndex = 0; primitiveCounts[i] = mesh.lods[lodIndex].indexCount / 3; geo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR; geo.geometryType = VK_GEOMETRY_TYPE_TRIANGLES_KHR; static_assert(offsetof(Vertex, vz) == offsetof(Vertex, vx) + sizeof(uint16_t) * 2, "Vertex layout mismatch"); geo.geometry.triangles.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_TRIANGLES_DATA_KHR; geo.geometry.triangles.vertexFormat = VK_FORMAT_R16G16B16A16_SFLOAT; geo.geometry.triangles.vertexData.deviceAddress = vbAddress + mesh.vertexOffset * sizeof(Vertex); geo.geometry.triangles.vertexStride = sizeof(Vertex); geo.geometry.triangles.maxVertex = mesh.vertexCount - 1; geo.geometry.triangles.indexType = VK_INDEX_TYPE_UINT32; geo.geometry.triangles.indexData.deviceAddress = ibAddress + mesh.lods[lodIndex].indexOffset * sizeof(uint32_t); buildInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; buildInfo.flags = kBuildBLAS | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR; buildInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; buildInfo.geometryCount = 1; buildInfo.pGeometries = &geo; VkAccelerationStructureBuildSizesInfoKHR sizeInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR }; vkGetAccelerationStructureBuildSizesKHR(device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &buildInfo, &primitiveCounts[i], &sizeInfo); accelerationOffsets[i] = totalAccelerationSize; accelerationSizes[i] = sizeInfo.accelerationStructureSize; scratchSizes[i] = sizeInfo.buildScratchSize; totalAccelerationSize = (totalAccelerationSize + sizeInfo.accelerationStructureSize + kAlignment - 1) & ~(kAlignment - 1); totalPrimitiveCount += primitiveCounts[i]; maxScratchSize = std::max(maxScratchSize, size_t(sizeInfo.buildScratchSize)); } createBuffer(blasBuffer, device, memoryProperties, totalAccelerationSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer scratchBuffer; createBuffer(scratchBuffer, device, memoryProperties, std::max(kDefaultScratch, maxScratchSize), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); printf("BLAS accelerationStructureSize: %.2f MB, scratchSize: %.2f MB (max %.2f MB), %.3fM triangles\n", double(totalAccelerationSize) / 1e6, double(scratchBuffer.size) / 1e6, double(maxScratchSize) / 1e6, double(totalPrimitiveCount) / 1e6); VkDeviceAddress scratchAddress = getBufferAddress(scratchBuffer, device); blas.resize(meshes.size()); std::vector<VkAccelerationStructureBuildRangeInfoKHR> buildRanges(meshes.size()); std::vector<const VkAccelerationStructureBuildRangeInfoKHR*> buildRangePtrs(meshes.size()); for (size_t i = 0; i < meshes.size(); ++i) { VkAccelerationStructureCreateInfoKHR accelerationInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR }; accelerationInfo.buffer = blasBuffer.buffer; accelerationInfo.offset = accelerationOffsets[i]; accelerationInfo.size = accelerationSizes[i]; accelerationInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; VK_CHECK(vkCreateAccelerationStructureKHR(device, &accelerationInfo, nullptr, &blas[i])); } VkQueryPoolCreateInfo createInfo = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO }; createInfo.queryType = VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR; createInfo.queryCount = blas.size(); VkQueryPool queryPool = 0; VK_CHECK(vkCreateQueryPool(device, &createInfo, 0, &queryPool)); VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); for (size_t start = 0; start < meshes.size();) { size_t scratchOffset = 0; // aggregate the range that fits into allocated scratch size_t i = start; while (i < meshes.size() && scratchOffset + scratchSizes[i] <= scratchBuffer.size) { buildInfos[i].scratchData.deviceAddress = scratchAddress + scratchOffset; buildInfos[i].dstAccelerationStructure = blas[i]; buildRanges[i].primitiveCount = primitiveCounts[i]; buildRangePtrs[i] = &buildRanges[i]; scratchOffset = (scratchOffset + scratchSizes[i] + kAlignment - 1) & ~(kAlignment - 1); ++i; } assert(i > start); // guaranteed as scratchBuffer.size >= maxScratchSize vkCmdBuildAccelerationStructuresKHR(commandBuffer, uint32_t(i - start), &buildInfos[start], &buildRangePtrs[start]); start = i; stageBarrier(commandBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR); } vkCmdResetQueryPool(commandBuffer, queryPool, 0, blas.size()); vkCmdWriteAccelerationStructuresPropertiesKHR(commandBuffer, blas.size(), blas.data(), VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR, queryPool, 0); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); compactedSizes.resize(blas.size()); VK_CHECK(vkGetQueryPoolResults(device, queryPool, 0, blas.size(), blas.size() * sizeof(VkDeviceSize), compactedSizes.data(), sizeof(VkDeviceSize), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT)); vkDestroyQueryPool(device, queryPool, 0); destroyBuffer(scratchBuffer, device); } void compactBLAS(VkDevice device, std::vector<VkAccelerationStructureKHR>& blas, const std::vector<VkDeviceSize>& compactedSizes, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties) { const size_t kAlignment = 256; // required by spec for acceleration structures VK_CHECK(vkResetCommandPool(device, commandPool, 0)); size_t totalCompactedSize = 0; std::vector<size_t> compactedOffsets(blas.size()); for (size_t i = 0; i < blas.size(); ++i) { compactedOffsets[i] = totalCompactedSize; totalCompactedSize = (totalCompactedSize + compactedSizes[i] + kAlignment - 1) & ~(kAlignment - 1); } printf("BLAS compacted accelerationStructureSize: %.2f MB\n", double(totalCompactedSize) / 1e6); Buffer compactedBuffer; createBuffer(compactedBuffer, device, memoryProperties, totalCompactedSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); std::vector<VkAccelerationStructureKHR> compactedBlas(blas.size()); for (size_t i = 0; i < blas.size(); ++i) { VkAccelerationStructureCreateInfoKHR accelerationInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR }; accelerationInfo.buffer = compactedBuffer.buffer; accelerationInfo.offset = compactedOffsets[i]; accelerationInfo.size = compactedSizes[i]; accelerationInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; VK_CHECK(vkCreateAccelerationStructureKHR(device, &accelerationInfo, nullptr, &compactedBlas[i])); } VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); for (size_t i = 0; i < blas.size(); ++i) { VkCopyAccelerationStructureInfoKHR copyInfo = { VK_STRUCTURE_TYPE_COPY_ACCELERATION_STRUCTURE_INFO_KHR }; copyInfo.src = blas[i]; copyInfo.dst = compactedBlas[i]; copyInfo.mode = VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR; vkCmdCopyAccelerationStructureKHR(commandBuffer, &copyInfo); } VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); for (size_t i = 0; i < blas.size(); ++i) { vkDestroyAccelerationStructureKHR(device, blas[i], nullptr); blas[i] = compactedBlas[i]; } destroyBuffer(blasBuffer, device); blasBuffer = compactedBuffer; } void buildCBLAS(VkDevice device, const std::vector<Mesh>& meshes, const std::vector<Meshlet>& meshlets, const Buffer& vxb, const Buffer& mdb, std::vector<VkAccelerationStructureKHR>& blas, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties) { #ifdef VK_NV_cluster_acceleration_structure const size_t kAlignment = 256; // required by spec for acceleration structures const size_t kClusterAlignment = 128; // required by spec for cluster acceleration structures VkClusterAccelerationStructureTriangleClusterInputNV clusterSizes = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_TRIANGLE_CLUSTER_INPUT_NV }; clusterSizes.vertexFormat = VK_FORMAT_R16G16B16A16_SFLOAT; clusterSizes.maxGeometryIndexValue = 0; clusterSizes.maxClusterUniqueGeometryCount = 1; clusterSizes.maxClusterTriangleCount = MESH_MAXTRI; clusterSizes.maxClusterVertexCount = MESH_MAXVTX; clusterSizes.minPositionTruncateBitCount = 0; VkClusterAccelerationStructureInputInfoNV clusterInfo = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_INPUT_INFO_NV }; clusterInfo.maxAccelerationStructureCount = 0; clusterInfo.flags = kBuildCLAS; clusterInfo.opType = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_TYPE_BUILD_TRIANGLE_CLUSTER_NV; clusterInfo.opMode = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_MODE_IMPLICIT_DESTINATIONS_NV; clusterInfo.opInput.pTriangleClusters = &clusterSizes; size_t maxClustersPerMesh = 0; for (const Mesh& mesh : meshes) { clusterSizes.maxTotalTriangleCount += mesh.lods[0].indexCount / 3; clusterInfo.maxAccelerationStructureCount += mesh.lods[0].meshletCount; maxClustersPerMesh = std::max(maxClustersPerMesh, size_t(mesh.lods[0].meshletCount)); for (size_t mi = 0; mi < mesh.lods[0].meshletCount; ++mi) { const Meshlet& ml = meshlets[mesh.lods[0].meshletOffset + mi]; clusterSizes.maxTotalVertexCount += ml.vertexCount; } } VkClusterAccelerationStructureClustersBottomLevelInputNV accelSizes = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_CLUSTERS_BOTTOM_LEVEL_INPUT_NV }; accelSizes.maxTotalClusterCount = clusterInfo.maxAccelerationStructureCount; accelSizes.maxClusterCountPerAccelerationStructure = maxClustersPerMesh; VkClusterAccelerationStructureMoveObjectsInputNV moveSizes = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_MOVE_OBJECTS_INPUT_NV }; moveSizes.type = VK_CLUSTER_ACCELERATION_STRUCTURE_TYPE_TRIANGLE_CLUSTER_NV; moveSizes.noMoveOverlap = true; VkClusterAccelerationStructureInputInfoNV accelInfo = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_INPUT_INFO_NV }; accelInfo.maxAccelerationStructureCount = meshes.size(); accelInfo.flags = kBuildBLAS; accelInfo.opType = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_TYPE_BUILD_CLUSTERS_BOTTOM_LEVEL_NV; accelInfo.opMode = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_MODE_IMPLICIT_DESTINATIONS_NV; accelInfo.opInput.pClustersBottomLevel = &accelSizes; VkClusterAccelerationStructureInputInfoNV moveInfo = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_INPUT_INFO_NV }; moveInfo.maxAccelerationStructureCount = clusterInfo.maxAccelerationStructureCount; moveInfo.opType = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_TYPE_MOVE_OBJECTS_NV; moveInfo.opMode = VK_CLUSTER_ACCELERATION_STRUCTURE_OP_MODE_IMPLICIT_DESTINATIONS_NV; moveInfo.opInput.pMoveObjects = &moveSizes; VkAccelerationStructureBuildSizesInfoKHR csizeInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR }; vkGetClusterAccelerationStructureBuildSizesNV(device, &clusterInfo, &csizeInfo); VkAccelerationStructureBuildSizesInfoKHR bsizeInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR }; vkGetClusterAccelerationStructureBuildSizesNV(device, &accelInfo, &bsizeInfo); moveSizes.maxMovedBytes = csizeInfo.accelerationStructureSize; VkAccelerationStructureBuildSizesInfoKHR msizeInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR }; vkGetClusterAccelerationStructureBuildSizesNV(device, &moveInfo, &msizeInfo); printf("CLAS accelerationStructureSize: %.2f MB, scratchSize: %.2f MB, compaction scratchSize: %.2f MB\n", double(csizeInfo.accelerationStructureSize) / 1e6, double(csizeInfo.buildScratchSize) / 1e6, double(msizeInfo.updateScratchSize) / 1e6); printf("CBLAS accelerationStructureSize: %.2f MB, scratchSize: %.2f MB\n", double(bsizeInfo.accelerationStructureSize) / 1e6, double(bsizeInfo.buildScratchSize) / 1e6); Buffer clasBuffer; createBuffer(clasBuffer, device, memoryProperties, csizeInfo.accelerationStructureSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer scratchBuffer; createBuffer(scratchBuffer, device, memoryProperties, std::max(std::max(bsizeInfo.buildScratchSize, csizeInfo.buildScratchSize), msizeInfo.updateScratchSize), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); Buffer infosBuffer; createBuffer(infosBuffer, device, memoryProperties, std::max(clusterInfo.maxAccelerationStructureCount * sizeof(VkClusterAccelerationStructureBuildTriangleClusterInfoNV), accelInfo.maxAccelerationStructureCount * sizeof(VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV)), VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VkDeviceAddress mdbAddress = getBufferAddress(mdb, device); VkDeviceAddress vxbAddress = getBufferAddress(vxb, device); VkClusterAccelerationStructureBuildTriangleClusterInfoNV* clusterData = static_cast<VkClusterAccelerationStructureBuildTriangleClusterInfoNV*>(infosBuffer.data); size_t vxbOffset = 0; for (const Mesh& mesh : meshes) { for (size_t mi = 0; mi < mesh.lods[0].meshletCount; ++mi) { const Meshlet& ml = meshlets[mesh.lods[0].meshletOffset + mi]; VkClusterAccelerationStructureBuildTriangleClusterInfoNV cluster = {}; cluster.clusterID = uint32_t(mi); cluster.triangleCount = ml.triangleCount; cluster.vertexCount = ml.vertexCount; cluster.positionTruncateBitCount = 0; cluster.indexType = VK_CLUSTER_ACCELERATION_STRUCTURE_INDEX_FORMAT_8BIT_NV; cluster.vertexBufferStride = sizeof(uint16_t) * 4; cluster.indexBuffer = mdbAddress + (ml.dataOffset + (ml.shortRefs ? (ml.vertexCount + 1) / 2 : ml.vertexCount)) * sizeof(uint32_t); cluster.vertexBuffer = vxbAddress + vxbOffset; memcpy(clusterData, &cluster, sizeof(VkClusterAccelerationStructureBuildTriangleClusterInfoNV)); clusterData++; vxbOffset += ml.vertexCount * (sizeof(uint16_t) * 4); } } Buffer rangeBuffer; // todo host vis -> device local? // todo merge with infos and suballocate more cleanly createBuffer(rangeBuffer, device, memoryProperties, (clusterInfo.maxAccelerationStructureCount + accelInfo.maxAccelerationStructureCount) * 16, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); VkClusterAccelerationStructureCommandsInfoNV clusterBuild = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_COMMANDS_INFO_NV }; clusterBuild.input = clusterInfo; clusterBuild.dstImplicitData = getBufferAddress(clasBuffer, device); clusterBuild.scratchData = getBufferAddress(scratchBuffer, device); clusterBuild.dstAddressesArray.deviceAddress = getBufferAddress(rangeBuffer, device); clusterBuild.dstAddressesArray.size = clusterInfo.maxAccelerationStructureCount * 8; clusterBuild.dstAddressesArray.stride = 8; clusterBuild.dstSizesArray.deviceAddress = getBufferAddress(rangeBuffer, device) + clusterInfo.maxAccelerationStructureCount * 8; clusterBuild.dstSizesArray.size = clusterInfo.maxAccelerationStructureCount * 8; clusterBuild.dstSizesArray.stride = 8; clusterBuild.srcInfosArray.deviceAddress = getBufferAddress(infosBuffer, device); clusterBuild.srcInfosArray.size = clusterInfo.maxAccelerationStructureCount * sizeof(VkClusterAccelerationStructureBuildTriangleClusterInfoNV); clusterBuild.srcInfosArray.stride = sizeof(VkClusterAccelerationStructureBuildTriangleClusterInfoNV); // TODO: redundant, validation layers bug VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); vkCmdBuildClusterAccelerationStructureIndirectNV(commandBuffer, &clusterBuild); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); size_t compactTotalSize = 0; for (size_t i = 0; i < clusterInfo.maxAccelerationStructureCount; ++i) { uint32_t size = ((uint32_t*)rangeBuffer.data)[clusterInfo.maxAccelerationStructureCount * 2 + i * 2]; compactTotalSize += (size + kClusterAlignment - 1) & ~(kClusterAlignment - 1); } // align subsequent acceleration structures compactTotalSize = (compactTotalSize + kAlignment - 1) & ~(kAlignment - 1); printf("CLAS compacted accelerationStructureSize: %.2f MB\n", double(compactTotalSize) / 1e6); printf("CLAS+CBLAS accelerationStructureSize: %.2f MB\n", double(compactTotalSize + bsizeInfo.accelerationStructureSize) / 1e6); createBuffer(blasBuffer, device, memoryProperties, compactTotalSize + bsizeInfo.accelerationStructureSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); // TODO: we are not actually querying size required for compaction, so scratch could be insufficient VkClusterAccelerationStructureCommandsInfoNV clusterMove = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_COMMANDS_INFO_NV }; clusterMove.input = moveInfo; clusterMove.dstImplicitData = getBufferAddress(blasBuffer, device); clusterMove.scratchData = getBufferAddress(scratchBuffer, device); clusterMove.dstAddressesArray.deviceAddress = getBufferAddress(rangeBuffer, device) + clusterInfo.maxAccelerationStructureCount * 8; clusterMove.dstAddressesArray.size = moveInfo.maxAccelerationStructureCount * 8; clusterMove.dstAddressesArray.stride = 8; clusterMove.srcInfosArray.deviceAddress = getBufferAddress(rangeBuffer, device); clusterMove.srcInfosArray.size = moveInfo.maxAccelerationStructureCount * 8; clusterMove.srcInfosArray.stride = 8; // TODO: redundant, probably a driver bug printf("max cluster count %d, total cluster count %d, total blas count %d\n", int(maxClustersPerMesh), int(clusterInfo.maxAccelerationStructureCount), int(accelInfo.maxAccelerationStructureCount)); VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV* accelData = static_cast<VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV*>(infosBuffer.data); size_t accelOffset = 0; for (const Mesh& mesh : meshes) { VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV accel = {}; accel.clusterReferencesCount = uint32_t(mesh.lods[0].meshletCount); accel.clusterReferencesStride = 8; accel.clusterReferences = getBufferAddress(rangeBuffer, device) + clusterInfo.maxAccelerationStructureCount * 8 + accelOffset * 8; memcpy(accelData, &accel, sizeof(VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV)); accelData++; accelOffset += mesh.lods[0].meshletCount; } VkClusterAccelerationStructureCommandsInfoNV accelBuild = { VK_STRUCTURE_TYPE_CLUSTER_ACCELERATION_STRUCTURE_COMMANDS_INFO_NV }; accelBuild.input = accelInfo; accelBuild.dstImplicitData = getBufferAddress(blasBuffer, device) + compactTotalSize; accelBuild.scratchData = getBufferAddress(scratchBuffer, device); accelBuild.dstAddressesArray.deviceAddress = getBufferAddress(rangeBuffer, device) + clusterInfo.maxAccelerationStructureCount * 16; accelBuild.dstAddressesArray.size = accelInfo.maxAccelerationStructureCount * 8; accelBuild.dstAddressesArray.stride = 8; accelBuild.dstSizesArray.deviceAddress = getBufferAddress(rangeBuffer, device) + clusterInfo.maxAccelerationStructureCount * 16 + accelInfo.maxAccelerationStructureCount * 8; accelBuild.dstSizesArray.size = accelInfo.maxAccelerationStructureCount * 8; accelBuild.dstSizesArray.stride = 8; accelBuild.srcInfosArray.deviceAddress = getBufferAddress(infosBuffer, device); accelBuild.srcInfosArray.size = accelInfo.maxAccelerationStructureCount * sizeof(VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV); accelBuild.srcInfosArray.stride = sizeof(VkClusterAccelerationStructureBuildClustersBottomLevelInfoNV); // TODO: redundant, validation layers bug VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); vkCmdBuildClusterAccelerationStructureIndirectNV(commandBuffer, &clusterMove); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR); vkCmdBuildClusterAccelerationStructureIndirectNV(commandBuffer, &accelBuild); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); VkDeviceAddress blasAddress = getBufferAddress(blasBuffer, device); uint32_t* rangeAccel = (uint32_t*)rangeBuffer.data + clusterInfo.maxAccelerationStructureCount * 4; blas.resize(meshes.size()); for (size_t i = 0; i < accelInfo.maxAccelerationStructureCount; ++i) { VkAccelerationStructureCreateInfoKHR accelerationInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR }; accelerationInfo.buffer = blasBuffer.buffer; accelerationInfo.offset = ((uint64_t*)rangeAccel)[i] - blasAddress; accelerationInfo.size = rangeAccel[accelInfo.maxAccelerationStructureCount * 2 + i * 2]; accelerationInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR; VK_CHECK(vkCreateAccelerationStructureKHR(device, &accelerationInfo, nullptr, &blas[i])); } destroyBuffer(scratchBuffer, device); destroyBuffer(infosBuffer, device); destroyBuffer(rangeBuffer, device); destroyBuffer(clasBuffer, device); #else VK_CHECK(VK_ERROR_FEATURE_NOT_PRESENT); #endif } void fillInstanceRT(VkAccelerationStructureInstanceKHR& instance, const MeshDraw& draw, uint32_t instanceIndex, VkDeviceAddress blas) { mat3 xform = transpose(glm::mat3_cast(draw.orientation)) * draw.scale; memcpy(instance.transform.matrix[0], &xform[0], sizeof(float) * 3); memcpy(instance.transform.matrix[1], &xform[1], sizeof(float) * 3); memcpy(instance.transform.matrix[2], &xform[2], sizeof(float) * 3); instance.transform.matrix[0][3] = draw.position.x; instance.transform.matrix[1][3] = draw.position.y; instance.transform.matrix[2][3] = draw.position.z; instance.instanceCustomIndex = instanceIndex; instance.mask = 1 << draw.postPass; instance.flags = draw.postPass ? VK_GEOMETRY_INSTANCE_FORCE_NO_OPAQUE_BIT_KHR : VK_GEOMETRY_INSTANCE_FORCE_OPAQUE_BIT_KHR; instance.accelerationStructureReference = draw.postPass <= 1 ? blas : 0; } VkAccelerationStructureKHR createTLAS(VkDevice device, Buffer& tlasBuffer, Buffer& scratchBuffer, const Buffer& instanceBuffer, uint32_t primitiveCount, const VkPhysicalDeviceMemoryProperties& memoryProperties) { VkAccelerationStructureGeometryKHR geometry = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR }; geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; geometry.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; geometry.geometry.instances.data.deviceAddress = getBufferAddress(instanceBuffer, device); VkAccelerationStructureBuildGeometryInfoKHR buildInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR }; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; buildInfo.flags = kBuildTLAS | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; buildInfo.mode = VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR; buildInfo.geometryCount = 1; buildInfo.pGeometries = &geometry; VkAccelerationStructureBuildSizesInfoKHR sizeInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR }; vkGetAccelerationStructureBuildSizesKHR(device, VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR, &buildInfo, &primitiveCount, &sizeInfo); printf("TLAS accelerationStructureSize: %.2f MB, scratchSize: %.2f MB, updateScratch: %.2f MB\n", double(sizeInfo.accelerationStructureSize) / 1e6, double(sizeInfo.buildScratchSize) / 1e6, double(sizeInfo.updateScratchSize) / 1e6); createBuffer(tlasBuffer, device, memoryProperties, sizeInfo.accelerationStructureSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); createBuffer(scratchBuffer, device, memoryProperties, std::max(sizeInfo.buildScratchSize, sizeInfo.updateScratchSize), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VkAccelerationStructureCreateInfoKHR accelerationInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR }; accelerationInfo.buffer = tlasBuffer.buffer; accelerationInfo.size = sizeInfo.accelerationStructureSize; accelerationInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; VkAccelerationStructureKHR tlas = nullptr; VK_CHECK(vkCreateAccelerationStructureKHR(device, &accelerationInfo, nullptr, &tlas)); return tlas; } void buildTLAS(VkDevice device, VkCommandBuffer commandBuffer, VkAccelerationStructureKHR tlas, const Buffer& tlasBuffer, const Buffer& scratchBuffer, const Buffer& instanceBuffer, uint32_t primitiveCount, VkBuildAccelerationStructureModeKHR mode) { VkAccelerationStructureGeometryKHR geometry = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_KHR }; geometry.geometryType = VK_GEOMETRY_TYPE_INSTANCES_KHR; geometry.geometry.instances.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_GEOMETRY_INSTANCES_DATA_KHR; geometry.geometry.instances.data.deviceAddress = getBufferAddress(instanceBuffer, device); VkAccelerationStructureBuildGeometryInfoKHR buildInfo = { VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_GEOMETRY_INFO_KHR }; buildInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR; buildInfo.flags = kBuildTLAS | VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; buildInfo.mode = mode; buildInfo.geometryCount = 1; buildInfo.pGeometries = &geometry; buildInfo.srcAccelerationStructure = tlas; buildInfo.dstAccelerationStructure = tlas; buildInfo.scratchData.deviceAddress = getBufferAddress(scratchBuffer, device); VkAccelerationStructureBuildRangeInfoKHR buildRange = {}; buildRange.primitiveCount = primitiveCount; const VkAccelerationStructureBuildRangeInfoKHR* buildRangePtr = &buildRange; vkCmdBuildAccelerationStructuresKHR(commandBuffer, 1, &buildInfo, &buildRangePtr); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT); }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/scenert.h
C/C++ Header
#pragma once struct Buffer; struct Mesh; struct MeshDraw; struct Meshlet; void buildBLAS(VkDevice device, const std::vector<Mesh>& meshes, const Buffer& vb, const Buffer& ib, std::vector<VkAccelerationStructureKHR>& blas, std::vector<VkDeviceSize>& compactedSizes, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties); void compactBLAS(VkDevice device, std::vector<VkAccelerationStructureKHR>& blas, const std::vector<VkDeviceSize>& compactedSizes, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties); void buildCBLAS(VkDevice device, const std::vector<Mesh>& meshes, const std::vector<Meshlet>& meshlets, const Buffer& vxb, const Buffer& mdb, std::vector<VkAccelerationStructureKHR>& blas, Buffer& blasBuffer, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties); void fillInstanceRT(VkAccelerationStructureInstanceKHR& instance, const MeshDraw& draw, uint32_t instanceIndex, VkDeviceAddress blas); VkAccelerationStructureKHR createTLAS(VkDevice device, Buffer& tlasBuffer, Buffer& scratchBuffer, const Buffer& instanceBuffer, uint32_t primitiveCount, const VkPhysicalDeviceMemoryProperties& memoryProperties); void buildTLAS(VkDevice device, VkCommandBuffer commandBuffer, VkAccelerationStructureKHR tlas, const Buffer& tlasBuffer, const Buffer& scratchBuffer, const Buffer& instanceBuffer, uint32_t primitiveCount, VkBuildAccelerationStructureModeKHR mode);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/shaders.cpp
C++
#include "common.h" #include "shaders.h" #include "config.h" #include <stdio.h> #include <string.h> #ifdef _WIN32 #include <io.h> #else #include <dirent.h> #endif #include <string> #include <vector> #if defined __APPLE__ #include <spirv_cross/spirv.h> #elif defined __linux__ #include <spirv/unified1/spirv.h> #elif VK_HEADER_VERSION >= 135 #include <spirv-headers/spirv.h> #else #include <vulkan/spirv.h> #endif // https://www.khronos.org/registry/spir-v/specs/1.0/SPIRV.pdf struct Id { uint32_t opcode; uint32_t typeId; uint32_t storageClass; uint32_t binding; uint32_t set; uint32_t imageSampled; uint32_t constant; }; static VkShaderStageFlagBits getShaderStage(SpvExecutionModel executionModel) { switch (executionModel) { case SpvExecutionModelVertex: return VK_SHADER_STAGE_VERTEX_BIT; case SpvExecutionModelGeometry: return VK_SHADER_STAGE_GEOMETRY_BIT; case SpvExecutionModelFragment: return VK_SHADER_STAGE_FRAGMENT_BIT; case SpvExecutionModelGLCompute: return VK_SHADER_STAGE_COMPUTE_BIT; case SpvExecutionModelTaskEXT: return VK_SHADER_STAGE_TASK_BIT_EXT; case SpvExecutionModelMeshEXT: return VK_SHADER_STAGE_MESH_BIT_EXT; default: assert(!"Unsupported execution model"); return VkShaderStageFlagBits(0); } } static VkDescriptorType getDescriptorType(SpvOp op, uint32_t imageSampled = 0) { switch (op) { case SpvOpTypeStruct: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case SpvOpTypeImage: return imageSampled == 1 ? VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE : VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; case SpvOpTypeSampler: return VK_DESCRIPTOR_TYPE_SAMPLER; case SpvOpTypeSampledImage: return VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; case SpvOpTypeAccelerationStructureKHR: return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; default: assert(!"Unknown resource type"); return VkDescriptorType(0); } } static void parseShader(Shader& shader, const uint32_t* code, uint32_t codeSize) { assert(code[0] == SpvMagicNumber); uint32_t idBound = code[3]; std::vector<Id> ids(idBound); int localSizeIdX = -1; int localSizeIdY = -1; int localSizeIdZ = -1; const uint32_t* insn = code + 5; while (insn != code + codeSize) { uint16_t opcode = uint16_t(insn[0]); uint16_t wordCount = uint16_t(insn[0] >> 16); switch (opcode) { case SpvOpEntryPoint: { assert(wordCount >= 2); shader.stage = getShaderStage(SpvExecutionModel(insn[1])); } break; case SpvOpExecutionMode: { assert(wordCount >= 3); uint32_t mode = insn[2]; switch (mode) { case SpvExecutionModeLocalSize: assert(wordCount == 6); shader.localSizeX = insn[3]; shader.localSizeY = insn[4]; shader.localSizeZ = insn[5]; break; } } break; case SpvOpExecutionModeId: { assert(wordCount >= 3); uint32_t mode = insn[2]; switch (mode) { case SpvExecutionModeLocalSizeId: assert(wordCount == 6); localSizeIdX = int(insn[3]); localSizeIdY = int(insn[4]); localSizeIdZ = int(insn[5]); break; } } break; case SpvOpDecorate: { assert(wordCount >= 3); uint32_t id = insn[1]; assert(id < idBound); switch (insn[2]) { case SpvDecorationDescriptorSet: assert(wordCount == 4); ids[id].set = insn[3]; break; case SpvDecorationBinding: assert(wordCount == 4); ids[id].binding = insn[3]; break; } } break; case SpvOpTypeStruct: case SpvOpTypeSampler: case SpvOpTypeSampledImage: case SpvOpTypeAccelerationStructureKHR: { assert(wordCount >= 2); uint32_t id = insn[1]; assert(id < idBound); assert(ids[id].opcode == 0); ids[id].opcode = opcode; } break; case SpvOpTypeImage: { assert(wordCount >= 9); uint32_t id = insn[1]; assert(id < idBound); assert(ids[id].opcode == 0); ids[id].opcode = opcode; ids[id].imageSampled = insn[7]; } break; case SpvOpTypePointer: { assert(wordCount == 4); uint32_t id = insn[1]; assert(id < idBound); assert(ids[id].opcode == 0); ids[id].opcode = opcode; ids[id].typeId = insn[3]; ids[id].storageClass = insn[2]; } break; case SpvOpConstant: { assert(wordCount >= 4); // we currently only correctly handle 32-bit integer constants uint32_t id = insn[2]; assert(id < idBound); assert(ids[id].opcode == 0); ids[id].opcode = opcode; ids[id].typeId = insn[1]; ids[id].constant = insn[3]; // note: this is the value, not the id of the constant } break; case SpvOpVariable: { assert(wordCount >= 4); uint32_t id = insn[2]; assert(id < idBound); assert(ids[id].opcode == 0); ids[id].opcode = opcode; ids[id].typeId = insn[1]; ids[id].storageClass = insn[3]; } break; } assert(insn + wordCount <= code + codeSize); insn += wordCount; } for (auto& id : ids) { // set 0 is reserved for push descriptors if (id.opcode == SpvOpVariable && (id.storageClass == SpvStorageClassUniform || id.storageClass == SpvStorageClassUniformConstant || id.storageClass == SpvStorageClassStorageBuffer) && id.set == 0) { assert(id.binding < 32); assert(ids[id.typeId].opcode == SpvOpTypePointer); const Id& type = ids[ids[id.typeId].typeId]; VkDescriptorType resourceType = getDescriptorType(SpvOp(type.opcode), type.imageSampled); assert((shader.resourceMask & (1 << id.binding)) == 0 || shader.resourceTypes[id.binding] == resourceType); shader.resourceTypes[id.binding] = resourceType; shader.resourceMask |= 1 << id.binding; } if (id.opcode == SpvOpVariable && id.storageClass == SpvStorageClassUniformConstant && id.set == 1) { shader.usesDescriptorArray = true; } if (id.opcode == SpvOpVariable && id.storageClass == SpvStorageClassPushConstant) { shader.usesPushConstants = true; } } if (shader.stage == VK_SHADER_STAGE_COMPUTE_BIT) { if (localSizeIdX >= 0) { assert(ids[localSizeIdX].opcode == SpvOpConstant); shader.localSizeX = ids[localSizeIdX].constant; } if (localSizeIdY >= 0) { assert(ids[localSizeIdY].opcode == SpvOpConstant); shader.localSizeY = ids[localSizeIdY].constant; } if (localSizeIdZ >= 0) { assert(ids[localSizeIdZ].opcode == SpvOpConstant); shader.localSizeZ = ids[localSizeIdZ].constant; } assert(shader.localSizeX && shader.localSizeY && shader.localSizeZ); } } static uint32_t gatherResources(Shaders shaders, VkDescriptorType (&resourceTypes)[32]) { uint32_t resourceMask = 0; for (const Shader* shader : shaders) { for (uint32_t i = 0; i < 32; ++i) { if (shader->resourceMask & (1 << i)) { if (resourceMask & (1 << i)) { assert(resourceTypes[i] == shader->resourceTypes[i]); } else { resourceTypes[i] = shader->resourceTypes[i]; resourceMask |= 1 << i; } } } } return resourceMask; } static VkDescriptorSetLayout createSetLayout(VkDevice device, Shaders shaders) { std::vector<VkDescriptorSetLayoutBinding> setBindings; VkDescriptorType resourceTypes[32] = {}; uint32_t resourceMask = gatherResources(shaders, resourceTypes); for (uint32_t i = 0; i < 32; ++i) if (resourceMask & (1 << i)) { VkDescriptorSetLayoutBinding binding = {}; binding.binding = i; binding.descriptorType = resourceTypes[i]; binding.descriptorCount = 1; binding.stageFlags = 0; for (const Shader* shader : shaders) if (shader->resourceMask & (1 << i)) binding.stageFlags |= shader->stage; setBindings.push_back(binding); } VkDescriptorSetLayoutCreateInfo setCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; setCreateInfo.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT; setCreateInfo.bindingCount = uint32_t(setBindings.size()); setCreateInfo.pBindings = setBindings.data(); VkDescriptorSetLayout setLayout = 0; VK_CHECK(vkCreateDescriptorSetLayout(device, &setCreateInfo, 0, &setLayout)); return setLayout; } static VkPipelineLayout createPipelineLayout(VkDevice device, VkDescriptorSetLayout setLayout, VkDescriptorSetLayout arrayLayout, VkShaderStageFlags pushConstantStages, size_t pushConstantSize) { VkDescriptorSetLayout layouts[2] = { setLayout, arrayLayout }; VkPipelineLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; createInfo.setLayoutCount = arrayLayout ? 2 : 1; createInfo.pSetLayouts = layouts; VkPushConstantRange pushConstantRange = {}; if (pushConstantSize) { pushConstantRange.stageFlags = pushConstantStages; pushConstantRange.size = uint32_t(pushConstantSize); createInfo.pushConstantRangeCount = 1; createInfo.pPushConstantRanges = &pushConstantRange; } VkPipelineLayout layout = 0; VK_CHECK(vkCreatePipelineLayout(device, &createInfo, 0, &layout)); return layout; } static VkDescriptorUpdateTemplate createUpdateTemplate(VkDevice device, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, Shaders shaders, uint32_t* pushDescriptorCount) { std::vector<VkDescriptorUpdateTemplateEntry> entries; VkDescriptorType resourceTypes[32] = {}; uint32_t resourceMask = gatherResources(shaders, resourceTypes); for (uint32_t i = 0; i < 32; ++i) if (resourceMask & (1 << i)) { VkDescriptorUpdateTemplateEntry entry = {}; entry.dstBinding = i; entry.dstArrayElement = 0; entry.descriptorCount = 1; entry.descriptorType = resourceTypes[i]; entry.offset = sizeof(DescriptorInfo) * i; entry.stride = sizeof(DescriptorInfo); entries.push_back(entry); // track descriptor count including gaps *pushDescriptorCount = i + 1; } VkDescriptorUpdateTemplateCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO }; createInfo.descriptorUpdateEntryCount = uint32_t(entries.size()); createInfo.pDescriptorUpdateEntries = entries.data(); createInfo.templateType = VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS; createInfo.pipelineBindPoint = bindPoint; createInfo.pipelineLayout = layout; VkDescriptorUpdateTemplate updateTemplate = 0; VK_CHECK(vkCreateDescriptorUpdateTemplate(device, &createInfo, 0, &updateTemplate)); return updateTemplate; } #if VK_EXT_descriptor_heap static VkShaderDescriptorSetAndBindingMappingInfoEXT generateHeapMapping(uint32_t resourceMask, const VkDescriptorType (&resourceTypes)[32], size_t pushConstantSize, size_t descriptorSize, VkDescriptorSetAndBindingMappingEXT (&mappings)[33]) { uint32_t mappingOffset = 0; // push descriptors for (uint32_t i = 0; i < 32; ++i) if (resourceMask & (1 << i)) { VkDescriptorSetAndBindingMappingEXT& mapping = mappings[mappingOffset++]; mapping.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT; mapping.descriptorSet = 0; mapping.firstBinding = i; mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_ALL_EXT; if (resourceTypes[i] == VK_DESCRIPTOR_TYPE_SAMPLER) { mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; } else { mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_PUSH_INDEX_EXT; mapping.sourceData.pushIndex.heapOffset = i * descriptorSize; mapping.sourceData.pushIndex.pushOffset = pushConstantSize; mapping.sourceData.pushIndex.heapIndexStride = descriptorSize; mapping.sourceData.pushIndex.heapArrayStride = descriptorSize; } } // texture array descriptor { VkDescriptorSetAndBindingMappingEXT& mapping = mappings[mappingOffset++]; mapping.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_AND_BINDING_MAPPING_EXT; mapping.descriptorSet = 1; mapping.firstBinding = 0; mapping.bindingCount = 1; mapping.resourceMask = VK_SPIRV_RESOURCE_TYPE_ALL_EXT; mapping.source = VK_DESCRIPTOR_MAPPING_SOURCE_HEAP_WITH_CONSTANT_OFFSET_EXT; mapping.sourceData.constantOffset.heapArrayStride = descriptorSize; } VkShaderDescriptorSetAndBindingMappingInfoEXT result = { VK_STRUCTURE_TYPE_SHADER_DESCRIPTOR_SET_AND_BINDING_MAPPING_INFO_EXT }; result.mappingCount = mappingOffset; result.pMappings = mappings; return result; } #endif bool loadShader(Shader& shader, const char* path) { FILE* file = fopen(path, "rb"); if (!file) return false; fseek(file, 0, SEEK_END); long length = ftell(file); assert(length >= 0); fseek(file, 0, SEEK_SET); std::vector<char> spirv(length); size_t rc = fread(spirv.data(), 1, length, file); assert(rc == size_t(length)); fclose(file); assert(length % 4 == 0); parseShader(shader, reinterpret_cast<const uint32_t*>(spirv.data()), length / 4); shader.spirv = spirv; return true; } bool loadShader(Shader& shader, const char* base, const char* path) { std::string spath = base; std::string::size_type pos = spath.find_last_of("/\\"); if (pos == std::string::npos) spath = ""; else spath = spath.substr(0, pos + 1); spath += path; return loadShader(shader, spath.c_str()); } bool loadShaders(ShaderSet& shaders, const char* base, const char* path) { std::string spath = base; std::string::size_type pos = spath.find_last_of("/\\"); if (pos == std::string::npos) spath = ""; else spath = spath.substr(0, pos + 1); spath += path; #ifdef _WIN32 _finddata_t finddata; intptr_t fh = _findfirst((spath + "/*.spv").c_str(), &finddata); if (fh == -1) return false; do { const char* ext = strrchr(finddata.name, '.'); if (!ext) continue; std::string fpath = spath + '/' + finddata.name; Shader shader = {}; if (!loadShader(shader, fpath.c_str())) { fprintf(stderr, "Warning: %s is not a valid SPIRV module\n", finddata.name); continue; } shader.name = std::string(finddata.name, ext - finddata.name); shaders.shaders.push_back(shader); } while (_findnext(fh, &finddata) == 0); _findclose(fh); #else DIR* dir = opendir(spath.c_str()); if (!dir) return false; while (dirent* de = readdir(dir)) { const char* ext = strstr(de->d_name, ".spv"); if (!ext || strcmp(ext, ".spv") != 0) continue; std::string fpath = spath + '/' + de->d_name; Shader shader = {}; if (!loadShader(shader, fpath.c_str())) { fprintf(stderr, "Warning: %s is not a valid SPIRV module\n", de->d_name); continue; } shader.name = std::string(de->d_name, ext - de->d_name); shaders.shaders.push_back(shader); } closedir(dir); #endif printf("Loaded %d shaders from %s\n", int(shaders.shaders.size()), spath.c_str()); return true; } const Shader& ShaderSet::operator[](const char* name) const { for (const Shader& shader : shaders) if (shader.name == name) return shader; fprintf(stderr, "Error: shader %s could not be loaded\n", name); abort(); } static VkSpecializationInfo fillSpecializationInfo(std::vector<VkSpecializationMapEntry>& entries, const Constants& constants) { for (size_t i = 0; i < constants.size(); ++i) entries.push_back({ uint32_t(i), uint32_t(i * 4), 4 }); VkSpecializationInfo result = {}; result.mapEntryCount = uint32_t(entries.size()); result.pMapEntries = entries.data(); result.dataSize = constants.size() * sizeof(int); result.pData = constants.begin(); return result; } VkPipeline createGraphicsPipeline(VkDevice device, VkPipelineCache pipelineCache, const VkPipelineRenderingCreateInfo& renderingInfo, const Program& program, Constants constants) { std::vector<VkSpecializationMapEntry> specializationEntries; VkSpecializationInfo specializationInfo = fillSpecializationInfo(specializationEntries, constants); VkPipelineCreateFlags2CreateInfo extraFlags = { VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO }; extraFlags.pNext = &renderingInfo; VkGraphicsPipelineCreateInfo createInfo = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO }; createInfo.pNext = &extraFlags; #if VK_EXT_descriptor_heap VkShaderDescriptorSetAndBindingMappingInfoEXT heapMapping = {}; VkDescriptorSetAndBindingMappingEXT heapMappingTable[33] = {}; if (program.descriptorSize) { extraFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; heapMapping = generateHeapMapping(program.resourceMask, program.resourceTypes, program.pushConstantSize, program.descriptorSize, heapMappingTable); } #endif std::vector<VkPipelineShaderStageCreateInfo> stages(program.shaderCount); std::vector<VkShaderModuleCreateInfo> modules(program.shaderCount); for (size_t i = 0; i < program.shaderCount; ++i) { const Shader* shader = program.shaders[i]; VkShaderModuleCreateInfo& module = modules[i]; module.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; module.codeSize = shader->spirv.size(); // note: this needs to be a number of bytes! module.pCode = reinterpret_cast<const uint32_t*>(shader->spirv.data()); VkPipelineShaderStageCreateInfo& stage = stages[i]; stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; stage.stage = shader->stage; stage.pName = "main"; stage.pSpecializationInfo = &specializationInfo; stage.pNext = &module; #if VK_EXT_descriptor_heap if (program.descriptorSize) module.pNext = &heapMapping; #endif } createInfo.stageCount = uint32_t(stages.size()); createInfo.pStages = stages.data(); VkPipelineVertexInputStateCreateInfo vertexInput = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO }; createInfo.pVertexInputState = &vertexInput; VkPipelineInputAssemblyStateCreateInfo inputAssembly = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO }; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; createInfo.pInputAssemblyState = &inputAssembly; VkPipelineViewportStateCreateInfo viewportState = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO }; viewportState.viewportCount = 1; viewportState.scissorCount = 1; createInfo.pViewportState = &viewportState; VkPipelineRasterizationStateCreateInfo rasterizationState = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO }; rasterizationState.lineWidth = 1.f; rasterizationState.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE; rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT; rasterizationState.depthBiasEnable = true; createInfo.pRasterizationState = &rasterizationState; VkPipelineMultisampleStateCreateInfo multisampleState = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO }; multisampleState.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; createInfo.pMultisampleState = &multisampleState; VkPipelineDepthStencilStateCreateInfo depthStencilState = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO }; depthStencilState.depthTestEnable = true; depthStencilState.depthWriteEnable = true; depthStencilState.depthCompareOp = VK_COMPARE_OP_GREATER; createInfo.pDepthStencilState = &depthStencilState; VkPipelineColorBlendAttachmentState colorAttachmentStates[8] = {}; assert(renderingInfo.colorAttachmentCount <= COUNTOF(colorAttachmentStates)); for (uint32_t i = 0; i < renderingInfo.colorAttachmentCount; ++i) colorAttachmentStates[i].colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; VkPipelineColorBlendStateCreateInfo colorBlendState = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO }; colorBlendState.attachmentCount = renderingInfo.colorAttachmentCount; colorBlendState.pAttachments = colorAttachmentStates; createInfo.pColorBlendState = &colorBlendState; VkDynamicState dynamicStates[] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_CULL_MODE, VK_DYNAMIC_STATE_DEPTH_BIAS }; VkPipelineDynamicStateCreateInfo dynamicState = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO }; dynamicState.dynamicStateCount = sizeof(dynamicStates) / sizeof(dynamicStates[0]); dynamicState.pDynamicStates = dynamicStates; createInfo.pDynamicState = &dynamicState; createInfo.layout = program.layout; VkPipeline pipeline = 0; VK_CHECK(vkCreateGraphicsPipelines(device, pipelineCache, 1, &createInfo, 0, &pipeline)); if (vkSetDebugUtilsObjectNameEXT) { std::string name; for (size_t i = 0; i < program.shaderCount; ++i) { const Shader* shader = program.shaders[i]; name += shader->name; if (i + 1 < program.shaderCount) name += " / "; } VkDebugUtilsObjectNameInfoEXT nameInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT }; nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE; nameInfo.objectHandle = uint64_t(pipeline); nameInfo.pObjectName = name.c_str(); vkSetDebugUtilsObjectNameEXT(device, &nameInfo); } return pipeline; } VkPipeline createComputePipeline(VkDevice device, VkPipelineCache pipelineCache, const Program& program, Constants constants) { assert(program.shaderCount == 1); const Shader& shader = *program.shaders[0]; assert(shader.stage == VK_SHADER_STAGE_COMPUTE_BIT); VkComputePipelineCreateInfo createInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO }; VkPipelineCreateFlags2CreateInfo extraFlags = { VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO }; createInfo.pNext = &extraFlags; #if VK_EXT_descriptor_heap if (program.descriptorSize) extraFlags.flags = VK_PIPELINE_CREATE_2_DESCRIPTOR_HEAP_BIT_EXT; #endif std::vector<VkSpecializationMapEntry> specializationEntries; VkSpecializationInfo specializationInfo = fillSpecializationInfo(specializationEntries, constants); VkShaderModuleCreateInfo module = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO }; module.codeSize = shader.spirv.size(); // note: this needs to be a number of bytes! module.pCode = reinterpret_cast<const uint32_t*>(shader.spirv.data()); #if VK_EXT_descriptor_heap VkShaderDescriptorSetAndBindingMappingInfoEXT heapMapping = {}; VkDescriptorSetAndBindingMappingEXT heapMappingTable[33] = {}; if (program.descriptorSize) { heapMapping = generateHeapMapping(program.resourceMask, program.resourceTypes, program.pushConstantSize, program.descriptorSize, heapMappingTable); module.pNext = &heapMapping; } #endif VkPipelineShaderStageCreateInfo stage = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO }; stage.stage = shader.stage; stage.pName = "main"; stage.pSpecializationInfo = &specializationInfo; stage.pNext = &module; createInfo.stage = stage; createInfo.layout = program.layout; VkPipeline pipeline = 0; VK_CHECK(vkCreateComputePipelines(device, pipelineCache, 1, &createInfo, 0, &pipeline)); if (vkSetDebugUtilsObjectNameEXT) { VkDebugUtilsObjectNameInfoEXT nameInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT }; nameInfo.objectType = VK_OBJECT_TYPE_PIPELINE; nameInfo.objectHandle = uint64_t(pipeline); nameInfo.pObjectName = shader.name.c_str(); vkSetDebugUtilsObjectNameEXT(device, &nameInfo); } return pipeline; } Program createProgram(VkDevice device, VkPipelineBindPoint bindPoint, Shaders shaders, size_t pushConstantSize, size_t descriptorSize, VkDescriptorSetLayout arrayLayout) { VkShaderStageFlags pushConstantStages = 0; for (const Shader* shader : shaders) if (shader->usesPushConstants) pushConstantStages |= shader->stage; bool usesDescriptorArray = false; for (const Shader* shader : shaders) usesDescriptorArray |= shader->usesDescriptorArray; assert(!usesDescriptorArray || arrayLayout); Program program = {}; program.bindPoint = bindPoint; if (descriptorSize) { program.resourceMask = gatherResources(shaders, program.resourceTypes); // track descriptor count including gaps for (uint32_t i = 0; i < 32; ++i) if (program.resourceMask & (1 << i)) program.pushDescriptorCount = i + 1; } else { program.setLayout = createSetLayout(device, shaders); assert(program.setLayout); program.layout = createPipelineLayout(device, program.setLayout, arrayLayout, pushConstantStages, pushConstantSize); assert(program.layout); program.updateTemplate = createUpdateTemplate(device, bindPoint, program.layout, shaders, &program.pushDescriptorCount); assert(program.updateTemplate); } program.pushConstantStages = pushConstantStages; program.pushConstantSize = uint32_t(pushConstantSize); program.descriptorSize = descriptorSize; const Shader* shader = shaders.size() == 1 ? *shaders.begin() : nullptr; if (shader && shader->stage == VK_SHADER_STAGE_COMPUTE_BIT) { program.localSizeX = shader->localSizeX; program.localSizeY = shader->localSizeY; program.localSizeZ = shader->localSizeZ; } memset(program.shaders, 0, sizeof(program.shaders)); program.shaderCount = 0; for (const Shader* shader : shaders) program.shaders[program.shaderCount++] = shader; return program; } void destroyProgram(VkDevice device, const Program& program) { if (program.descriptorSize == 0) { vkDestroyDescriptorUpdateTemplate(device, program.updateTemplate, 0); vkDestroyPipelineLayout(device, program.layout, 0); vkDestroyDescriptorSetLayout(device, program.setLayout, 0); } } VkDescriptorSetLayout createDescriptorArrayLayout(VkDevice device) { VkShaderStageFlags stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT; VkDescriptorSetLayoutBinding setBinding = { 0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, DESCRIPTOR_LIMIT, stageFlags, nullptr }; VkDescriptorBindingFlags bindingFlags = VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT; VkDescriptorSetLayoutBindingFlagsCreateInfo setBindingFlags = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO }; setBindingFlags.bindingCount = 1; setBindingFlags.pBindingFlags = &bindingFlags; VkDescriptorSetLayoutCreateInfo setCreateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; setCreateInfo.pNext = &setBindingFlags; setCreateInfo.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT; setCreateInfo.bindingCount = 1; setCreateInfo.pBindings = &setBinding; VkDescriptorSetLayout setLayout = 0; VK_CHECK(vkCreateDescriptorSetLayout(device, &setCreateInfo, 0, &setLayout)); return setLayout; } std::pair<VkDescriptorPool, VkDescriptorSet> createDescriptorArray(VkDevice device, VkDescriptorSetLayout layout, uint32_t descriptorCount) { VkDescriptorPoolSize poolSize = { VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, descriptorCount }; VkDescriptorPoolCreateInfo poolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO }; poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT; poolInfo.maxSets = 1; poolInfo.poolSizeCount = 1; poolInfo.pPoolSizes = &poolSize; VkDescriptorPool pool = nullptr; VK_CHECK(vkCreateDescriptorPool(device, &poolInfo, 0, &pool)); VkDescriptorSetVariableDescriptorCountAllocateInfo setAllocateCountInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO }; setAllocateCountInfo.descriptorSetCount = 1; setAllocateCountInfo.pDescriptorCounts = &descriptorCount; VkDescriptorSetAllocateInfo setAllocateInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; setAllocateInfo.pNext = &setAllocateCountInfo; setAllocateInfo.descriptorPool = pool; setAllocateInfo.descriptorSetCount = 1; setAllocateInfo.pSetLayouts = &layout; VkDescriptorSet set = 0; VK_CHECK(vkAllocateDescriptorSets(device, &setAllocateInfo, &set)); return std::make_pair(pool, set); }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/shaders.h
C/C++ Header
#pragma once #include <string> struct Shader { std::string name; std::vector<char> spirv; VkShaderStageFlagBits stage; VkDescriptorType resourceTypes[32]; uint32_t resourceMask; uint32_t localSizeX; uint32_t localSizeY; uint32_t localSizeZ; bool usesPushConstants; bool usesDescriptorArray; }; struct ShaderSet { std::vector<Shader> shaders; const Shader& operator[](const char* name) const; }; struct Program { VkPipelineBindPoint bindPoint; VkPipelineLayout layout; VkDescriptorSetLayout setLayout; VkDescriptorUpdateTemplate updateTemplate; VkShaderStageFlags pushConstantStages; uint32_t pushConstantSize; uint32_t pushDescriptorCount; size_t descriptorSize; // only used for descriptor heaps VkDescriptorType resourceTypes[32] = {}; uint32_t resourceMask = 0; uint32_t localSizeX; uint32_t localSizeY; uint32_t localSizeZ; const Shader* shaders[8]; size_t shaderCount; }; bool loadShader(Shader& shader, const char* path); bool loadShader(Shader& shader, const char* base, const char* path); bool loadShaders(ShaderSet& shaders, const char* base, const char* path); using Shaders = std::initializer_list<const Shader*>; using Constants = std::initializer_list<int>; VkPipeline createGraphicsPipeline(VkDevice device, VkPipelineCache pipelineCache, const VkPipelineRenderingCreateInfo& renderingInfo, const Program& program, Constants constants = {}); VkPipeline createComputePipeline(VkDevice device, VkPipelineCache pipelineCache, const Program& program, Constants constants = {}); Program createProgram(VkDevice device, VkPipelineBindPoint bindPoint, Shaders shaders, size_t pushConstantSize, size_t descriptorSize = 0, VkDescriptorSetLayout arrayLayout = nullptr); void destroyProgram(VkDevice device, const Program& program); VkDescriptorSetLayout createDescriptorArrayLayout(VkDevice device); std::pair<VkDescriptorPool, VkDescriptorSet> createDescriptorArray(VkDevice device, VkDescriptorSetLayout layout, uint32_t descriptorCount); inline uint32_t getGroupCount(uint32_t threadCount, uint32_t localSize) { return (threadCount + localSize - 1) / localSize; } struct DescriptorInfo { union { VkDescriptorImageInfo image; VkDescriptorBufferInfo buffer; VkAccelerationStructureKHR accelerationStructure; }; const void* resource = NULL; int resourceMip = -1; DescriptorInfo() { } DescriptorInfo(VkAccelerationStructureKHR structure) { accelerationStructure = structure; } DescriptorInfo(VkImageView imageView) { image.sampler = VK_NULL_HANDLE; image.imageView = imageView; image.imageLayout = VK_IMAGE_LAYOUT_GENERAL; } DescriptorInfo(VkSampler sampler) { image.sampler = sampler; image.imageView = VK_NULL_HANDLE; image.imageLayout = VK_IMAGE_LAYOUT_UNDEFINED; } DescriptorInfo(VkBuffer buffer_) { buffer.buffer = buffer_; buffer.offset = 0; buffer.range = VK_WHOLE_SIZE; } DescriptorInfo(const struct Buffer& buffer); DescriptorInfo(const struct Image& image); DescriptorInfo(const struct Image& image, VkImageView mipView, int mipIndex); };
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/shaders/math.h
C/C++ Header
// 2D Polyhedral Bounds of a Clipped, Perspective-Projected 3D Sphere. Michael Mara, Morgan McGuire. 2013 bool projectSphere(vec3 c, float r, float znear, float P00, float P11, out vec4 aabb) { if (c.z < r + znear) return false; vec3 cr = c * r; float czr2 = c.z * c.z - r * r; float vx = sqrt(c.x * c.x + czr2); float minx = (vx * c.x - cr.z) / (vx * c.z + cr.x); float maxx = (vx * c.x + cr.z) / (vx * c.z - cr.x); float vy = sqrt(c.y * c.y + czr2); float miny = (vy * c.y - cr.z) / (vy * c.z + cr.y); float maxy = (vy * c.y + cr.z) / (vy * c.z - cr.y); aabb = vec4(minx * P00, miny * P11, maxx * P00, maxy * P11); aabb = aabb.xwzy * vec4(0.5f, -0.5f, 0.5f, -0.5f) + vec4(0.5f); // clip space -> uv space return true; } bool coneCull(vec3 center, float radius, vec3 cone_axis, float cone_cutoff, vec3 camera_position) { return dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius; } vec3 rotateQuat(vec3 v, vec4 q) { return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v); } // A Survey of Efficient Representations for Independent Unit Vectors vec2 encodeOct(vec3 v) { vec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z))); vec2 s = vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0); vec2 r = (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * s) : p; return r; } vec3 decodeOct(vec2 e) { // https://x.com/Stubbesaurus/status/937994790553227264 vec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y)); float t = max(-v.z, 0); v.xy += vec2(v.x >= 0 ? -t : t, v.y >= 0 ? -t : t); return normalize(v); } vec3 tosrgb(vec3 c) { return pow(c.xyz, vec3(1.0 / 2.2)); } vec4 tosrgb(vec4 c) { return vec4(pow(c.xyz, vec3(1.0 / 2.2)), c.w); } vec3 fromsrgb(vec3 c) { return pow(c.xyz, vec3(2.2)); } vec4 fromsrgb(vec4 c) { return vec4(pow(c.xyz, vec3(2.2)), c.w); } // Optimized filmic operator by Jim Hejl and Richard Burgess-Dawson // http://filmicworlds.com/blog/filmic-tonemapping-operators/ vec3 tonemap(vec3 c) { vec3 x = max(vec3(0), c - 0.004); return (x * (6.2 * x + .5)) / (x * (6.2 * x + 1.7) + 0.06); } // Gradient noise from Jorge Jimenez's presentation: // http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare float gradientNoise(vec2 uv) { return fract(52.9829189 * fract(dot(uv, vec2(0.06711056, 0.00583715)))); } void unpackTBN(uint np, uint tp, out vec3 normal, out vec4 tangent) { normal = ((ivec3(np) >> ivec3(0, 10, 20)) & ivec3(1023)) / 511.0 - 1.0; tangent.xyz = decodeOct(((ivec2(tp) >> ivec2(0, 8)) & ivec2(255)) / 127.0 - 1.0); tangent.w = (np & (1 << 30)) != 0 ? -1.0 : 1.0; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/shaders/mesh.h
C/C++ Header
#include "../config.h" struct Vertex { float16_t vx, vy, vz; uint16_t tp; // packed tangent: 8-8 octahedral uint np; // packed normal: 10-10-10-2 vector + bitangent sign float16_t tu, tv; }; struct Meshlet { float16_t center[3]; float16_t radius; int8_t cone_axis[3]; int8_t cone_cutoff; uint dataOffset; uint baseVertex; uint8_t vertexCount; uint8_t triangleCount; uint8_t shortRefs; uint8_t padding; }; struct CullData { mat4 view; float P00, P11, znear, zfar; // symmetric projection parameters float frustum[4]; // data for left/right/top/bottom frustum planes float lodTarget; // lod target error at z=1 float pyramidWidth, pyramidHeight; // depth pyramid size in texels uint drawCount; int cullingEnabled; int lodEnabled; int occlusionEnabled; int clusterOcclusionEnabled; int clusterBackfaceEnabled; uint postPass; }; struct Globals { mat4 projection; CullData cullData; float screenWidth, screenHeight; }; struct MeshLod { uint indexOffset; uint indexCount; uint meshletOffset; uint meshletCount; float error; }; struct Mesh { vec3 center; float radius; uint vertexOffset; uint vertexCount; uint lodCount; MeshLod lods[8]; }; struct Material { uint albedoTexture; uint normalTexture; uint specularTexture; uint emissiveTexture; vec4 diffuseFactor; vec4 specularFactor; vec3 emissiveFactor; }; struct MeshDraw { vec3 position; float scale; vec4 orientation; uint meshIndex; uint meshletVisibilityOffset; uint postPass; uint materialIndex; }; struct MeshDrawCommand { uint drawId; // VkDrawIndexedIndirectCommand uint indexCount; uint instanceCount; uint firstIndex; uint vertexOffset; uint firstInstance; }; struct MeshTaskCommand { uint drawId; uint taskOffset; uint taskCount; uint lateDrawVisibility; uint meshletVisibilityOffset; }; struct MeshTaskPayload { uint clusterIndices[TASK_WGSIZE]; };
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/swapchain.cpp
C++
#include "common.h" #include "swapchain.h" #include "config.h" #include <GLFW/glfw3.h> #ifdef VK_USE_PLATFORM_WIN32_KHR #include <GLFW/glfw3native.h> #endif #include <algorithm> #define VSYNC CONFIG_VSYNC const char** getSwapchainExtensions(uint32_t* count) { #ifdef VK_USE_PLATFORM_WIN32_KHR static const char* extensions[] = { VK_KHR_SURFACE_EXTENSION_NAME, VK_KHR_WIN32_SURFACE_EXTENSION_NAME }; *count = sizeof(extensions) / sizeof(extensions[0]); return extensions; #else return glfwGetRequiredInstanceExtensions(count); #endif } VkSurfaceKHR createSurface(VkInstance instance, GLFWwindow* window) { VkSurfaceKHR surface = 0; #ifdef VK_USE_PLATFORM_WIN32_KHR // Note: GLFW has a helper glfwCreateWindowSurface but we're going to do this the hard way to demonstrate the platform-specific surface creation assert(glfwGetPlatform() == GLFW_PLATFORM_WIN32); VkWin32SurfaceCreateInfoKHR createInfo = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR }; createInfo.hinstance = GetModuleHandle(0); createInfo.hwnd = glfwGetWin32Window(window); VK_CHECK(vkCreateWin32SurfaceKHR(instance, &createInfo, 0, &surface)); #else VK_CHECK(glfwCreateWindowSurface(instance, window, 0, &surface)); #endif return surface; } VkFormat getSwapchainFormat(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) { uint32_t formatCount = 0; VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, 0)); assert(formatCount > 0); std::vector<VkSurfaceFormatKHR> formats(formatCount); VK_CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(physicalDevice, surface, &formatCount, formats.data())); if (formatCount == 1 && formats[0].format == VK_FORMAT_UNDEFINED) return VK_FORMAT_R8G8B8A8_UNORM; for (uint32_t i = 0; i < formatCount; ++i) if (formats[i].format == VK_FORMAT_R8G8B8A8_UNORM || formats[i].format == VK_FORMAT_B8G8R8A8_UNORM) return formats[i].format; return formats[0].format; } static VkPresentModeKHR getPresentMode(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface) { if (VSYNC) return VK_PRESENT_MODE_FIFO_KHR; // guaranteed to be available uint32_t presentModeCount = 0; VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, 0)); assert(presentModeCount > 0); std::vector<VkPresentModeKHR> presentModes(presentModeCount); VK_CHECK(vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &presentModeCount, presentModes.data())); for (VkPresentModeKHR mode : presentModes) { if (mode == VK_PRESENT_MODE_MAILBOX_KHR) return mode; if (mode == VK_PRESENT_MODE_IMMEDIATE_KHR) return mode; } // fall back to fifo return VK_PRESENT_MODE_FIFO_KHR; } void createSwapchain(Swapchain& result, VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface, uint32_t familyIndex, GLFWwindow* window, VkFormat format, VkSwapchainKHR oldSwapchain) { VkSurfaceCapabilitiesKHR surfaceCaps; VK_CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &surfaceCaps)); int width = 0, height = 0; glfwGetFramebufferSize(window, &width, &height); VkPresentModeKHR presentMode = getPresentMode(physicalDevice, surface); VkCompositeAlphaFlagBitsKHR surfaceComposite = (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) ? VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR : (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR) ? VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR : (surfaceCaps.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR) ? VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR : VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR; VkSwapchainCreateInfoKHR createInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR }; createInfo.surface = surface; createInfo.minImageCount = std::max(unsigned(MIN_IMAGES), surfaceCaps.minImageCount); createInfo.imageFormat = format; createInfo.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; createInfo.imageExtent.width = width; createInfo.imageExtent.height = height; createInfo.imageArrayLayers = 1; createInfo.imageUsage = VK_IMAGE_USAGE_STORAGE_BIT; createInfo.queueFamilyIndexCount = 1; createInfo.pQueueFamilyIndices = &familyIndex; createInfo.preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; createInfo.compositeAlpha = surfaceComposite; createInfo.presentMode = presentMode; createInfo.oldSwapchain = oldSwapchain; VkSwapchainKHR swapchain = 0; VK_CHECK(vkCreateSwapchainKHR(device, &createInfo, 0, &swapchain)); uint32_t imageCount = 0; VK_CHECK(vkGetSwapchainImagesKHR(device, swapchain, &imageCount, 0)); std::vector<VkImage> images(imageCount); VK_CHECK(vkGetSwapchainImagesKHR(device, swapchain, &imageCount, images.data())); result.swapchain = swapchain; result.images = images; result.width = width; result.height = height; result.imageCount = imageCount; result.dirty = false; } void destroySwapchain(VkDevice device, const Swapchain& swapchain) { vkDestroySwapchainKHR(device, swapchain.swapchain, 0); } SwapchainStatus updateSwapchain(Swapchain& result, VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface, uint32_t familyIndex, GLFWwindow* window, VkFormat format) { int width = 0, height = 0; glfwGetFramebufferSize(window, &width, &height); if (width == 0 || height == 0) return Swapchain_NotReady; if (result.width == width && result.height == height && !result.dirty) return Swapchain_Ready; Swapchain old = result; createSwapchain(result, physicalDevice, device, surface, familyIndex, window, format, old.swapchain); VK_CHECK(vkDeviceWaitIdle(device)); destroySwapchain(device, old); return Swapchain_Resized; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/swapchain.h
C/C++ Header
#pragma once struct Swapchain { VkSwapchainKHR swapchain; std::vector<VkImage> images; uint32_t width, height; uint32_t imageCount; bool dirty; }; typedef struct GLFWwindow GLFWwindow; const char** getSwapchainExtensions(uint32_t* count); VkSurfaceKHR createSurface(VkInstance instance, GLFWwindow* window); VkFormat getSwapchainFormat(VkPhysicalDevice physicalDevice, VkSurfaceKHR surface); void createSwapchain(Swapchain& result, VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface, uint32_t familyIndex, GLFWwindow* window, VkFormat format, VkSwapchainKHR oldSwapchain = 0); void destroySwapchain(VkDevice device, const Swapchain& swapchain); enum SwapchainStatus { Swapchain_Ready, Swapchain_Resized, Swapchain_NotReady, }; SwapchainStatus updateSwapchain(Swapchain& result, VkPhysicalDevice physicalDevice, VkDevice device, VkSurfaceKHR surface, uint32_t familyIndex, GLFWwindow* window, VkFormat format);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/textures.cpp
C++
#include "common.h" #include "textures.h" #include "resources.h" #include <stdio.h> #include <memory> struct DDS_PIXELFORMAT { unsigned int dwSize; unsigned int dwFlags; unsigned int dwFourCC; unsigned int dwRGBBitCount; unsigned int dwRBitMask; unsigned int dwGBitMask; unsigned int dwBBitMask; unsigned int dwABitMask; }; struct DDS_HEADER { unsigned int dwSize; unsigned int dwFlags; unsigned int dwHeight; unsigned int dwWidth; unsigned int dwPitchOrLinearSize; unsigned int dwDepth; unsigned int dwMipMapCount; unsigned int dwReserved1[11]; DDS_PIXELFORMAT ddspf; unsigned int dwCaps; unsigned int dwCaps2; unsigned int dwCaps3; unsigned int dwCaps4; unsigned int dwReserved2; }; struct DDS_HEADER_DXT10 { unsigned int dxgiFormat; unsigned int resourceDimension; unsigned int miscFlag; unsigned int arraySize; unsigned int miscFlags2; }; const unsigned int DDSCAPS2_CUBEMAP = 0x200; const unsigned int DDSCAPS2_VOLUME = 0x200000; const unsigned int DDS_DIMENSION_TEXTURE2D = 3; enum DXGI_FORMAT { DXGI_FORMAT_BC1_UNORM = 71, DXGI_FORMAT_BC1_UNORM_SRGB = 72, DXGI_FORMAT_BC2_UNORM = 74, DXGI_FORMAT_BC2_UNORM_SRGB = 75, DXGI_FORMAT_BC3_UNORM = 77, DXGI_FORMAT_BC3_UNORM_SRGB = 78, DXGI_FORMAT_BC4_UNORM = 80, DXGI_FORMAT_BC4_SNORM = 81, DXGI_FORMAT_BC5_UNORM = 83, DXGI_FORMAT_BC5_SNORM = 84, DXGI_FORMAT_BC6H_UF16 = 95, DXGI_FORMAT_BC6H_SF16 = 96, DXGI_FORMAT_BC7_UNORM = 98, DXGI_FORMAT_BC7_UNORM_SRGB = 99, }; static unsigned int fourCC(const char (&str)[5]) { return (unsigned(str[0]) << 0) | (unsigned(str[1]) << 8) | (unsigned(str[2]) << 16) | (unsigned(str[3]) << 24); } static VkFormat getFormat(const DDS_HEADER& header, const DDS_HEADER_DXT10& header10) { if (header.ddspf.dwFourCC == fourCC("DXT1")) return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; if (header.ddspf.dwFourCC == fourCC("DXT3")) return VK_FORMAT_BC2_UNORM_BLOCK; if (header.ddspf.dwFourCC == fourCC("DXT5")) return VK_FORMAT_BC3_UNORM_BLOCK; if (header.ddspf.dwFourCC == fourCC("ATI1")) return VK_FORMAT_BC4_UNORM_BLOCK; if (header.ddspf.dwFourCC == fourCC("ATI2")) return VK_FORMAT_BC5_UNORM_BLOCK; if (header.ddspf.dwFourCC == fourCC("DX10")) { switch (header10.dxgiFormat) { case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB: return VK_FORMAT_BC1_RGBA_UNORM_BLOCK; case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB: return VK_FORMAT_BC2_UNORM_BLOCK; case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB: return VK_FORMAT_BC3_UNORM_BLOCK; case DXGI_FORMAT_BC4_UNORM: return VK_FORMAT_BC4_UNORM_BLOCK; case DXGI_FORMAT_BC4_SNORM: return VK_FORMAT_BC4_SNORM_BLOCK; case DXGI_FORMAT_BC5_UNORM: return VK_FORMAT_BC5_UNORM_BLOCK; case DXGI_FORMAT_BC5_SNORM: return VK_FORMAT_BC5_SNORM_BLOCK; case DXGI_FORMAT_BC6H_UF16: return VK_FORMAT_BC6H_UFLOAT_BLOCK; case DXGI_FORMAT_BC6H_SF16: return VK_FORMAT_BC6H_SFLOAT_BLOCK; case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB: return VK_FORMAT_BC7_UNORM_BLOCK; } } return VK_FORMAT_UNDEFINED; } static size_t getImageSizeBC(unsigned int width, unsigned int height, unsigned int levels, unsigned int blockSize) { size_t result = 0; for (unsigned int i = 0; i < levels; ++i) { result += ((width + 3) / 4) * ((height + 3) / 4) * blockSize; width = width > 1 ? width / 2 : 1; height = height > 1 ? height / 2 : 1; } return result; } bool loadImage(Image& image, VkDevice device, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties, const Buffer& scratch, const char* path) { FILE* file = fopen(path, "rb"); if (!file) return false; std::unique_ptr<FILE, int (*)(FILE*)> filePtr(file, fclose); unsigned int magic = 0; if (fread(&magic, sizeof(magic), 1, file) != 1 || magic != fourCC("DDS ")) return false; DDS_HEADER header = {}; if (fread(&header, sizeof(header), 1, file) != 1) return false; DDS_HEADER_DXT10 header10 = {}; if (header.ddspf.dwFourCC == fourCC("DX10") && fread(&header10, sizeof(header10), 1, file) != 1) return false; if (header.dwSize != sizeof(header) || header.ddspf.dwSize != sizeof(header.ddspf)) return false; if (header.dwCaps2 & (DDSCAPS2_CUBEMAP | DDSCAPS2_VOLUME)) return false; if (header.ddspf.dwFourCC == fourCC("DX10") && header10.resourceDimension != DDS_DIMENSION_TEXTURE2D) return false; VkFormat format = getFormat(header, header10); if (format == VK_FORMAT_UNDEFINED) return false; unsigned int blockSize = (format == VK_FORMAT_BC1_RGBA_UNORM_BLOCK || format == VK_FORMAT_BC4_SNORM_BLOCK || format == VK_FORMAT_BC4_UNORM_BLOCK) ? 8 : 16; size_t imageSize = getImageSizeBC(header.dwWidth, header.dwHeight, header.dwMipMapCount, blockSize); if (scratch.size < imageSize) return false; VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; createImage(image, device, memoryProperties, header.dwWidth, header.dwHeight, header.dwMipMapCount, format, usage); size_t readSize = fread(scratch.data, 1, imageSize, file); if (readSize != imageSize) return false; if (fgetc(file) != -1) return false; filePtr.reset(); file = nullptr; VK_CHECK(vkResetCommandPool(device, commandPool, 0)); VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VK_CHECK(vkBeginCommandBuffer(commandBuffer, &beginInfo)); VkImageMemoryBarrier2 preBarrier = imageBarrier(image.image, 0, 0, VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL); pipelineBarrier(commandBuffer, 0, 0, nullptr, 1, &preBarrier); size_t bufferOffset = 0; unsigned int mipWidth = header.dwWidth, mipHeight = header.dwHeight; for (unsigned int i = 0; i < header.dwMipMapCount; ++i) { VkBufferImageCopy region = { bufferOffset, 0, 0, { VK_IMAGE_ASPECT_COLOR_BIT, i, 0, 1 }, { 0, 0, 0 }, { mipWidth, mipHeight, 1 }, }; vkCmdCopyBufferToImage(commandBuffer, scratch.buffer, image.image, VK_IMAGE_LAYOUT_GENERAL, 1, &region); bufferOffset += ((mipWidth + 3) / 4) * ((mipHeight + 3) / 4) * blockSize; mipWidth = mipWidth > 1 ? mipWidth / 2 : 1; mipHeight = mipHeight > 1 ? mipHeight / 2 : 1; } assert(bufferOffset == imageSize); stageBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT); VK_CHECK(vkEndCommandBuffer(commandBuffer)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; VK_CHECK(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VK_CHECK(vkDeviceWaitIdle(device)); return true; }
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/textures.h
C/C++ Header
#pragma once struct Image; struct Buffer; bool loadImage(Image& image, VkDevice device, VkCommandPool commandPool, VkCommandBuffer commandBuffer, VkQueue queue, const VkPhysicalDeviceMemoryProperties& memoryProperties, const Buffer& scratch, const char* path);
zeux/niagara
1,665
A Vulkan renderer written from scratch on stream
C++
zeux
Arseny Kapoulkine
src/AABB2.h
C/C++ Header
#pragma once #include <algorithm> template <typename T> class AABB2 { public: AABB2() { Reset(); } AABB2(const Vector2<T>& _boxPoint1, const Vector2<T>& _boxPoint2) { Set(_boxPoint1, _boxPoint2); } bool Intersects(const AABB2<T>& aabb) const { if ((boxPoint1.x > aabb.boxPoint2.x) || (aabb.boxPoint1.x > boxPoint2.x)) return 0; if ((boxPoint1.y > aabb.boxPoint2.y) || (aabb.boxPoint1.y > boxPoint2.y)) return 0; return 1; } template <bool isFiniteCast> bool Intersects(Vector2<T> rayStart, Vector2<T> rayDir, float& paramMin, float& paramMax) { // r.dir is unit direction vector of ray Vector2f invDir(1.0f / rayDir.x, 1.0f / rayDir.y); // lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner // r.org is origin of ray float t1 = (boxPoint1.x - rayStart.x) * invDir.x; float t2 = (boxPoint2.x - rayStart.x) * invDir.x; float t3 = (boxPoint1.y - rayStart.y) * invDir.y; float t4 = (boxPoint2.y - rayStart.y) * invDir.y; paramMin = std::max(std::min(t1, t2), std::min(t3, t4)); paramMax = std::min(std::max(t1, t2), std::max(t3, t4)); // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us if (isFiniteCast && paramMax < 0) { return false; } // if tmin > tmax, ray doesn't intersect AABB if (paramMin > paramMax) { return false; } return true; } bool Includes(const Vector2<T>& point) const { if ((point.x < boxPoint1.x) || (point.x > boxPoint2.x) || (point.y < boxPoint1.y) || (point.y > boxPoint2.y)) { return 0; } return 1; } bool Includes(const AABB2<T>& aabb) const { return Includes(aabb.boxPoint1) && Includes(aabb.boxPoint2); } void Set(const Vector2<T>& _boxPoint1, const Vector2<T>& _boxPoint2) { boxPoint1 = _boxPoint1; boxPoint2 = _boxPoint2; } void Reset() { boxPoint1 = Vector2<T>::zeroVector(); boxPoint2 = Vector2<T>::zeroVector(); } void Expand(const Vector2<T>& additionalPoint) { boxPoint1.x = Min(boxPoint1.x, additionalPoint.x); boxPoint1.y = Min(boxPoint1.y, additionalPoint.y); boxPoint2.x = Max(boxPoint2.x, additionalPoint.x); boxPoint2.y = Max(boxPoint2.y, additionalPoint.y); } void Expand(const AABB2<T>& internalAABB) { Expand(internalAABB.boxPoint1); Expand(internalAABB.boxPoint2); } void Expand(const T mult) { Vector2<T> size = boxPoint2 - boxPoint1; boxPoint1 -= size * (mult - T(1.0)) * T(0.5); boxPoint2 += size * (mult - T(1.0)) * T(0.5); } const T Square() //perimeter actually, used for AABBTree balancing { Vector2<T> size = boxPoint2 - boxPoint1; return (size.x + size.y) * T(2.0); } Vector2<T> GetSize() { return boxPoint2 - boxPoint1; } Vector2<T> boxPoint1, boxPoint2; }; typedef AABB2<float> AABB2f; typedef AABB2<double> AABB2d;
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Collider.cpp
C++
#include "Collider.h" #include "base/Parallel.h" #include "base/RadixSort.h" #include "microprofile.h" static NOINLINE bool ComputeSeparatingAxis(RigidBody* body1, RigidBody* body2, Vector2f& separatingAxis) { // http://www.geometrictools.com/Source/Intersection2D.html#PlanarPlanar // Adapted to return axis with least amount of penetration const Vector2f* A0 = &body1->coords.xVector; const Vector2f* A1 = &body2->coords.xVector; const Vector2f& E0 = body1->geom.size; const Vector2f& E1 = body2->geom.size; Vector2f D = body1->coords.pos - body2->coords.pos; float Adot[2][2]; // Test axis box0.axis[0] Adot[0][0] = fabsf(A0[0] * A1[0]); Adot[0][1] = fabsf(A0[0] * A1[1]); float rSum0 = E0.x + E1.x * Adot[0][0] + E1.y * Adot[0][1]; float dist0 = fabsf(A0[0] * D) - rSum0; if (dist0 > 0) return false; float bestdist = dist0; Vector2f bestaxis = A0[0]; // Test axis box0.axis[1]. Adot[1][0] = fabsf(A0[1] * A1[0]); Adot[1][1] = fabsf(A0[1] * A1[1]); float rSum1 = E0.y + E1.x * Adot[1][0] + E1.y * Adot[1][1]; float dist1 = fabsf(A0[1] * D) - rSum1; if (dist1 > 0) return false; if (dist1 > bestdist) { bestdist = dist1; bestaxis = A0[1]; } // Test axis box1.axis[0]. float rSum2 = E1.x + E0.x * Adot[0][0] + E0.y * Adot[1][0]; float dist2 = fabsf(A1[0] * D) - rSum2; if (dist2 > 0) return false; if (dist2 > bestdist) { bestdist = dist2; bestaxis = A1[0]; } // Test axis box1.axis[1]. float rSum3 = E1.y + E0.x * Adot[0][1] + E0.y * Adot[1][1]; float dist3 = fabsf(A1[1] * D) - rSum3; if (dist3 > 0) return false; if (dist3 > bestdist) { bestdist = dist3; bestaxis = A1[1]; } separatingAxis = bestaxis; return true; } static void AddPoint(ContactPoint* points, int& pointCount, ContactPoint& newbie) { ContactPoint* closest = 0; float bestdepth = std::numeric_limits<float>::max(); for (int collisionIndex = 0; collisionIndex < pointCount; collisionIndex++) { ContactPoint& col = points[collisionIndex]; if (newbie.Equals(col, 2.0f)) { float depth = (newbie.delta1 - col.delta1).SquareLen() + (newbie.delta2 - col.delta2).SquareLen(); if (depth < bestdepth) { bestdepth = depth; closest = &col; } } } if (closest) { closest->isMerged = 1; closest->isNewlyCreated = 0; closest->normal = newbie.normal; closest->delta1 = newbie.delta1; closest->delta2 = newbie.delta2; } else { assert(pointCount < 4); newbie.isMerged = 1; newbie.isNewlyCreated = 1; points[pointCount++] = newbie; } } static void NOINLINE GenerateContacts(RigidBody* body1, RigidBody* body2, ContactPoint* points, int& pointCount, Vector2f separatingAxis) { if (separatingAxis * (body1->coords.pos - body2->coords.pos) < 0.0f) separatingAxis.Invert(); const int kMaxSupportPoints = 2; Vector2f supportPoints1[kMaxSupportPoints]; Vector2f supportPoints2[kMaxSupportPoints]; float linearTolerance = 2.0f; int supportPointsCount1 = body1->geom.GetSupportPointSet(-separatingAxis, supportPoints1); int supportPointsCount2 = body2->geom.GetSupportPointSet(separatingAxis, supportPoints2); if ((supportPointsCount1 == 2) && (((supportPoints1[0] - supportPoints1[1])).SquareLen() < linearTolerance * linearTolerance)) { supportPoints1[0] = (supportPoints1[0] + supportPoints1[1]) * 0.5f; supportPointsCount1 = 1; } if ((supportPointsCount2 == 2) && (((supportPoints2[0] - supportPoints2[1])).SquareLen() < linearTolerance * linearTolerance)) { supportPoints2[0] = (supportPoints2[0] + supportPoints2[1]) * 0.5f; supportPointsCount2 = 1; } if ((supportPointsCount1 == 1) && (supportPointsCount2 == 1)) { Vector2f delta = supportPoints2[0] - supportPoints1[0]; //float eps = (delta ^ separatingAxis).SquareLen(); if (delta * separatingAxis >= 0.0f) { ContactPoint newbie(supportPoints1[0], supportPoints2[0], separatingAxis, body1, body2); AddPoint(points, pointCount, newbie); } } else if ((supportPointsCount1 == 1) && (supportPointsCount2 == 2)) { Vector2f n = (supportPoints2[1] - supportPoints2[0]).GetPerpendicular(); Vector2f point; ProjectPointToLine(supportPoints1[0], supportPoints2[0], n, separatingAxis, point); if ((((point - supportPoints2[0]) * (supportPoints2[1] - supportPoints2[0])) >= 0.0f) && (((point - supportPoints2[1]) * (supportPoints2[0] - supportPoints2[1])) >= 0.0f)) { ContactPoint newbie(supportPoints1[0], point, separatingAxis, body1, body2); AddPoint(points, pointCount, newbie); } } else if ((supportPointsCount1 == 2) && (supportPointsCount2 == 1)) { Vector2f n = (supportPoints1[1] - supportPoints1[0]).GetPerpendicular(); Vector2f point; ProjectPointToLine(supportPoints2[0], supportPoints1[0], n, separatingAxis, point); if ((((point - supportPoints1[0]) * (supportPoints1[1] - supportPoints1[0])) >= 0.0f) && (((point - supportPoints1[1]) * (supportPoints1[0] - supportPoints1[1])) >= 0.0f)) { ContactPoint newbie(point, supportPoints2[0], separatingAxis, body1, body2); AddPoint(points, pointCount, newbie); } } else if ((supportPointsCount2 == 2) && (supportPointsCount1 == 2)) { struct TempColInfo { Vector2f point1, point2; }; TempColInfo tempCol[4]; int tempCols = 0; for (int i = 0; i < 2; i++) { Vector2f n = (supportPoints2[1] - supportPoints2[0]).GetPerpendicular(); if ((supportPoints1[i] - supportPoints2[0]) * n >= 0.0) { Vector2f point; ProjectPointToLine(supportPoints1[i], supportPoints2[0], n, separatingAxis, point); if ((((point - supportPoints2[0]) * (supportPoints2[1] - supportPoints2[0])) >= 0.0f) && (((point - supportPoints2[1]) * (supportPoints2[0] - supportPoints2[1])) >= 0.0f)) { tempCol[tempCols].point1 = supportPoints1[i]; tempCol[tempCols].point2 = point; tempCols++; } } } for (int i = 0; i < 2; i++) { Vector2f n = (supportPoints1[1] - supportPoints1[0]).GetPerpendicular(); if ((supportPoints2[i] - supportPoints1[0]) * n >= 0.0) { Vector2f point; ProjectPointToLine(supportPoints2[i], supportPoints1[0], n, separatingAxis, point); if ((((point - supportPoints1[0]) * (supportPoints1[1] - supportPoints1[0])) >= 0.0f) && (((point - supportPoints1[1]) * (supportPoints1[0] - supportPoints1[1])) >= 0.0f)) { tempCol[tempCols].point1 = point; tempCol[tempCols].point2 = supportPoints2[i]; tempCols++; } } } if (tempCols == 1) //buggy but must work { ContactPoint newbie(tempCol[0].point1, tempCol[0].point2, separatingAxis, body1, body2); AddPoint(points, pointCount, newbie); } if (tempCols >= 2) //means only equality, but clamp to two points { ContactPoint newbie1(tempCol[0].point1, tempCol[0].point2, separatingAxis, body1, body2); AddPoint(points, pointCount, newbie1); ContactPoint newbie2(tempCol[1].point1, tempCol[1].point2, separatingAxis, body1, body2); AddPoint(points, pointCount, newbie2); } } } static void UpdateManifold(Manifold& m, RigidBody* bodies, ContactPoint* points) { ContactPoint newpoints[kMaxContactPoints * 2]; for (int collisionIndex = 0; collisionIndex < m.pointCount; collisionIndex++) { newpoints[collisionIndex] = points[collisionIndex]; newpoints[collisionIndex].isMerged = 0; newpoints[collisionIndex].isNewlyCreated = 0; } int newPointCount = m.pointCount; RigidBody* body1 = &bodies[m.body1Index]; RigidBody* body2 = &bodies[m.body2Index]; Vector2f separatingAxis; if (ComputeSeparatingAxis(body1, body2, separatingAxis)) { GenerateContacts(body1, body2, newpoints, newPointCount, separatingAxis); } m.pointCount = 0; for (int collisionIndex = 0; collisionIndex < newPointCount; ++collisionIndex) { if (newpoints[collisionIndex].isMerged) { assert(m.pointCount < kMaxContactPoints); points[m.pointCount++] = newpoints[collisionIndex]; } } } Collider::Collider() { } NOINLINE void Collider::UpdateBroadphase(RigidBody* bodies, size_t bodiesCount) { MICROPROFILE_SCOPEI("Physics", "UpdateBroadphase", -1); broadphase.resize(bodiesCount); broadphaseSort[0].resize(bodiesCount); broadphaseSort[1].resize(bodiesCount); for (size_t bodyIndex = 0; bodyIndex < bodiesCount; ++bodyIndex) { const AABB2f& aabb = bodies[bodyIndex].geom.aabb; broadphaseSort[0][bodyIndex].value = radixFloat(aabb.boxPoint1.x); broadphaseSort[0][bodyIndex].index = bodyIndex; } radixSort3(broadphaseSort[0].data, broadphaseSort[1].data, bodiesCount, [](const BroadphaseSortEntry& e) { return e.value; }); for (size_t i = 0; i < bodiesCount; ++i) { unsigned int bodyIndex = broadphaseSort[1][i].index; const AABB2f& aabb = bodies[bodyIndex].geom.aabb; BroadphaseEntry e = { aabb.boxPoint1.x, aabb.boxPoint2.x, (aabb.boxPoint1.y + aabb.boxPoint2.y) * 0.5f, (aabb.boxPoint2.y - aabb.boxPoint1.y) * 0.5f, unsigned(bodyIndex)}; broadphase[i] = e; } } NOINLINE void Collider::UpdatePairs(WorkQueue& queue, RigidBody* bodies, size_t bodiesCount) { assert(bodiesCount == broadphase.size); if (queue.getWorkerCount() == 0) UpdatePairsSerial(bodies, bodiesCount); else UpdatePairsParallel(queue, bodies, bodiesCount); } NOINLINE void Collider::UpdatePairsSerial(RigidBody* bodies, size_t bodiesCount) { MICROPROFILE_SCOPEI("Physics", "UpdatePairsSerial", -1); for (size_t bodyIndex1 = 0; bodyIndex1 < bodiesCount; bodyIndex1++) { const BroadphaseEntry& be1 = broadphase[bodyIndex1]; float maxx = be1.maxx; for (size_t bodyIndex2 = bodyIndex1 + 1; bodyIndex2 < bodiesCount; bodyIndex2++) { const BroadphaseEntry& be2 = broadphase[bodyIndex2]; if (be2.minx > maxx) break; if (fabsf(be2.centery - be1.centery) <= be1.extenty + be2.extenty) { if (manifoldMap.insert(std::make_pair(be1.index, be2.index))) { manifolds.push_back(Manifold(be1.index, be2.index, manifolds.size * kMaxContactPoints)); } } } } } NOINLINE void Collider::UpdatePairsParallel(WorkQueue& queue, RigidBody* bodies, size_t bodiesCount) { MICROPROFILE_SCOPEI("Physics", "UpdatePairsParallel", -1); manifoldBuffers.resize(queue.getWorkerCount() + 1); for (auto& buf: manifoldBuffers) buf.pairs.clear(); parallelFor(queue, 0, bodiesCount, 128, [this, bodies, bodiesCount](int bodyIndex1, int worker) { UpdatePairsOne(bodies, bodyIndex1, bodyIndex1 + 1, bodiesCount, manifoldBuffers[worker]); }); MICROPROFILE_SCOPEI("Physics", "CreateManifolds", -1); for (auto& buf : manifoldBuffers) { for (auto& pair : buf.pairs) { manifoldMap.insert(pair); manifolds.push_back(Manifold(pair.first, pair.second, manifolds.size * kMaxContactPoints)); } } } void Collider::UpdatePairsOne(RigidBody* bodies, size_t bodyIndex1, size_t startIndex, size_t endIndex, ManifoldDeferredBuffer& buffer) { const BroadphaseEntry& be1 = broadphase[bodyIndex1]; float maxx = be1.maxx; for (size_t bodyIndex2 = startIndex; bodyIndex2 < endIndex; bodyIndex2++) { const BroadphaseEntry& be2 = broadphase[bodyIndex2]; if (be2.minx > maxx) return; if (fabsf(be2.centery - be1.centery) <= be1.extenty + be2.extenty) { if (!manifoldMap.contains(std::make_pair(be1.index, be2.index))) { buffer.pairs.push_back(std::make_pair(be1.index, be2.index)); } } } } NOINLINE void Collider::UpdateManifolds(WorkQueue& queue, RigidBody* bodies) { MICROPROFILE_SCOPEI("Physics", "UpdateManifolds", -1); contactPoints.resize_copy(manifolds.size * kMaxContactPoints); parallelFor(queue, manifolds.data, manifolds.size, 16, [&](Manifold& m, int) { UpdateManifold(m, bodies, contactPoints.data + m.pointIndex); }); } NOINLINE void Collider::PackManifolds(RigidBody* bodies) { MICROPROFILE_SCOPEI("Physics", "PackManifolds", -1); for (int manifoldIndex = 0; manifoldIndex < manifolds.size;) { Manifold& m = manifolds[manifoldIndex]; // TODO // This reduces broadphase insert/erase operations, which is good // However, current behavior causes issues with DenseHash - is it possible to improve it? if (m.pointCount == 0 && !bodies[m.body1Index].geom.aabb.Intersects(bodies[m.body2Index].geom.aabb)) { manifoldMap.erase(std::make_pair(m.body1Index, m.body2Index)); if (manifoldIndex < manifolds.size) { Manifold& me = manifolds[manifolds.size - 1]; unsigned int pointIndex = m.pointIndex; for (int i = 0; i < me.pointCount; ++i) contactPoints[pointIndex + i] = contactPoints[me.pointIndex + i]; m = me; m.pointIndex = pointIndex; } manifolds.size--; } else { manifoldIndex++; } } contactPoints.truncate(manifolds.size * kMaxContactPoints); }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Collider.h
C/C++ Header
#pragma once #include "Manifold.h" #include "base/DenseHash.h" #include "base/AlignedArray.h" namespace std { template <> struct hash<std::pair<unsigned int, unsigned int>> { size_t operator()(const std::pair<unsigned int, unsigned int>& p) const { unsigned int lb = p.first; unsigned int rb = p.second; return lb ^ (rb + 0x9e3779b9 + (lb << 6) + (lb >> 2)); } }; } class WorkQueue; struct Collider { Collider(); void UpdateBroadphase(RigidBody* bodies, size_t bodiesCount); void UpdatePairs(WorkQueue& queue, RigidBody* bodies, size_t bodiesCount); void UpdatePairsSerial(RigidBody* bodies, size_t bodiesCount); void UpdatePairsParallel(WorkQueue& queue, RigidBody* bodies, size_t bodiesCount); struct ManifoldDeferredBuffer; void UpdatePairsOne(RigidBody* bodies, size_t bodyIndex1, size_t startIndex, size_t endIndex, ManifoldDeferredBuffer& buffer); void UpdateManifolds(WorkQueue& queue, RigidBody* bodies); void PackManifolds(RigidBody* bodies); struct ManifoldDeferredBuffer { AlignedArray<std::pair<int, int>> pairs; }; struct BroadphaseEntry { float minx, maxx; float centery, extenty; unsigned int index; }; struct BroadphaseSortEntry { unsigned int value; unsigned int index; }; DenseHashSet<std::pair<unsigned int, unsigned int>> manifoldMap; AlignedArray<Manifold> manifolds; AlignedArray<ContactPoint> contactPoints; std::vector<ManifoldDeferredBuffer> manifoldBuffers; AlignedArray<BroadphaseEntry> broadphase; AlignedArray<BroadphaseSortEntry> broadphaseSort[2]; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Configuration.h
C/C++ Header
#pragma once struct Configuration { enum SolveMode { Solve_Scalar, Solve_SSE2, Solve_AVX2, }; enum IslandMode { Island_Single, Island_Multiple, Island_SingleSloppy, Island_MultipleSloppy }; SolveMode solveMode; IslandMode islandMode; int contactIterationsCount; int penetrationIterationsCount; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Coords2.h
C/C++ Header
#pragma once template <typename T> class Coords2 { public: Vector2<T> xVector, yVector; Vector2<T> pos; Coords2() {} Coords2(const Vector2<T>& _pos, const T angle) { float pi = 3.141592f; xVector = Vector2<T>(cos(angle), sin(angle)); yVector = Vector2<T>(cos(angle + T(pi) / T(2.0)), sin(angle + T(pi) / T(2.0))); pos = _pos; } const Vector2<T> GetPointRelativePos(const Vector2<T>& globalPoint) const { Vector2<T> delta = globalPoint - pos; return Vector2<T>(delta * xVector, delta * yVector); } const Vector2<T> GetAxisRelativeOrientation(const Vector2<T>& globalAxis) const { Vector2<T> delta = globalAxis; return Vector2<T>(delta * xVector, delta * yVector); } const Vector2<T> GetPointGlobalPos(const Vector2<T>& relativePoint) const { return pos + xVector * relativePoint.x + yVector * relativePoint.y; } const Vector2<T> GetAxisGlobalOrientation(const Vector2<T>& relativeAxis) const { return xVector * relativeAxis.x + yVector * relativeAxis.y; } const Coords2<T> GetGlobalCoords(const Coords2<T>& localCoords) { Coords2<T> res; res.pos = GetPointGlobalPos(localCoords.pos); res.xVector = GetAxisGlobalOrientation(localCoords.xVector); res.yVector = GetAxisGlobalOrientation(localCoords.yVector); return res; } const Coords2<T> GetLocalCoords(const Coords2<T>& globalCoords) { Coords2<T> res; res.pos = GetPointRelativePos(globalCoords.pos); res.xVector = GetAxisRelativeOrientation(globalCoords.xVector); res.yVector = GetAxisRelativeOrientation(globalCoords.yVector); return res; } void Identity() { xVector = Vector2<T>(1.0f, 0.0f); yVector = Vector2<T>(0.0f, 1.0f); pos = Vector2<T>::zeroVector(); } void SetRotation(const T& angle) { float pi = 3.141592f; xVector = Vector2<T>(cos(angle), sin(angle)); yVector = Vector2<T>(cos(angle + pi / 2.0), sin(angle + pi / 2.0)); } void Rotate(const T& angle) { this->xVector.Rotate(angle); this->yVector.Rotate(angle); } static const Coords2<T> defCoords() { Coords2<T> coords; coords.pos = Vector2<T>::zeroVector(); coords.xVector = Vector2<T>::xAxis(); coords.yVector = Vector2<T>::yAxis(); return coords; } }; typedef Coords2<float> Coords2f; typedef Coords2<double> Coords2d; typedef Coords2f Coords2f; typedef Coords2d Coords2d;
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Geom.h
C/C++ Header
#pragma once #include "Vector2.h" #include "Coords2.h" #include "AABB2.h" #include <cmath> struct RigidBody; struct Geom { Vector2f GetClippingVertex(const Vector2f& axis) const { Vector2f xdim = coords.xVector * size.x; Vector2f ydim = coords.yVector * size.y; float xsgn = coords.xVector * axis < 0.0f ? -1.0f : 1.0f; float ysgn = coords.yVector * axis < 0.0f ? -1.0f : 1.0f; return coords.pos + xsgn * xdim + ysgn * ydim; } bool GetClippingEdge(const Vector2f& axis, Vector2f& edgepoint1, Vector2f& edgepoint2) const { edgepoint1 = coords.pos; edgepoint2 = coords.pos; Vector2f xdim = coords.xVector * size.x; Vector2f ydim = coords.yVector * size.y; Vector2f offset = Vector2f::zero(); float xdiff = axis * coords.xVector; float ydiff = axis * coords.yVector; if (fabsf(xdiff) < fabsf(ydiff)) { if (axis * ydim > 0.0f) { offset += ydim; edgepoint1 += xdim; edgepoint2 -= xdim; } else { offset -= ydim; edgepoint1 -= xdim; edgepoint2 += xdim; } } else { if (axis * xdim > 0.0f) { offset += xdim; edgepoint1 -= ydim; edgepoint2 += ydim; } else { offset -= xdim; edgepoint1 += ydim; edgepoint2 -= ydim; } } edgepoint1 += offset; edgepoint2 += offset; return 1; } int GetSupportPointSet(const Vector2f& axis, Vector2f* supportPoints) { if ((fabsf(axis * coords.xVector) < 0.1f) || (fabsf(axis * coords.yVector) < 0.1f)) { GetClippingEdge(axis, supportPoints[0], supportPoints[1]); return 2; } supportPoints[0] = GetClippingVertex(axis); return 1; } void RecomputeAABB() { Vector2f diff = Vector2f( fabsf(coords.xVector.x) * size.x + fabsf(coords.yVector.x) * size.y, fabsf(coords.xVector.y) * size.x + fabsf(coords.yVector.y) * size.y); aabb.Set(coords.pos - diff, coords.pos + diff); } Vector2f size; Coords2f coords; AABB2f aabb; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Joints.h
C/C++ Header
#pragma once #include "RigidBody.h" #include "Manifold.h" struct ContactJoint { ContactJoint(int body1Index, int body2Index, int collisionIndex) { this->contactPointIndex = collisionIndex; this->body1Index = body1Index; this->body2Index = body2Index; normalLimiter_accumulatedImpulse = 0.f; frictionLimiter_accumulatedImpulse = 0.f; } int contactPointIndex; int body1Index; int body2Index; float normalLimiter_accumulatedImpulse; float frictionLimiter_accumulatedImpulse; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Manifold.h
C/C++ Header
#pragma once #include "Vector2.h" #include "Geom.h" #include "RigidBody.h" #include <limits> #include <cassert> static const int kMaxContactPoints = 2; struct ContactPoint { ContactPoint() { } ContactPoint(Vector2f point1, const Vector2f& point2, const Vector2f normal, RigidBody* body1, RigidBody* body2) { this->delta1 = point1 - body1->coords.pos; this->delta2 = point2 - body2->coords.pos; this->normal = normal; isMerged = 0; isNewlyCreated = 1; solverIndex = -1; } bool Equals(const ContactPoint& other, float tolerance) const { if (((other.delta1 - delta1).SquareLen() > tolerance * tolerance) && ((other.delta2 - delta2).SquareLen() > tolerance * tolerance)) { return 0; } return 1; } Vector2f delta1, delta2; Vector2f normal; bool isMerged; bool isNewlyCreated; int solverIndex; }; struct Manifold { Manifold() { body1Index = -1; body2Index = -1; pointCount = 0; pointIndex = 0; } Manifold(int body1Index, int body2Index, int pointIndex) { this->body1Index = body1Index; this->body2Index = body2Index; this->pointCount = 0; this->pointIndex = pointIndex; } int body1Index; int body2Index; int pointCount; int pointIndex; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/RigidBody.h
C/C++ Header
#pragma once #include "Vector2.h" #include "Coords2.h" #include "Geom.h" #ifdef _MSC_VER #define NOINLINE __declspec(noinline) #else #define NOINLINE __attribute__((noinline)) #endif struct RigidBody { RigidBody() {} RigidBody(Coords2f coords, Vector2f size, float density) { this->coords = coords; displacingVelocity = Vector2f(0.0f, 0.0f); displacingAngularVelocity = 0.0f; acceleration = Vector2f(0.0f, 0.0f); angularAcceleration = 0.0f; velocity = Vector2f(0.0f, 0.0f); angularVelocity = 0.0f; geom.size = size; float mass = density * (size.x * size.y); float inertia = mass * (size.x * size.x + size.y * size.y); invMass = 1.0f / mass; invInertia = 1.0f / inertia; UpdateGeom(); } void UpdateGeom() { geom.coords = coords; geom.RecomputeAABB(); } unsigned int index; Geom geom; Vector2f velocity, acceleration; Vector2f displacingVelocity; float angularVelocity, angularAcceleration; float displacingAngularVelocity; float invMass, invInertia; Coords2f coords; int lastIteration; int lastDisplacementIteration; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Solver.cpp
C++
#include "Solver.h" #include "base/Parallel.h" #include "base/SIMD.h" #include "Configuration.h" const float kProductiveImpulse = 1e-4f; const float kFrictionCoefficient = 0.3f; const int kIslandMinSize = 256; Solver::Solver() { } NOINLINE void Solver::SolveJoints(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration) { switch (configuration.solveMode) { case Configuration::Solve_AVX2: #ifdef __AVX2__ SolveJoints_AVX2(queue, bodies, bodiesCount, contactPoints, configuration); break; #endif case Configuration::Solve_SSE2: #ifdef __SSE2__ SolveJoints_SSE2(queue, bodies, bodiesCount, contactPoints, configuration); break; #endif case Configuration::Solve_Scalar: SolveJoints_Scalar(queue, bodies, bodiesCount, contactPoints, configuration); break; default: assert(!"Unknown solver mode"); break; } } NOINLINE void Solver::SolveJoints_Scalar(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration) { MICROPROFILE_SCOPEI("Physics", "SolveJoints_Scalar", -1); SolveJoints(queue, joint_packed1, bodies, bodiesCount, contactPoints, configuration); } #ifdef __SSE2__ NOINLINE void Solver::SolveJoints_SSE2(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration) { MICROPROFILE_SCOPEI("Physics", "SolveJoints_SSE2", -1); SolveJoints(queue, joint_packed4, bodies, bodiesCount, contactPoints, configuration); } #endif #ifdef __AVX2__ NOINLINE void Solver::SolveJoints_AVX2(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration) { MICROPROFILE_SCOPEI("Physics", "SolveJoints_AVX2", -1); SolveJoints(queue, joint_packed8, bodies, bodiesCount, contactPoints, configuration); } #endif template <int N> void Solver::SolveJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration) { PrepareBodies(bodies, bodiesCount); bool splitIslands = (configuration.islandMode == Configuration::Island_Multiple || configuration.islandMode == Configuration::Island_MultipleSloppy); if (splitIslands) { int jointCountAligned = GatherIslands(bodies, bodiesCount, N); joint_packed.resize(jointCountAligned); jointGroup_joints.resize(jointCountAligned); jointGroup_bodies.resize(bodiesCount); for (int i = 0; i < bodiesCount; ++i) jointGroup_bodies[i] = 0; parallelFor(queue, 0, islandCount, 1, [&](int islandIndex, int) { int jointsBegin = island_offset[islandIndex]; int jointsEnd = jointsBegin + island_size[islandIndex]; SolveJointIsland(queue, joint_packed, jointsBegin, jointsEnd, contactPoints, configuration); }); } else { int jointCount = contactJoints.size; joint_index.resize(jointCount); joint_packed.resize(jointCount); jointGroup_joints.resize(jointCount); jointGroup_bodies.resize(bodiesCount); for (int i = 0; i < jointCount; ++i) joint_index[i] = i; for (int i = 0; i < bodiesCount; ++i) jointGroup_bodies[i] = 0; islandCount = 1; islandMaxSize = jointCount; SolveJointIsland(queue, joint_packed, 0, jointCount, contactPoints, configuration); } FinishBodies(bodies, bodiesCount); MICROPROFILE_COUNTER_SET("physics/islands", islandCount); MICROPROFILE_COUNTER_SET("physics/bodies", bodiesCount); MICROPROFILE_COUNTER_SET("physics/joints", contactJoints.size); } static bool any(const AlignedArray<bool>& v) { for (int i = 0; i < v.size; ++i) if (v[i]) return true; return false; } template <int N> NOINLINE void Solver::SolveJointIsland(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd, ContactPoint* contactPoints, const Configuration& configuration) { MICROPROFILE_SCOPEI("Physics", "SolveJointIsland", -1); int groupOffset = PrepareJoints(queue, joint_packed, jointBegin, jointEnd, N); bool sloppy = (configuration.islandMode == Configuration::Island_SingleSloppy || configuration.islandMode == Configuration::Island_MultipleSloppy); int batchSize = sloppy ? 512 : jointEnd - jointBegin; int batchCount = ((jointEnd - jointBegin) + batchSize - 1) / batchSize; { MICROPROFILE_SCOPEI("Physics", "Prepare", -1); { MICROPROFILE_SCOPEI("Physics", "RefreshJoints", -1); parallelFor(queue, 0, batchCount, 1, [&](int batchIndex, int worker) { int batchBegin = jointBegin + batchIndex * batchSize; int batchEnd = std::min(batchBegin + batchSize, jointEnd); RefreshJoints<N>(joint_packed.data, batchBegin, std::min(groupOffset, batchEnd), contactPoints); RefreshJoints<1>(joint_packed.data, std::max(groupOffset, batchBegin), batchEnd, contactPoints); }); } { MICROPROFILE_SCOPEI("Physics", "PreStepJoints", -1); parallelFor(queue, 0, batchCount, 1, [&](int batchIndex, int worker) { int batchBegin = jointBegin + batchIndex * batchSize; int batchEnd = std::min(batchBegin + batchSize, jointEnd); PreStepJoints<N>(joint_packed.data, batchBegin, std::min(groupOffset, batchEnd)); PreStepJoints<1>(joint_packed.data, std::max(groupOffset, batchBegin), batchEnd); }); } } AlignedArray<bool> productivew; productivew.resize(queue.getWorkerCount() + 1); { MICROPROFILE_SCOPEI("Physics", "Impulse", -1); for (int iterationIndex = 0; iterationIndex < configuration.contactIterationsCount; iterationIndex++) { MICROPROFILE_SCOPEI("Physics", "ImpulseIteration", -1); memset(productivew.data, 0, productivew.size * sizeof(bool)); parallelFor(queue, 0, batchCount, 1, [&](int batchIndex, int worker) { int batchBegin = jointBegin + batchIndex * batchSize; int batchEnd = std::min(batchBegin + batchSize, jointEnd); productivew[worker] |= SolveJointsImpulses<N>(joint_packed.data, batchBegin, std::min(groupOffset, batchEnd), iterationIndex); productivew[worker] |= SolveJointsImpulses<1>(joint_packed.data, std::max(groupOffset, batchBegin), batchEnd, iterationIndex); }); if (!any(productivew)) break; } } { MICROPROFILE_SCOPEI("Physics", "Displacement", -1); for (int iterationIndex = 0; iterationIndex < configuration.penetrationIterationsCount; iterationIndex++) { MICROPROFILE_SCOPEI("Physics", "DisplacementIteration", -1); memset(productivew.data, 0, productivew.size * sizeof(bool)); parallelFor(queue, 0, batchCount, 1, [&](int batchIndex, int worker) { int batchBegin = jointBegin + batchIndex * batchSize; int batchEnd = std::min(batchBegin + batchSize, jointEnd); productivew[worker] |= SolveJointsDisplacement<N>(joint_packed.data, batchBegin, std::min(groupOffset, batchEnd), iterationIndex); productivew[worker] |= SolveJointsDisplacement<1>(joint_packed.data, std::max(groupOffset, batchBegin), batchEnd, iterationIndex); }); if (!any(productivew)) break; } } FinishJoints(queue, joint_packed, jointBegin, jointEnd); } NOINLINE int Solver::PrepareIndices(int jointBegin, int jointEnd, int groupSizeTarget) { MICROPROFILE_SCOPEI("Physics", "PrepareIndices", -1); if (groupSizeTarget == 1) return jointEnd; for (int i = jointBegin; i < jointEnd; ++i) jointGroup_joints[i] = joint_index[i]; int tag = 0; int remainingJoints = jointEnd - jointBegin; int groupOffset = jointBegin; while (remainingJoints >= groupSizeTarget) { // gather a group of N joints with non-overlapping bodies int groupSize = 0; tag++; for (int i = 0; i < remainingJoints && groupSize < groupSizeTarget;) { int jointIndex = jointGroup_joints[jointBegin + i]; ContactJoint& joint = contactJoints[jointIndex]; // TODO: race between static bodies from different islands if (jointGroup_bodies[joint.body1Index] < tag && jointGroup_bodies[joint.body2Index] < tag) { jointGroup_bodies[joint.body1Index] = tag; jointGroup_bodies[joint.body2Index] = tag; joint_index[groupOffset + groupSize] = jointIndex; groupSize++; jointGroup_joints[jointBegin + i] = jointGroup_joints[jointBegin + remainingJoints - 1]; remainingJoints--; } else { i++; } } groupOffset += groupSize; if (groupSize < groupSizeTarget) break; } // fill in the rest of the joints sequentially - they don't form a group so we'll have to solve them 1 by 1 for (int i = 0; i < remainingJoints; ++i) joint_index[groupOffset + i] = jointGroup_joints[jointBegin + i]; return groupOffset & ~(groupSizeTarget - 1); } static int remap(AlignedArray<int>& table, int index) { int result = index; while (result != table[result]) result = table[result]; return table[index] = result; } NOINLINE int Solver::GatherIslands(RigidBody* bodies, int bodiesCount, int groupSizeTarget) { MICROPROFILE_SCOPEI("Physics", "GatherIslands", -1); int jointCount = contactJoints.size; int jointCountAligned = jointCount; island_remap.resize(bodiesCount); island_index.resize(bodiesCount); island_indexremap.resize(bodiesCount); island_offset.resize(bodiesCount); island_offsettemp.resize(bodiesCount); island_size.resize(bodiesCount); { MICROPROFILE_SCOPEI("Physics", "Prepare", -1); for (int i = 0; i < bodiesCount; ++i) { island_remap[i] = (bodies[i].invMass == 0 && bodies[i].invInertia == 0) ? -1 : i; } } { MICROPROFILE_SCOPEI("Physics", "Merge", -1); for (ContactJoint& j: contactJoints) { int island1 = island_remap[j.body1Index]; int island2 = island_remap[j.body2Index]; if ((island1 | island2) < 0) continue; int remap1 = remap(island_remap, island1); int remap2 = remap(island_remap, island2); island_remap[remap1] = remap2; } } { MICROPROFILE_SCOPEI("Physics", "Gather", -1); islandCount = 0; for (int i = 0; i < bodiesCount; ++i) { island_index[i] = -1; } for (int i = 0; i < bodiesCount; ++i) { if (island_remap[i] < 0) continue; island_remap[i] = remap(island_remap, i); } for (int i = 0; i < bodiesCount; ++i) { if (island_remap[i] < 0) continue; int island = island_remap[i]; if (island_index[island] < 0) { island_index[island] = islandCount; islandCount++; } } } { MICROPROFILE_SCOPEI("Physics", "Count", -1); for (int i = 0; i < islandCount; ++i) { island_offset[i] = 0; } for (ContactJoint& j: contactJoints) { int island1 = island_remap[j.body1Index]; int island2 = island_remap[j.body2Index]; if ((island1 & island2) < 0) continue; assert(island1 == island2 || ((island1 | island2) < 0 && (island1 & island2) >= 0)); int island = island1 < 0 ? island2 : island1; island_offset[island_index[island]]++; } } { MICROPROFILE_SCOPEI("Physics", "Coalesce", -1); for (int i = 0; i < islandCount; ++i) { island_indexremap[i] = i; } int runningIndex = 0; int runningCount = 0; int totalCount = 0; for (int i = 0; i < islandCount; ++i) { runningCount += island_offset[i]; island_indexremap[i] = runningIndex; if (runningCount >= kIslandMinSize || (runningCount > 0 && i == islandCount - 1)) { int runningCountAligned = (runningCount + groupSizeTarget - 1) & ~(groupSizeTarget - 1); island_size[runningIndex] = runningCount; island_offset[runningIndex] = totalCount; totalCount += runningCountAligned; runningCount = 0; runningIndex++; } } jointCountAligned = totalCount; islandCount = runningIndex; } joint_index.resize(jointCountAligned); { MICROPROFILE_SCOPEI("Physics", "Index", -1); for (int i = 0; i < islandCount; ++i) { island_offsettemp[i] = island_offset[i]; } for (int jointIndex = 0; jointIndex < jointCount; ++jointIndex) { ContactJoint& j = contactJoints[jointIndex]; int island1 = island_remap[j.body1Index]; int island2 = island_remap[j.body2Index]; if ((island1 & island2) < 0) continue; assert(island1 == island2 || ((island1 | island2) < 0 && (island1 & island2) >= 0)); int island = island1 < 0 ? island2 : island1; joint_index[island_offsettemp[island_indexremap[island_index[island]]]++] = jointIndex; } islandMaxSize = 0; for (int i = 0; i < islandCount; ++i) { assert(island_offsettemp[i] == island_offset[i] + island_size[i]); islandMaxSize = std::max(islandMaxSize, island_size[i]); } } return jointCountAligned; } NOINLINE void Solver::PrepareBodies(RigidBody* bodies, int bodiesCount) { MICROPROFILE_SCOPEI("Physics", "PrepareBodies", -1); solveBodiesParams.resize(bodiesCount); solveBodiesImpulse.resize(bodiesCount); solveBodiesDisplacement.resize(bodiesCount); for (int i = 0; i < bodiesCount; ++i) { solveBodiesParams[i].invMass = bodies[i].invMass; solveBodiesParams[i].invInertia = bodies[i].invInertia; solveBodiesParams[i].coords_pos = bodies[i].coords.pos; solveBodiesParams[i].coords_xVector = bodies[i].coords.xVector; solveBodiesParams[i].coords_yVector = bodies[i].coords.yVector; solveBodiesImpulse[i].velocity = bodies[i].velocity; solveBodiesImpulse[i].angularVelocity = bodies[i].angularVelocity; solveBodiesImpulse[i].lastIteration = -1; solveBodiesDisplacement[i].velocity = bodies[i].displacingVelocity; solveBodiesDisplacement[i].angularVelocity = bodies[i].displacingAngularVelocity; solveBodiesDisplacement[i].lastIteration = -1; } } NOINLINE void Solver::FinishBodies(RigidBody* bodies, int bodiesCount) { MICROPROFILE_SCOPEI("Physics", "FinishBodies", -1); for (int i = 0; i < bodiesCount; ++i) { bodies[i].velocity = solveBodiesImpulse[i].velocity; bodies[i].angularVelocity = solveBodiesImpulse[i].angularVelocity; bodies[i].displacingVelocity = solveBodiesDisplacement[i].velocity; bodies[i].displacingAngularVelocity = solveBodiesDisplacement[i].angularVelocity; } } template <int N> NOINLINE int Solver::PrepareJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd, int groupSizeTarget) { MICROPROFILE_SCOPEI("Physics", "PrepareJoints", -1); assert(jointBegin % groupSizeTarget == 0); assert(jointBegin % N == 0); int groupOffset = PrepareIndices(jointBegin, jointEnd, groupSizeTarget); { MICROPROFILE_SCOPEI("Physics", "CopyJoints", -1); parallelFor(queue, 0, jointEnd - jointBegin, 128, [&](int i, int) { ContactJoint& joint = contactJoints[joint_index[jointBegin + i]]; ContactJointPacked<N>& jointP = joint_packed[unsigned(jointBegin + i) / N]; int iP = i & (N - 1); jointP.body1Index[iP] = joint.body1Index; jointP.body2Index[iP] = joint.body2Index; jointP.contactPointIndex[iP] = joint.contactPointIndex; jointP.normalLimiter_accumulatedImpulse[iP] = joint.normalLimiter_accumulatedImpulse; jointP.frictionLimiter_accumulatedImpulse[iP] = joint.frictionLimiter_accumulatedImpulse; }); } return groupOffset; } template <int N> NOINLINE void Solver::FinishJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd) { MICROPROFILE_SCOPEI("Physics", "FinishJoints", -1); assert(jointBegin % N == 0); { MICROPROFILE_SCOPEI("Physics", "CopyJoints", -1); parallelFor(queue, 0, jointEnd - jointBegin, 128, [&](int i, int) { ContactJoint& joint = contactJoints[joint_index[jointBegin + i]]; ContactJointPacked<N>& jointP = joint_packed[unsigned(jointBegin + i) / N]; int iP = i & (N - 1); joint.normalLimiter_accumulatedImpulse = jointP.normalLimiter_accumulatedImpulse[iP]; joint.frictionLimiter_accumulatedImpulse = jointP.frictionLimiter_accumulatedImpulse[iP]; }); } } template <typename Vf, int N> static void RefreshLimiter( ContactLimiterPacked<N>& limiter, int iP, const Vf& n1X, const Vf& n1Y, const Vf& n2X, const Vf& n2Y, const Vf& w1X, const Vf& w1Y, const Vf& w2X, const Vf& w2Y, const Vf& body1_invMass, const Vf& body1_invInertia, const Vf& body2_invMass, const Vf& body2_invInertia) { Vf normalProjector1X = n1X; Vf normalProjector1Y = n1Y; Vf normalProjector2X = n2X; Vf normalProjector2Y = n2Y; Vf angularProjector1 = n1X * w1Y - n1Y * w1X; Vf angularProjector2 = n2X * w2Y - n2Y * w2X; Vf compMass1_linearX = normalProjector1X * body1_invMass; Vf compMass1_linearY = normalProjector1Y * body1_invMass; Vf compMass1_angular = angularProjector1 * body1_invInertia; Vf compMass2_linearX = normalProjector2X * body2_invMass; Vf compMass2_linearY = normalProjector2Y * body2_invMass; Vf compMass2_angular = angularProjector2 * body2_invInertia; Vf compMass1 = normalProjector1X * compMass1_linearX + normalProjector1Y * compMass1_linearY + angularProjector1 * compMass1_angular; Vf compMass2 = normalProjector2X * compMass2_linearX + normalProjector2Y * compMass2_linearY + angularProjector2 * compMass2_angular; Vf compMass = compMass1 + compMass2; Vf compInvMass = select(Vf::zero(), Vf::one(1) / compMass, abs(compMass) > Vf::zero()); store(normalProjector1X, &limiter.normalProjector1X[iP]); store(normalProjector1Y, &limiter.normalProjector1Y[iP]); store(normalProjector2X, &limiter.normalProjector2X[iP]); store(normalProjector2Y, &limiter.normalProjector2Y[iP]); store(angularProjector1, &limiter.angularProjector1[iP]); store(angularProjector2, &limiter.angularProjector2[iP]); store(compMass1_linearX, &limiter.compMass1_linearX[iP]); store(compMass1_linearY, &limiter.compMass1_linearY[iP]); store(compMass2_linearX, &limiter.compMass2_linearX[iP]); store(compMass2_linearY, &limiter.compMass2_linearY[iP]); store(compMass1_angular, &limiter.compMass1_angular[iP]); store(compMass2_angular, &limiter.compMass2_angular[iP]); store(compInvMass, &limiter.compInvMass[iP]); } template <int VN, int N> NOINLINE void Solver::RefreshJoints(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, ContactPoint* contactPoints) { typedef simd::VNf<VN> Vf; assert(jointBegin % VN == 0 && jointEnd % VN == 0); for (int jointIndex = jointBegin; jointIndex < jointEnd; jointIndex += VN) { int i = jointIndex; ContactJointPacked<N>& jointP = joint_packed[unsigned(i) / N]; int iP = (VN == N) ? 0 : i & (N - 1); Vf body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf; Vf body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf; Vf body1_invMass, body1_invInertia, body1_coords_posX, body1_coords_posY; Vf body1_coords_xVectorX, body1_coords_xVectorY, body1_coords_yVectorX, body1_coords_yVectorY; Vf body2_invMass, body2_invInertia, body2_coords_posX, body2_coords_posY; Vf body2_coords_xVectorX, body2_coords_xVectorY, body2_coords_yVectorX, body2_coords_yVectorY; Vf collision_delta1X, collision_delta1Y, collision_delta2X, collision_delta2Y; Vf collision_normalX, collision_normalY; Vf dummy; loadindexed4( body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesImpulse.data, jointP.body1Index + iP, sizeof(SolveBody)); loadindexed4( body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesImpulse.data, jointP.body2Index + iP, sizeof(SolveBody)); loadindexed8( body1_invMass, body1_invInertia, body1_coords_posX, body1_coords_posY, body1_coords_xVectorX, body1_coords_xVectorY, body1_coords_yVectorX, body1_coords_yVectorY, solveBodiesParams.data, jointP.body1Index + iP, sizeof(SolveBodyParams)); loadindexed8( body2_invMass, body2_invInertia, body2_coords_posX, body2_coords_posY, body2_coords_xVectorX, body2_coords_xVectorY, body2_coords_yVectorX, body2_coords_yVectorY, solveBodiesParams.data, jointP.body2Index + iP, sizeof(SolveBodyParams)); loadindexed8( collision_delta1X, collision_delta1Y, collision_delta2X, collision_delta2Y, collision_normalX, collision_normalY, dummy, dummy, contactPoints, jointP.contactPointIndex + iP, sizeof(ContactPoint)); Vf point1X = collision_delta1X + body1_coords_posX; Vf point1Y = collision_delta1Y + body1_coords_posY; Vf point2X = collision_delta2X + body2_coords_posX; Vf point2Y = collision_delta2Y + body2_coords_posY; Vf w1X = collision_delta1X; Vf w1Y = collision_delta1Y; Vf w2X = point1X - body2_coords_posX; Vf w2Y = point1Y - body2_coords_posY; // Normal limiter RefreshLimiter(jointP.normalLimiter, iP, collision_normalX, collision_normalY, -collision_normalX, -collision_normalY, w1X, w1Y, w2X, w2Y, body1_invMass, body1_invInertia, body2_invMass, body2_invInertia); Vf bounce = Vf::zero(); Vf deltaVelocity = Vf::one(1.f); Vf maxPenetrationVelocity = Vf::one(0.1f); Vf deltaDepth = Vf::one(1.f); Vf errorReduction = Vf::one(0.1f); Vf pointVelocity_body1X = (body1_coords_posY - point1Y) * body1_angularVelocity + body1_velocityX; Vf pointVelocity_body1Y = (point1X - body1_coords_posX) * body1_angularVelocity + body1_velocityY; Vf pointVelocity_body2X = (body2_coords_posY - point2Y) * body2_angularVelocity + body2_velocityX; Vf pointVelocity_body2Y = (point2X - body2_coords_posX) * body2_angularVelocity + body2_velocityY; Vf relativeVelocityX = pointVelocity_body1X - pointVelocity_body2X; Vf relativeVelocityY = pointVelocity_body1Y - pointVelocity_body2Y; Vf dv = -bounce * (relativeVelocityX * collision_normalX + relativeVelocityY * collision_normalY); Vf depth = (point2X - point1X) * collision_normalX + (point2Y - point1Y) * collision_normalY; Vf dstVelocity = max(dv - deltaVelocity, Vf::zero()); Vf j_normalLimiter_dstVelocity = select(dstVelocity, dstVelocity - maxPenetrationVelocity, depth < deltaDepth); Vf j_normalLimiter_dstDisplacingVelocity = errorReduction * max(Vf::zero(), depth - Vf::one(2.0f) * deltaDepth); Vf j_normalLimiter_accumulatedDisplacingImpulse = Vf::zero(); // Friction limiter Vf tangentX = -collision_normalY; Vf tangentY = collision_normalX; RefreshLimiter(jointP.frictionLimiter, iP, tangentX, tangentY, -tangentX, -tangentY, w1X, w1Y, w2X, w2Y, body1_invMass, body1_invInertia, body2_invMass, body2_invInertia); store(j_normalLimiter_dstVelocity, &jointP.normalLimiter_dstVelocity[iP]); store(j_normalLimiter_dstDisplacingVelocity, &jointP.normalLimiter_dstDisplacingVelocity[iP]); store(j_normalLimiter_accumulatedDisplacingImpulse, &jointP.normalLimiter_accumulatedDisplacingImpulse[iP]); } } template <int VN, int N> NOINLINE void Solver::PreStepJoints(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd) { typedef simd::VNf<VN> Vf; assert(jointBegin % VN == 0 && jointEnd % VN == 0); for (int jointIndex = jointBegin; jointIndex < jointEnd; jointIndex += VN) { int i = jointIndex; ContactJointPacked<N>& jointP = joint_packed[unsigned(i) / N]; int iP = (VN == N) ? 0 : i & (N - 1); Vf body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf; Vf body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf; loadindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesImpulse.data, jointP.body1Index + iP, sizeof(SolveBody)); loadindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesImpulse.data, jointP.body2Index + iP, sizeof(SolveBody)); Vf j_normalLimiter_compMass1_linearX = Vf::load(&jointP.normalLimiter.compMass1_linearX[iP]); Vf j_normalLimiter_compMass1_linearY = Vf::load(&jointP.normalLimiter.compMass1_linearY[iP]); Vf j_normalLimiter_compMass2_linearX = Vf::load(&jointP.normalLimiter.compMass2_linearX[iP]); Vf j_normalLimiter_compMass2_linearY = Vf::load(&jointP.normalLimiter.compMass2_linearY[iP]); Vf j_normalLimiter_compMass1_angular = Vf::load(&jointP.normalLimiter.compMass1_angular[iP]); Vf j_normalLimiter_compMass2_angular = Vf::load(&jointP.normalLimiter.compMass2_angular[iP]); Vf j_normalLimiter_accumulatedImpulse = Vf::load(&jointP.normalLimiter_accumulatedImpulse[iP]); Vf j_frictionLimiter_compMass1_linearX = Vf::load(&jointP.frictionLimiter.compMass1_linearX[iP]); Vf j_frictionLimiter_compMass1_linearY = Vf::load(&jointP.frictionLimiter.compMass1_linearY[iP]); Vf j_frictionLimiter_compMass2_linearX = Vf::load(&jointP.frictionLimiter.compMass2_linearX[iP]); Vf j_frictionLimiter_compMass2_linearY = Vf::load(&jointP.frictionLimiter.compMass2_linearY[iP]); Vf j_frictionLimiter_compMass1_angular = Vf::load(&jointP.frictionLimiter.compMass1_angular[iP]); Vf j_frictionLimiter_compMass2_angular = Vf::load(&jointP.frictionLimiter.compMass2_angular[iP]); Vf j_frictionLimiter_accumulatedImpulse = Vf::load(&jointP.frictionLimiter_accumulatedImpulse[iP]); body1_velocityX += j_normalLimiter_compMass1_linearX * j_normalLimiter_accumulatedImpulse; body1_velocityY += j_normalLimiter_compMass1_linearY * j_normalLimiter_accumulatedImpulse; body1_angularVelocity += j_normalLimiter_compMass1_angular * j_normalLimiter_accumulatedImpulse; body2_velocityX += j_normalLimiter_compMass2_linearX * j_normalLimiter_accumulatedImpulse; body2_velocityY += j_normalLimiter_compMass2_linearY * j_normalLimiter_accumulatedImpulse; body2_angularVelocity += j_normalLimiter_compMass2_angular * j_normalLimiter_accumulatedImpulse; body1_velocityX += j_frictionLimiter_compMass1_linearX * j_frictionLimiter_accumulatedImpulse; body1_velocityY += j_frictionLimiter_compMass1_linearY * j_frictionLimiter_accumulatedImpulse; body1_angularVelocity += j_frictionLimiter_compMass1_angular * j_frictionLimiter_accumulatedImpulse; body2_velocityX += j_frictionLimiter_compMass2_linearX * j_frictionLimiter_accumulatedImpulse; body2_velocityY += j_frictionLimiter_compMass2_linearY * j_frictionLimiter_accumulatedImpulse; body2_angularVelocity += j_frictionLimiter_compMass2_angular * j_frictionLimiter_accumulatedImpulse; storeindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesImpulse.data, jointP.body1Index + iP, sizeof(SolveBody)); storeindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesImpulse.data, jointP.body2Index + iP, sizeof(SolveBody)); } } template <int VN, int N> NOINLINE bool Solver::SolveJointsImpulses(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, int iterationIndex) { typedef simd::VNf<VN> Vf; typedef simd::VNi<VN> Vi; typedef simd::VNb<VN> Vb; assert(jointBegin % VN == 0 && jointEnd % VN == 0); Vi iterationIndex0 = Vi::one(iterationIndex); Vi iterationIndex2 = Vi::one(iterationIndex - 2); Vb productive_any = Vb::zero(); for (int jointIndex = jointBegin; jointIndex < jointEnd; jointIndex += VN) { int i = jointIndex; ContactJointPacked<N>& jointP = joint_packed[unsigned(i) / N]; int iP = (VN == N) ? 0 : i & (N - 1); Vf body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf; Vf body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf; loadindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesImpulse.data, jointP.body1Index + iP, sizeof(SolveBody)); loadindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesImpulse.data, jointP.body2Index + iP, sizeof(SolveBody)); Vi body1_lastIteration = bitcast(body1_lastIterationf); Vi body2_lastIteration = bitcast(body2_lastIterationf); Vb body1_productive = body1_lastIteration > iterationIndex2; Vb body2_productive = body2_lastIteration > iterationIndex2; Vb body_productive = body1_productive | body2_productive; if (none(body_productive)) continue; Vf j_normalLimiter_normalProjector1X = Vf::load(&jointP.normalLimiter.normalProjector1X[iP]); Vf j_normalLimiter_normalProjector1Y = Vf::load(&jointP.normalLimiter.normalProjector1Y[iP]); Vf j_normalLimiter_normalProjector2X = Vf::load(&jointP.normalLimiter.normalProjector2X[iP]); Vf j_normalLimiter_normalProjector2Y = Vf::load(&jointP.normalLimiter.normalProjector2Y[iP]); Vf j_normalLimiter_angularProjector1 = Vf::load(&jointP.normalLimiter.angularProjector1[iP]); Vf j_normalLimiter_angularProjector2 = Vf::load(&jointP.normalLimiter.angularProjector2[iP]); Vf j_normalLimiter_compMass1_linearX = Vf::load(&jointP.normalLimiter.compMass1_linearX[iP]); Vf j_normalLimiter_compMass1_linearY = Vf::load(&jointP.normalLimiter.compMass1_linearY[iP]); Vf j_normalLimiter_compMass2_linearX = Vf::load(&jointP.normalLimiter.compMass2_linearX[iP]); Vf j_normalLimiter_compMass2_linearY = Vf::load(&jointP.normalLimiter.compMass2_linearY[iP]); Vf j_normalLimiter_compMass1_angular = Vf::load(&jointP.normalLimiter.compMass1_angular[iP]); Vf j_normalLimiter_compMass2_angular = Vf::load(&jointP.normalLimiter.compMass2_angular[iP]); Vf j_normalLimiter_compInvMass = Vf::load(&jointP.normalLimiter.compInvMass[iP]); Vf j_normalLimiter_accumulatedImpulse = Vf::load(&jointP.normalLimiter_accumulatedImpulse[iP]); Vf j_normalLimiter_dstVelocity = Vf::load(&jointP.normalLimiter_dstVelocity[iP]); Vf j_frictionLimiter_normalProjector1X = Vf::load(&jointP.frictionLimiter.normalProjector1X[iP]); Vf j_frictionLimiter_normalProjector1Y = Vf::load(&jointP.frictionLimiter.normalProjector1Y[iP]); Vf j_frictionLimiter_normalProjector2X = Vf::load(&jointP.frictionLimiter.normalProjector2X[iP]); Vf j_frictionLimiter_normalProjector2Y = Vf::load(&jointP.frictionLimiter.normalProjector2Y[iP]); Vf j_frictionLimiter_angularProjector1 = Vf::load(&jointP.frictionLimiter.angularProjector1[iP]); Vf j_frictionLimiter_angularProjector2 = Vf::load(&jointP.frictionLimiter.angularProjector2[iP]); Vf j_frictionLimiter_compMass1_linearX = Vf::load(&jointP.frictionLimiter.compMass1_linearX[iP]); Vf j_frictionLimiter_compMass1_linearY = Vf::load(&jointP.frictionLimiter.compMass1_linearY[iP]); Vf j_frictionLimiter_compMass2_linearX = Vf::load(&jointP.frictionLimiter.compMass2_linearX[iP]); Vf j_frictionLimiter_compMass2_linearY = Vf::load(&jointP.frictionLimiter.compMass2_linearY[iP]); Vf j_frictionLimiter_compMass1_angular = Vf::load(&jointP.frictionLimiter.compMass1_angular[iP]); Vf j_frictionLimiter_compMass2_angular = Vf::load(&jointP.frictionLimiter.compMass2_angular[iP]); Vf j_frictionLimiter_compInvMass = Vf::load(&jointP.frictionLimiter.compInvMass[iP]); Vf j_frictionLimiter_accumulatedImpulse = Vf::load(&jointP.frictionLimiter_accumulatedImpulse[iP]); Vf normaldV = j_normalLimiter_dstVelocity; normaldV -= j_normalLimiter_normalProjector1X * body1_velocityX; normaldV -= j_normalLimiter_normalProjector1Y * body1_velocityY; normaldV -= j_normalLimiter_angularProjector1 * body1_angularVelocity; normaldV -= j_normalLimiter_normalProjector2X * body2_velocityX; normaldV -= j_normalLimiter_normalProjector2Y * body2_velocityY; normaldV -= j_normalLimiter_angularProjector2 * body2_angularVelocity; Vf normalDeltaImpulse = normaldV * j_normalLimiter_compInvMass; normalDeltaImpulse = max(normalDeltaImpulse, -j_normalLimiter_accumulatedImpulse); body1_velocityX += j_normalLimiter_compMass1_linearX * normalDeltaImpulse; body1_velocityY += j_normalLimiter_compMass1_linearY * normalDeltaImpulse; body1_angularVelocity += j_normalLimiter_compMass1_angular * normalDeltaImpulse; body2_velocityX += j_normalLimiter_compMass2_linearX * normalDeltaImpulse; body2_velocityY += j_normalLimiter_compMass2_linearY * normalDeltaImpulse; body2_angularVelocity += j_normalLimiter_compMass2_angular * normalDeltaImpulse; j_normalLimiter_accumulatedImpulse += normalDeltaImpulse; Vf frictiondV = Vf::zero(); frictiondV -= j_frictionLimiter_normalProjector1X * body1_velocityX; frictiondV -= j_frictionLimiter_normalProjector1Y * body1_velocityY; frictiondV -= j_frictionLimiter_angularProjector1 * body1_angularVelocity; frictiondV -= j_frictionLimiter_normalProjector2X * body2_velocityX; frictiondV -= j_frictionLimiter_normalProjector2Y * body2_velocityY; frictiondV -= j_frictionLimiter_angularProjector2 * body2_angularVelocity; Vf frictionDeltaImpulse = frictiondV * j_frictionLimiter_compInvMass; Vf reactionForce = j_normalLimiter_accumulatedImpulse; Vf accumulatedImpulse = j_frictionLimiter_accumulatedImpulse; Vf frictionForce = accumulatedImpulse + frictionDeltaImpulse; Vf reactionForceScaled = reactionForce * Vf::one(kFrictionCoefficient); Vf frictionForceAbs = abs(frictionForce); Vf reactionForceScaledSigned = flipsign(reactionForceScaled, frictionForce); Vf frictionDeltaImpulseAdjusted = reactionForceScaledSigned - accumulatedImpulse; frictionDeltaImpulse = select(frictionDeltaImpulse, frictionDeltaImpulseAdjusted, frictionForceAbs > reactionForceScaled); j_frictionLimiter_accumulatedImpulse += frictionDeltaImpulse; body1_velocityX += j_frictionLimiter_compMass1_linearX * frictionDeltaImpulse; body1_velocityY += j_frictionLimiter_compMass1_linearY * frictionDeltaImpulse; body1_angularVelocity += j_frictionLimiter_compMass1_angular * frictionDeltaImpulse; body2_velocityX += j_frictionLimiter_compMass2_linearX * frictionDeltaImpulse; body2_velocityY += j_frictionLimiter_compMass2_linearY * frictionDeltaImpulse; body2_angularVelocity += j_frictionLimiter_compMass2_angular * frictionDeltaImpulse; store(j_normalLimiter_accumulatedImpulse, &jointP.normalLimiter_accumulatedImpulse[iP]); store(j_frictionLimiter_accumulatedImpulse, &jointP.frictionLimiter_accumulatedImpulse[iP]); Vf cumulativeImpulse = max(abs(normalDeltaImpulse), abs(frictionDeltaImpulse)); Vb productive = cumulativeImpulse > Vf::one(kProductiveImpulse); productive_any |= productive; body1_lastIteration = select(body1_lastIteration, iterationIndex0, productive); body2_lastIteration = select(body2_lastIteration, iterationIndex0, productive); body1_lastIterationf = bitcast(body1_lastIteration); body2_lastIterationf = bitcast(body2_lastIteration); storeindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesImpulse.data, jointP.body1Index + iP, sizeof(SolveBody)); storeindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesImpulse.data, jointP.body2Index + iP, sizeof(SolveBody)); } return any(productive_any); } template <int VN, int N> NOINLINE bool Solver::SolveJointsDisplacement(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, int iterationIndex) { typedef simd::VNf<VN> Vf; typedef simd::VNi<VN> Vi; typedef simd::VNb<VN> Vb; assert(jointBegin % VN == 0 && jointEnd % VN == 0); Vi iterationIndex0 = Vi::one(iterationIndex); Vi iterationIndex2 = Vi::one(iterationIndex - 2); Vb productive_any = Vb::zero(); for (int jointIndex = jointBegin; jointIndex < jointEnd; jointIndex += VN) { int i = jointIndex; ContactJointPacked<N>& jointP = joint_packed[unsigned(i) / N]; int iP = (VN == N) ? 0 : i & (N - 1); Vf body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf; Vf body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf; loadindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesDisplacement.data, jointP.body1Index + iP, sizeof(SolveBody)); loadindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesDisplacement.data, jointP.body2Index + iP, sizeof(SolveBody)); Vi body1_lastIteration = bitcast(body1_lastIterationf); Vi body2_lastIteration = bitcast(body2_lastIterationf); Vb body1_productive = body1_lastIteration > iterationIndex2; Vb body2_productive = body2_lastIteration > iterationIndex2; Vb body_productive = body1_productive | body2_productive; if (none(body_productive)) continue; Vf j_normalLimiter_normalProjector1X = Vf::load(&jointP.normalLimiter.normalProjector1X[iP]); Vf j_normalLimiter_normalProjector1Y = Vf::load(&jointP.normalLimiter.normalProjector1Y[iP]); Vf j_normalLimiter_normalProjector2X = Vf::load(&jointP.normalLimiter.normalProjector2X[iP]); Vf j_normalLimiter_normalProjector2Y = Vf::load(&jointP.normalLimiter.normalProjector2Y[iP]); Vf j_normalLimiter_angularProjector1 = Vf::load(&jointP.normalLimiter.angularProjector1[iP]); Vf j_normalLimiter_angularProjector2 = Vf::load(&jointP.normalLimiter.angularProjector2[iP]); Vf j_normalLimiter_compMass1_linearX = Vf::load(&jointP.normalLimiter.compMass1_linearX[iP]); Vf j_normalLimiter_compMass1_linearY = Vf::load(&jointP.normalLimiter.compMass1_linearY[iP]); Vf j_normalLimiter_compMass2_linearX = Vf::load(&jointP.normalLimiter.compMass2_linearX[iP]); Vf j_normalLimiter_compMass2_linearY = Vf::load(&jointP.normalLimiter.compMass2_linearY[iP]); Vf j_normalLimiter_compMass1_angular = Vf::load(&jointP.normalLimiter.compMass1_angular[iP]); Vf j_normalLimiter_compMass2_angular = Vf::load(&jointP.normalLimiter.compMass2_angular[iP]); Vf j_normalLimiter_compInvMass = Vf::load(&jointP.normalLimiter.compInvMass[iP]); Vf j_normalLimiter_dstDisplacingVelocity = Vf::load(&jointP.normalLimiter_dstDisplacingVelocity[iP]); Vf j_normalLimiter_accumulatedDisplacingImpulse = Vf::load(&jointP.normalLimiter_accumulatedDisplacingImpulse[iP]); Vf dV = j_normalLimiter_dstDisplacingVelocity; dV -= j_normalLimiter_normalProjector1X * body1_velocityX; dV -= j_normalLimiter_normalProjector1Y * body1_velocityY; dV -= j_normalLimiter_angularProjector1 * body1_angularVelocity; dV -= j_normalLimiter_normalProjector2X * body2_velocityX; dV -= j_normalLimiter_normalProjector2Y * body2_velocityY; dV -= j_normalLimiter_angularProjector2 * body2_angularVelocity; Vf displacingDeltaImpulse = dV * j_normalLimiter_compInvMass; displacingDeltaImpulse = max(displacingDeltaImpulse, -j_normalLimiter_accumulatedDisplacingImpulse); body1_velocityX += j_normalLimiter_compMass1_linearX * displacingDeltaImpulse; body1_velocityY += j_normalLimiter_compMass1_linearY * displacingDeltaImpulse; body1_angularVelocity += j_normalLimiter_compMass1_angular * displacingDeltaImpulse; body2_velocityX += j_normalLimiter_compMass2_linearX * displacingDeltaImpulse; body2_velocityY += j_normalLimiter_compMass2_linearY * displacingDeltaImpulse; body2_angularVelocity += j_normalLimiter_compMass2_angular * displacingDeltaImpulse; j_normalLimiter_accumulatedDisplacingImpulse += displacingDeltaImpulse; store(j_normalLimiter_accumulatedDisplacingImpulse, &jointP.normalLimiter_accumulatedDisplacingImpulse[iP]); Vb productive = abs(displacingDeltaImpulse) > Vf::one(kProductiveImpulse); productive_any |= productive; body1_lastIteration = select(body1_lastIteration, iterationIndex0, productive); body2_lastIteration = select(body2_lastIteration, iterationIndex0, productive); // this is a bit painful :( body1_lastIterationf = bitcast(body1_lastIteration); body2_lastIterationf = bitcast(body2_lastIteration); storeindexed4(body1_velocityX, body1_velocityY, body1_angularVelocity, body1_lastIterationf, solveBodiesDisplacement.data, jointP.body1Index + iP, sizeof(SolveBody)); storeindexed4(body2_velocityX, body2_velocityY, body2_angularVelocity, body2_lastIterationf, solveBodiesDisplacement.data, jointP.body2Index + iP, sizeof(SolveBody)); } return any(productive_any); }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Solver.h
C/C++ Header
#include "Joints.h" #include <assert.h> #include <vector> #include "base/AlignedArray.h" template <int N> struct ContactLimiterPacked { float normalProjector1X[N]; float normalProjector1Y[N]; float normalProjector2X[N]; float normalProjector2Y[N]; float angularProjector1[N]; float angularProjector2[N]; float compMass1_linearX[N]; float compMass1_linearY[N]; float compMass2_linearX[N]; float compMass2_linearY[N]; float compMass1_angular[N]; float compMass2_angular[N]; float compInvMass[N]; }; template <int N> struct ContactJointPacked { int body1Index[N]; int body2Index[N]; int contactPointIndex[N]; ContactLimiterPacked<N> normalLimiter; float normalLimiter_compInvMass[N]; float normalLimiter_accumulatedImpulse[N]; float normalLimiter_dstVelocity[N]; float normalLimiter_dstDisplacingVelocity[N]; float normalLimiter_accumulatedDisplacingImpulse[N]; ContactLimiterPacked<N> frictionLimiter; float frictionLimiter_accumulatedImpulse[N]; }; class WorkQueue; struct Configuration; struct Solver { Solver(); void SolveJoints(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration); void SolveJoints_Scalar(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration); void SolveJoints_SSE2(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration); void SolveJoints_AVX2(WorkQueue& queue, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration); template <int N> void SolveJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, RigidBody* bodies, int bodiesCount, ContactPoint* contactPoints, const Configuration& configuration); int GatherIslands(RigidBody* bodies, int bodiesCount, int groupSizeTarget); void PrepareBodies(RigidBody* bodies, int bodiesCount); void FinishBodies(RigidBody* bodies, int bodiesCount); template <int N> void SolveJointIsland(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd, ContactPoint* contactPoints, const Configuration& configuration); template <int N> int PrepareJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd, int groupSizeTarget); template <int N> void FinishJoints(WorkQueue& queue, AlignedArray<ContactJointPacked<N>>& joint_packed, int jointBegin, int jointEnd); int PrepareIndices(int jointBegin, int jointEnd, int groupSizeTarget); template <int VN, int N> void RefreshJoints(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, ContactPoint* contactPoints); template <int VN, int N> void PreStepJoints(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd); template <int VN, int N> bool SolveJointsImpulses(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, int iterationIndex); template <int VN, int N> bool SolveJointsDisplacement(ContactJointPacked<N>* joint_packed, int jointBegin, int jointEnd, int iterationIndex); struct SolveBodyParams { float invMass; float invInertia; Vector2f coords_pos; Vector2f coords_xVector; Vector2f coords_yVector; }; struct SolveBody { Vector2f velocity; float angularVelocity; int lastIteration; }; int islandCount; int islandMaxSize; AlignedArray<SolveBodyParams> solveBodiesParams; AlignedArray<SolveBody> solveBodiesImpulse; AlignedArray<SolveBody> solveBodiesDisplacement; AlignedArray<ContactJoint> contactJoints; AlignedArray<int> jointGroup_bodies; AlignedArray<int> jointGroup_joints; AlignedArray<int> joint_index; AlignedArray<int> island_remap; AlignedArray<int> island_index; AlignedArray<int> island_indexremap; AlignedArray<int> island_offset; AlignedArray<int> island_offsettemp; AlignedArray<int> island_size; AlignedArray<ContactJointPacked<1>> joint_packed1; AlignedArray<ContactJointPacked<4>> joint_packed4; AlignedArray<ContactJointPacked<8>> joint_packed8; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/Vector2.h
C/C++ Header
#pragma once #include <limits> #include <cmath> template <typename T> struct Vector2 { T x, y; T& operator[](const int i) { return *(&(x) + i); } inline Vector2<T>() {} //inline Vector3d(const Vector3d & rhs) { *this = rhs; } inline Vector2<T>(const T& _x, const T& _y) : x(_x) , y(_y) { } inline T Len() const { return sqrt(x * x + y * y); } inline T SquareLen() const { return x * x + y * y; } inline void Normalize() //Normalize itself { T l = sqrtf(x * x + y * y); if (fabs(l) > T(1e-8)) { T k = T(1.0) / l; x *= k; y *= k; } } inline void Invert() { x = -x; y = -y; } void Rotate(const T angle) { Vector2 self = *this; Vector2 x = self; Vector2 y = Vector2(-x.y, x.x); Vector2 delta = x * cos(angle) + y * sin(angle) - x; self += delta; *this = self; } inline Vector2<T> GetNorm() const { T l = sqrt(x * x + y * y); if (fabs(l) > T(1e-8)) { T k = T(1.0) / l; return Vector2<T>(x * k, y * k); } else { return Vector2<T>(0, 0); } } inline Vector2<T> operator-() const { return Vector2<T>(-x, -y); } void Decrease(T val) { if (SquareLen() > val * val) { T len = Len(); T scale = (len - val) / len; x *= scale; y *= scale; } else { x = 0.0f; y = 0.0f; } } inline Vector2<T>& operator*=(const T& val) { x *= val; y *= val; return *this; } inline Vector2<T>& operator/=(const T& val) { T inv = T(1.0) / val; x *= inv; y *= inv; return *this; } inline Vector2<T>& operator+=(const Vector2<T>& vec) { x += vec.x; y += vec.y; return *this; } inline Vector2<T>& operator-=(const Vector2<T>& vec) { x -= vec.x; y -= vec.y; return *this; } inline Vector2<T>& operator--() { x = -x; y = -y; return *this; } inline Vector2<T> operator+(const Vector2<T>& vec) const { return Vector2<T>(x + vec.x, y + vec.y); } inline Vector2<T> operator-(const Vector2<T>& vec) const { return Vector2<T>(x - vec.x, y - vec.y); } inline T operator*(const Vector2<T>& vec) const { return x * vec.x + y * vec.y; } inline Vector2<T> operator*(const T& val) const { return Vector2<T>(x * val, y * val); } Vector2<T> GetPerpendicular() const { return Vector2<T>(-y, x); } template <typename SomeVector> inline const Vector2<T> operator=(const SomeVector& v) { x = v.x; y = v.y; return *this; } static const Vector2<T> zeroVector() { return Vector2<T>(0, 0); } static const Vector2<T> zero() { return zeroVector(); } static const Vector2<T> one() { return Vector2<T>(T(1.0), T(1.0)); } static const Vector2<T> xAxis() { return Vector2<T>(T(1.0), 0); } static const Vector2<T> yAxis() { return Vector2<T>(0, T(1.0)); } }; template <typename T> inline Vector2<T> operator*(const T& d, const Vector2<T>& V) { return Vector2<T>(V.x * d, V.y * d); } template <typename T> inline Vector2<T> operator/(const Vector2<T>& V, const T& d) { T invd = T(1.0) / d; return Vector2<T>(V.x * invd, V.y * invd); } template <typename T> inline T operator^(const Vector2<T>& v1, const Vector2<T>& v2) { return v1.x * v2.y - v1.y * v2.x; } typedef Vector2<float> Vector2f; typedef Vector2<double> Vector2d; const static Vector2f zeroVector2f = Vector2f(0, 0); const static Vector2f xAxis2f = Vector2f(1, 0); const static Vector2f yAxis2f = Vector2f(0, 1); const static Vector2d zeroVector2d = Vector2d(0, 0); const static Vector2d xAxis2d = Vector2d(1, 0); const static Vector2d yAxis2d = Vector2d(0, 1); template <typename T> bool GetTwoLinesIntersection(const Vector2<T>& p1, const Vector2<T>& p2, const Vector2<T>& t1, const Vector2<T>& t2, Vector2<T>& p0) { Vector2<T> v1, v2; T k1, k2; v1 = p2 - p1; v2 = t2 - t1; T invmul; T mul = v1 ^ v2; if (fabs(mul) > T(1e-5)) { invmul = 1.0f / (v1 ^ v2); k2 = ((t1 ^ v1) - (p1 ^ v1)) * invmul; /*p1.x * v1.y - p1.y * v1.x + t1.y * v1.x - t1.x * v1.y*/ k1 = ((t1 ^ v2) - (p1 ^ v2)) * invmul; p0 = p1 + v1 * k1; // Vector p02 = t1 + v2 * k2; return ((k1 > 0.0f) && (k1 < 1.0f) && (k2 > 0.0f) && (k2 < 1.0f)); } else { return 0; } p0 = t1 + (t1 - t2); //100% bad point return 0; } template <typename T> bool ProjectPointToLine(const Vector2<T>& t1, const Vector2<T>& t2, const Vector2<T>& p, Vector2<T>& p0, T& signOfSide) { Vector2<T> v1 = p - t1; Vector2<T> v2 = t2 - t1; signOfSide = sgn(v1 ^ v2); p0 = t1 + v2 * ((v1 * v2) / v2.SquareLen()); if ((v1 * v2 >= 0.0f) && ((v1 * v2) / (v2.SquareLen()) <= 1.0f)) { return 1; } else { return 0; } } template <typename T> bool ProjectPointToLine(const Vector2<T>& t1, const Vector2<T>& t2, const Vector2<T>& p, Vector2<T>& p0) { T signOfSide; return ProjectPointToLine(t1, t2, p, p0, signOfSide); } template <typename T> T PointToSegmentDistanse(const Vector2<T>& t1, const Vector2<T>& t2, const Vector2<T>& p) { Vector2<T> p0; T signOfSide; if (ProjectPointToLine(t1, t2, p, p0, signOfSide)) { return Vector2<T>(p.x - p0.x, p.y - p0.y).Len(); } else { return Min(Vector2<T>(p.x - t1.x, p.y - t1.y).Len(), Vector2<T>(p.x - t2.x, p.y - t2.y).Len()); } } template <typename T> void ProjectPointToLine(const Vector2<T>& point, const Vector2<T>& planePoint, const Vector2<T>& planeNormal, const Vector2<T>& projectionDirection, Vector2f& projectedPoint) { float mult = 1.0f / (projectionDirection * planeNormal); projectedPoint = point + projectionDirection * ((planePoint * planeNormal) - (point * planeNormal)) * mult; } template <typename T> void ProjectPointToPlane(const Vector2<T>& point, const Vector2<T>& planePoint, const Vector2<T>& planeNormal, const Vector2<T>& projectionDirection, Vector2f& projectedPoint) { ProjectPointToLine(point, planePoint, planeNormal, projectionDirection, projectedPoint); } template <typename T> void ProjectPointToLine_noreturn(const Vector2<T>& t1, const Vector2<T>& t2, const Vector2<T>& p, Vector2<T>& p0, T& signOfSide) { Vector2<T> v1 = p - t1; Vector2<T> v2 = t2 - t1; signOfSide = sgn(v1 ^ v2); p0 = t1 + v2 * ((v1 * v2) / v2.SquareLen()); } template <typename GeomSpace> bool IsPointInCellEx(const typename GeomSpace::Vector2 points[3], typename GeomSpace::Vector2 testPoint, typename GeomSpace::Scalar eps = 0) { typedef typename GeomSpace::Scalar Scalar; Scalar side0 = ((points[1] - points[0]) ^ (testPoint - points[0])); Scalar side1 = ((points[2] - points[1]) ^ (testPoint - points[1])); Scalar side2 = ((points[0] - points[2]) ^ (testPoint - points[2])); if (side0 >= -eps && side1 >= -eps && side2 >= -eps) return 1; if (side0 <= eps && side1 <= eps && side2 <= eps) return 1; return 0; } template <typename GeomSpace> bool IsPointInCell(const typename GeomSpace::Vector2 points[3], typename GeomSpace::Vector2 testPoint) { typedef typename GeomSpace::Scalar Scalar; //Scalar //eps = 0;//-1e-4;//std::numeric_limits<float>::epsilon();//Scalar(1e-9); Scalar eps = std::numeric_limits<Scalar>::epsilon(); Scalar side0 = ((points[1] - points[0]) ^ (testPoint - points[0])); Scalar side1 = ((points[2] - points[1]) ^ (testPoint - points[1])); Scalar side2 = ((points[0] - points[2]) ^ (testPoint - points[2])); if (side0 >= -eps && side1 >= -eps && side2 >= -eps) return 1; if (side0 <= eps && side1 <= eps && side2 <= eps) return 1; return 0; /*Scalar eps = std::numeric_limits<float>::epsilon();//Scalar(1e-9); Scalar side012 = mixed_product(points[1] - points[0], points[2] - points[0], testPoint - points[0]) * mixed_product(points[1] - points[0], points[2] - points[0], points[3] - points[0]); if(side012 < -eps) return 0; Scalar side123 = mixed_product(points[1] - points[2], points[3] - points[2], testPoint - points[2]) * mixed_product(points[1] - points[2], points[3] - points[2], points[0] - points[2]); if(side123 < -eps) return 0; Scalar side230 = mixed_product(points[2] - points[3], points[0] - points[3], testPoint - points[3]) * mixed_product(points[2] - points[3], points[0] - points[3], points[1] - points[3]); if(side230 < -eps) return 0; Scalar side013 = mixed_product(points[0] - points[1], points[3] - points[1], testPoint - points[1]) * mixed_product(points[0] - points[1], points[3] - points[1], points[2] - points[1]); if(side013 < -eps) return 0; return 1;*/ /*Scalar side1 = mixed_product(points[2] - points[0], points[3] - points[0], testPoint - points[0]); Scalar side2 = mixed_product(points[3] - points[0], points[1] - points[0], testPoint - points[0]); Scalar side3 = mixed_product(points[3] - points[1], points[2] - points[1], testPoint - points[1]); if (side0 * side1 < 0) return 0; if (side1 * side2 < 0) return 0; if (side2 * side3 < 0) return 0; return 1;*/ }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/World.cpp
C++
#include "World.h" #include "base/Parallel.h" #include "microprofile.h" World::World() : gravity(0) { } RigidBody* World::AddBody(Coords2f coords, Vector2f size) { RigidBody newbie(coords, size, 1e-5f); newbie.index = bodies.size; bodies.push_back(newbie); return &(bodies[bodies.size - 1]); } void World::Update(WorkQueue& queue, float dt, const Configuration& configuration) { MICROPROFILE_SCOPEI("Physics", "Update", 0x00ff00); collisionTime = mergeTime = solveTime = 0; IntegrateVelocity(queue, dt); collider.UpdateBroadphase(bodies.data, bodies.size); collider.UpdatePairs(queue, bodies.data, bodies.size); collider.UpdateManifolds(queue, bodies.data); collider.PackManifolds(bodies.data); RefreshContactJoints(); solver.SolveJoints(queue, bodies.data, bodies.size, collider.contactPoints.data, configuration); IntegratePosition(queue, dt); } NOINLINE void World::IntegrateVelocity(WorkQueue& queue, float dt) { MICROPROFILE_SCOPEI("Physics", "IntegrateVelocity", -1); parallelFor(queue, bodies.data, bodies.size, 32, [this, dt](RigidBody& body, int) { if (body.invMass > 0.0f) { body.acceleration.y += gravity; } body.velocity += body.acceleration * dt; body.acceleration = Vector2f(0.0f, 0.0f); body.angularVelocity += body.angularAcceleration * dt; body.angularAcceleration = 0.0f; }); } NOINLINE void World::IntegratePosition(WorkQueue& queue, float dt) { MICROPROFILE_SCOPEI("Physics", "IntegratePosition", -1); parallelFor(queue, bodies.data, bodies.size, 32, [dt](RigidBody& body, int) { body.coords.pos += body.displacingVelocity + body.velocity * dt; body.coords.Rotate(-(body.displacingAngularVelocity + body.angularVelocity * dt)); body.displacingVelocity = Vector2f(0.0f, 0.0f); body.displacingAngularVelocity = 0.0f; body.UpdateGeom(); }); } NOINLINE void World::RefreshContactJoints() { MICROPROFILE_SCOPEI("Physics", "RefreshContactJoints", -1); int matched = 0; int created = 0; int deleted = 0; { MICROPROFILE_SCOPEI("Physics", "Reset", -1); for (int jointIndex = 0; jointIndex < solver.contactJoints.size; jointIndex++) { solver.contactJoints[jointIndex].contactPointIndex = -1; } } { MICROPROFILE_SCOPEI("Physics", "Match", -1); for (int manifoldIndex = 0; manifoldIndex < collider.manifolds.size; ++manifoldIndex) { Manifold& man = collider.manifolds[manifoldIndex]; for (int collisionIndex = 0; collisionIndex < man.pointCount; collisionIndex++) { int contactPointIndex = man.pointIndex + collisionIndex; ContactPoint& col = collider.contactPoints[contactPointIndex]; if (col.solverIndex < 0) { col.solverIndex = solver.contactJoints.size; solver.contactJoints.push_back(ContactJoint(man.body1Index, man.body2Index, contactPointIndex)); created++; } else { ContactJoint& joint = solver.contactJoints[col.solverIndex]; assert(joint.body1Index == man.body1Index); assert(joint.body2Index == man.body2Index); joint.contactPointIndex = contactPointIndex; matched++; } } } } { MICROPROFILE_SCOPEI("Physics", "Cleanup", -1); for (int jointIndex = 0; jointIndex < solver.contactJoints.size;) { ContactJoint& joint = solver.contactJoints[jointIndex]; if (joint.contactPointIndex < 0) { joint = solver.contactJoints[solver.contactJoints.size - 1]; solver.contactJoints.size--; deleted++; } else { collider.contactPoints[joint.contactPointIndex].solverIndex = jointIndex; jointIndex++; } } } MICROPROFILE_META_CPU("Matched", matched); MICROPROFILE_META_CPU("Created", created); MICROPROFILE_META_CPU("Deleted", deleted); }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/World.h
C/C++ Header
#pragma once #include "RigidBody.h" #include "Collider.h" #include "Solver.h" struct Configuration; struct World { enum SolveMode { Solve_Scalar, Solve_SSE2, Solve_AVX2, }; World(); RigidBody* AddBody(Coords2f coords, Vector2f size); void Update(WorkQueue& queue, float dt, const Configuration& configuration); NOINLINE void IntegrateVelocity(WorkQueue& queue, float dt); NOINLINE void IntegratePosition(WorkQueue& queue, float dt); NOINLINE void RefreshContactJoints(); float collisionTime; float mergeTime; float solveTime; AlignedArray<RigidBody> bodies; Collider collider; Solver solver; float gravity; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/AlignedArray.h
C/C++ Header
#pragma once #include <xmmintrin.h> #include <string.h> template <typename T> struct AlignedArray { T* data; int size; int capacity; AlignedArray() : data(0) , size(0) , capacity(0) { } ~AlignedArray() { _mm_free(data); } AlignedArray(const AlignedArray&) = delete; AlignedArray& operator=(const AlignedArray&) = delete; AlignedArray(AlignedArray&& other) { data = other.data; size = other.size; capacity = other.capacity; other.data = 0; other.size = 0; other.capacity = 0; } AlignedArray& operator=(AlignedArray&& other) { _mm_free(data); data = other.data; size = other.size; capacity = other.capacity; other.data = 0; other.size = 0; other.capacity = 0; return *this; } T* begin() { return data; } T* end() { return data + size; } T& operator[](int i) { assert(i >= 0 && i < size); return data[i]; } const T& operator[](int i) const { assert(i >= 0 && i < size); return data[i]; } void push_back(const T& value) { if (size == capacity) { T copy = value; realloc(size + 1, true); data[size++] = copy; } else { data[size++] = value; } } void truncate(int newsize) { assert(newsize <= size); size = newsize; } void resize_copy(int newsize) { if (newsize > capacity) realloc(newsize, true); size = newsize; } void resize(int newsize) { if (newsize > capacity) realloc(newsize, false); size = newsize; } void realloc(int newsize, bool copy) { int newcapacity = capacity; while (newcapacity < newsize) newcapacity += newcapacity / 2 + 1; // Leave 32b padding at the end to avoid buffer overruns for fast SIMD code T* newdata = static_cast<T*>(_mm_malloc(newcapacity * sizeof(T) + 32, 32)); if (data) { if (copy) memcpy(newdata, data, size * sizeof(T)); _mm_free(data); } data = newdata; capacity = newcapacity; } void clear() { size = 0; } };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/DenseHash.h
C/C++ Header
#pragma once #include <vector> #include <cassert> #include <utility> #include <functional> // Internal implementation of DenseHashSet and DenseHashMap namespace detail { template <typename Key, typename Item, typename Hash, typename Eq> class DenseHashTable { public: typedef typename std::vector<Item>::const_iterator const_iterator; DenseHashTable(size_t capacity, const Hash& hash, const Eq& eq) : filled(0) , hash(hash) , eq(eq) { if (capacity) { items.reserve(capacity); rehash(capacity); } } const_iterator begin() const { return items.begin(); } const_iterator end() const { return items.end(); } bool empty() const { return items.empty(); } size_t size() const { return items.size(); } size_t bucket_count() const { return buckets.size(); } float load_factor() const { return buckets.empty() ? 0 : float(filled) / float(buckets.size()); } void clear() { items.clear(); buckets.clear(); filled = 0; } protected: std::vector<Item> items; std::vector<int32_t> buckets; size_t filled; // number of non-empty buckets Hash hash; Eq eq; void rehash() { if (filled >= buckets.size() * 3 / 4) { rehash(items.size() * 2); } } void rehash(size_t capacity) { size_t newbuckets = 16; while (newbuckets < capacity) newbuckets *= 2; size_t hashmod = newbuckets - 1; std::vector<int32_t>(newbuckets, -1).swap(buckets); for (size_t i = 0; i < items.size(); ++i) { size_t bucket = hash(getKey(items[i])) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { if (buckets[bucket] < 0) { buckets[bucket] = i; break; } // Hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } } filled = items.size(); } int find_bucket(const Key& key) const { if (buckets.empty()) return -1; size_t hashmod = buckets.size() - 1; size_t bucket = hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { int32_t probe_index = buckets[bucket]; // Element does not exist, insert here if (probe_index == -1) return -1; // Not a tombstone and key matches if (probe_index >= 0 && eq(getKey(items[probe_index]), key)) return bucket; // Hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } // Hash table is full - this should not happen assert(false); return -1; } std::pair<Item*, bool> insert_item(const Key& key) { assert(!buckets.empty()); size_t hashmod = buckets.size() - 1; size_t bucket = hash(key) & hashmod; for (size_t probe = 0; probe <= hashmod; ++probe) { int32_t probe_index = buckets[bucket]; // Element does not exist or a tombstone, insert here // TODO: this is incorrect! we have to follow the chain of tombstones to the end just in case our element does exist :( if (probe_index < 0) { buckets[bucket] = items.size(); filled += probe_index == -1; items.push_back(Item()); getKey(items.back()) = key; return std::make_pair(&items.back(), true); } // Key matches, insert here if (eq(getKey(items[probe_index]), key)) return std::make_pair(&items[probe_index], false); // Hash collision, quadratic probing bucket = (bucket + probe + 1) & hashmod; } // Hash table is full - this should not happen assert(false); return std::make_pair(static_cast<Item*>(0), false); } void erase_bucket(int bucket) { assert(bucket >= 0); int32_t probe_index = buckets[bucket]; assert(probe_index >= 0); // move last key // TODO: this is suboptimal! we don't need to compare keys when searching for this, it's enough to find a bucket that points to items.size()-1 int probe_bucket = find_bucket(getKey(items.back())); assert(probe_bucket >= 0); assert(buckets[probe_bucket] == int32_t(items.size() - 1)); items[probe_index] = items.back(); buckets[probe_bucket] = probe_index; items.pop_back(); // mark bucket as tombstone buckets[bucket] = -2; } private: // Interface to support both key and pair<key, value> static const Key& getKey(const Key& item) { return item; } static Key& getKey(Key& item) { return item; } template <typename Value> static const Key& getKey(const std::pair<Key, Value>& item) { return item.first; } template <typename Value> static Key& getKey(std::pair<Key, Value>& item) { return item.first; } }; } template <typename Key, typename Hash = std::hash<Key>, typename Eq = std::equal_to<Key>> class DenseHashSet: public detail::DenseHashTable<Key, Key, Hash, Eq> { public: explicit DenseHashSet(size_t capacity = 0, const Hash& hash = Hash(), const Eq& eq = Eq()) : detail::DenseHashTable<Key, Key, Hash, Eq>(capacity, hash, eq) { } bool contains(const Key& key) const { return this->find_bucket(key) >= 0; } bool insert(const Key& key) { this->rehash(); return this->insert_item(key).second; } void erase(const Key& key) { int bucket = this->find_bucket(key); if (bucket >= 0) this->erase_bucket(bucket); } }; // This is a faster alternative of std::unordered_map, but it does not implement the same interface (i.e. it does not support erasing and has contains() instead of find()) template <typename Key, typename Value, typename Hash = std::hash<Key>, typename Eq = std::equal_to<Key>> class DenseHashMap: public detail::DenseHashTable<Key, std::pair<Key, Value>, Hash, Eq> { public: explicit DenseHashMap(size_t capacity = 0, const Hash& hash = Hash(), const Eq& eq = Eq()) : detail::DenseHashTable<Key, std::pair<Key, Value>, Hash, Eq>(capacity, hash, eq) { } const Value* find(const Key& key) const { int bucket = this->find_bucket(key); return bucket < 0 ? NULL : &this->items[this->buckets[bucket]].second; } Value& operator[](const Key& key) { this->rehash(); return this->insert_item(key).first->second; } void erase(const Key& key) { int bucket = this->find_bucket(key); if (bucket >= 0) this->erase_bucket(bucket); } };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/Parallel.h
C/C++ Header
#pragma once #include "WorkQueue.h" #include <atomic> #include "microprofile.h" template <typename T> inline T& parallelForIndex(T* data, unsigned int index) { return data[index]; } inline unsigned int parallelForIndex(unsigned int data, unsigned int index) { return data + index; } template <typename T, typename F> inline void serialFor(WorkQueue& queue, T data, unsigned int count, unsigned int groupSize, F func) { for (unsigned int i = 0; i < count; ++i) func(parallelForIndex(data, i), 0); } template <typename T, typename F> inline void parallelFor(WorkQueue& queue, T data, unsigned int count, unsigned int groupSize, F func) { if (queue.getWorkerCount() == 0 || count <= groupSize) { for (unsigned int i = 0; i < count; ++i) func(parallelForIndex(data, i), 0); return; } MICROPROFILE_SCOPEI("WorkQueue", "ParallelFor", 0x808080); struct Item: WorkQueue::Item { WorkQueue* queue; std::atomic<unsigned int> counter; std::atomic<unsigned int> ready; T data; unsigned int count; unsigned int groupSize; unsigned int groupCount; F* func; Item(): counter(0), ready(0) { } void run(int worker) override { unsigned int groups = 0; for (;;) { unsigned int groupIndex = counter.fetch_add(1); if (groupIndex >= groupCount) break; unsigned int begin = groupIndex * groupSize; unsigned int end = std::min(count, begin + groupSize); for (unsigned int i = begin; i < end; ++i) (*func)(parallelForIndex(data, i), worker); groups++; } ready.fetch_add(groups); } }; auto item = std::make_shared<Item>(); item->queue = &queue; item->data = data; item->count = count; item->groupSize = groupSize; item->groupCount = (count + groupSize - 1) / groupSize; item->func = &func; int optimalWorkerCount = std::min(unsigned(queue.getWorkerCount()), item->groupCount - 1); queue.pushItem(item, optimalWorkerCount); item->run(queue.getWorkerCount()); if (item->ready.load() < item->groupCount) { MICROPROFILE_SCOPEI("WorkQueue", "Wait", 0xff0000); do std::this_thread::yield(); while (item->ready.load() < item->groupCount); } }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/RadixSort.h
C/C++ Header
#pragma once inline unsigned int radixUnsignedInt(unsigned int v) { return v; } inline unsigned int radixInt(int v) { // flip sign bit return static_cast<unsigned int>(v) ^ 0x80000000; } inline unsigned int radixUnsignedFloat(const float& v) { return *reinterpret_cast<const unsigned int*>(&v); } inline unsigned int radixFloat(const float& v) { // if sign bit is 0, flip sign bit // if sign bit is 1, flip everything int f = *reinterpret_cast<const int*>(&v); unsigned int mask = int(f >> 31) | 0x80000000; return f ^ mask; } template <typename T, typename Pred> inline T* radixSort3(T* e0, T* e1, size_t count, Pred pred) { unsigned int h[2048*3]; for (size_t i = 0; i < 2048*3; ++i) h[i] = 0; unsigned int* h0 = h; unsigned int* h1 = h + 2048; unsigned int* h2 = h + 2048*2; T* e0_end = e0 + count; #define _0(h) ((h) & 2047) #define _1(h) (((h) >> 11) & 2047) #define _2(h) ((h) >> 22) // fill histogram for (const T* i = e0; i != e0_end; ++i) { unsigned int h = pred(*i); h0[_0(h)]++; h1[_1(h)]++; h2[_2(h)]++; } // compute offsets { unsigned int sum0 = 0, sum1 = 0, sum2 = 0; for (unsigned int i = 0; i < 2048; ++i) { unsigned int c0 = h0[i]; unsigned int c1 = h1[i]; unsigned int c2 = h2[i]; h0[i] = sum0; h1[i] = sum1; h2[i] = sum2; sum0 += c0; sum1 += c1; sum2 += c2; } } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e0[i]); e1[h0[_0(h)]++] = e0[i]; } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e1[i]); e0[h1[_1(h)]++] = e1[i]; } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e0[i]); e1[h2[_2(h)]++] = e0[i]; } #undef _0 #undef _1 #undef _2 return e1; } template <typename T, typename Pred> inline T* radixSort4(T* e0, T* e1, size_t count, Pred pred) { unsigned int h[256*4]; for (size_t i = 0; i < 256*4; ++i) h[i] = 0; unsigned int* h0 = h; unsigned int* h1 = h + 256; unsigned int* h2 = h + 256*2; unsigned int* h3 = h + 256*3; T* e0_end = e0 + count; #define _0(h) ((h) & 255) #define _1(h) (((h) >> 8) & 255) #define _2(h) (((h) >> 16) & 255) #define _3(h) ((h) >> 24) // fill histogram for (const T* i = e0; i != e0_end; ++i) { unsigned int h = pred(*i); h0[_0(h)]++; h1[_1(h)]++; h2[_2(h)]++; h3[_3(h)]++; } // compute offsets { unsigned int sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0; for (unsigned int i = 0; i < 256; ++i) { unsigned int c0 = h0[i]; unsigned int c1 = h1[i]; unsigned int c2 = h2[i]; unsigned int c3 = h3[i]; h0[i] = sum0; h1[i] = sum1; h2[i] = sum2; h3[i] = sum3; sum0 += c0; sum1 += c1; sum2 += c2; sum3 += c3; } } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e0[i]); e1[h0[_0(h)]++] = e0[i]; } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e1[i]); e0[h1[_1(h)]++] = e1[i]; } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e0[i]); e1[h2[_2(h)]++] = e0[i]; } for (size_t i = 0; i < count; ++i) { unsigned int h = pred(e1[i]); e0[h3[_3(h)]++] = e1[i]; } #undef _0 #undef _1 #undef _2 #undef _3 return e0; }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/SIMD.h
C/C++ Header
#pragma once #include <immintrin.h> #ifdef _MSC_VER #define SIMD_INLINE __forceinline #define SIMD_ALIGN(n) __declspec(align(n)) #else #define SIMD_INLINE __attribute__((always_inline)) inline #define SIMD_ALIGN(n) __attribute__((aligned(n))) #endif namespace simd { template <int N> struct VNf_; template <int N> struct VNi_; template <int N> struct VNb_; template <int N> using VNf = typename VNf_<N>::type; template <int N> using VNi = typename VNi_<N>::type; template <int N> using VNb = typename VNb_<N>::type; template <typename T> void dump(const char* name, const T& v) { printf("%s:", name); const float* fptr = reinterpret_cast<const float*>(&v); const int* iptr = reinterpret_cast<const int*>(&v); for (size_t i = 0; i < sizeof(v) / 4; ++i) printf(" %f [%08x]", fptr[i], iptr[i]); printf("\n"); } } #define SIMD_DUMP(v) simd::dump(#v, v) #include "SIMD_Scalar.h" #ifdef __SSE2__ #include "SIMD_SSE2.h" #endif #ifdef __AVX2__ #include "SIMD_AVX2.h" #endif
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/SIMD_AVX2.h
C/C++ Header
#pragma once #include "SIMD_AVX2_Transpose.h" namespace simd { struct V8f { __m256 v; SIMD_INLINE V8f() { } SIMD_INLINE V8f(__m256 v): v(v) { } SIMD_INLINE operator __m256() const { return v; } SIMD_INLINE static V8f zero() { return _mm256_setzero_ps(); } SIMD_INLINE static V8f one(float v) { return _mm256_set1_ps(v); } SIMD_INLINE static V8f sign() { return _mm256_castsi256_ps(_mm256_set1_epi32(0x80000000)); } SIMD_INLINE static V8f load(const float* ptr) { return _mm256_load_ps(ptr); } }; struct V8i { __m256i v; SIMD_INLINE V8i() { } SIMD_INLINE V8i(__m256i v): v(v) { } SIMD_INLINE operator __m256i() const { return v; } SIMD_INLINE static V8i zero() { return _mm256_setzero_si256(); } SIMD_INLINE static V8i one(int v) { return _mm256_set1_epi32(v); } SIMD_INLINE static V8i load(const int* ptr) { return _mm256_load_si256(reinterpret_cast<const __m256i*>(ptr)); } }; struct V8b { __m256 v; SIMD_INLINE V8b() { } SIMD_INLINE V8b(__m256 v): v(v) { } SIMD_INLINE V8b(__m256i v): v(_mm256_castsi256_ps(v)) { } SIMD_INLINE operator __m256() const { return v; } SIMD_INLINE static V8b zero() { return _mm256_setzero_ps(); } }; SIMD_INLINE V8i bitcast(V8f v) { return _mm256_castps_si256(v.v); } SIMD_INLINE V8f bitcast(V8i v) { return _mm256_castsi256_ps(v.v); } SIMD_INLINE V8f operator+(V8f v) { return v; } SIMD_INLINE V8f operator-(V8f v) { return _mm256_xor_ps(V8f::sign(), v.v); } SIMD_INLINE V8f operator+(V8f l, V8f r) { return _mm256_add_ps(l.v, r.v); } SIMD_INLINE V8f operator-(V8f l, V8f r) { return _mm256_sub_ps(l.v, r.v); } SIMD_INLINE V8f operator*(V8f l, V8f r) { return _mm256_mul_ps(l.v, r.v); } SIMD_INLINE V8f operator/(V8f l, V8f r) { return _mm256_div_ps(l.v, r.v); } SIMD_INLINE void operator+=(V8f& l, V8f r) { l.v = _mm256_add_ps(l.v, r.v); } SIMD_INLINE void operator-=(V8f& l, V8f r) { l.v = _mm256_sub_ps(l.v, r.v); } SIMD_INLINE void operator*=(V8f& l, V8f r) { l.v = _mm256_mul_ps(l.v, r.v); } SIMD_INLINE void operator/=(V8f& l, V8f r) { l.v = _mm256_div_ps(l.v, r.v); } SIMD_INLINE V8b operator==(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_EQ_UQ); } SIMD_INLINE V8b operator==(V8i l, V8i r) { return _mm256_cmpeq_epi32(l.v, r.v); } SIMD_INLINE V8b operator!=(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_NEQ_UQ); } SIMD_INLINE V8b operator!=(V8i l, V8i r) { return _mm256_xor_si256(_mm256_setzero_si256(), _mm256_cmpeq_epi32(l.v, r.v)); } SIMD_INLINE V8b operator<(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_LT_OQ); } SIMD_INLINE V8b operator<(V8i l, V8i r) { return _mm256_cmpgt_epi32(r.v, l.v); } SIMD_INLINE V8b operator<=(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_LE_OQ); } SIMD_INLINE V8b operator<=(V8i l, V8i r) { return _mm256_xor_si256(_mm256_setzero_si256(), _mm256_cmpgt_epi32(l.v, r.v)); } SIMD_INLINE V8b operator>(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_GT_OQ); } SIMD_INLINE V8b operator>(V8i l, V8i r) { return _mm256_cmpgt_epi32(l.v, r.v); } SIMD_INLINE V8b operator>=(V8f l, V8f r) { return _mm256_cmp_ps(l.v, r.v, _CMP_GE_OQ); } SIMD_INLINE V8b operator>=(V8i l, V8i r) { return _mm256_xor_si256(_mm256_setzero_si256(), _mm256_cmpgt_epi32(r.v, l.v)); } SIMD_INLINE V8b operator!(V8b v) { return _mm256_xor_ps(_mm256_setzero_ps(), v.v); } SIMD_INLINE V8b operator&(V8b l, V8b r) { return _mm256_and_ps(l.v, r.v); } SIMD_INLINE V8b operator|(V8b l, V8b r) { return _mm256_or_ps(l.v, r.v); } SIMD_INLINE V8b operator^(V8b l, V8b r) { return _mm256_xor_ps(l.v, r.v); } SIMD_INLINE void operator&=(V8b& l, V8b r) { l.v = _mm256_and_ps(l.v, r.v); } SIMD_INLINE void operator|=(V8b& l, V8b r) { l.v = _mm256_or_ps(l.v, r.v); } SIMD_INLINE void operator^=(V8b& l, V8b r) { l.v = _mm256_xor_ps(l.v, r.v); } SIMD_INLINE V8f abs(V8f v) { return _mm256_andnot_ps(V8f::sign(), v.v); } SIMD_INLINE V8f copysign(V8f x, V8f y) { V8f sign = V8f::sign(); return _mm256_or_ps(_mm256_andnot_ps(sign.v, x.v), _mm256_and_ps(y.v, sign.v)); } SIMD_INLINE V8f flipsign(V8f x, V8f y) { return _mm256_xor_ps(x.v, _mm256_and_ps(y.v, V8f::sign())); } SIMD_INLINE V8f min(V8f l, V8f r) { return _mm256_min_ps(l.v, r.v); } SIMD_INLINE V8f max(V8f l, V8f r) { return _mm256_max_ps(l.v, r.v); } SIMD_INLINE V8f select(V8f l, V8f r, V8b m) { return _mm256_blendv_ps(l.v, r.v, m.v); } SIMD_INLINE V8i select(V8i l, V8i r, V8b m) { __m256i mi = _mm256_castps_si256(m.v); return _mm256_blendv_epi8(l.v, r.v, mi); } SIMD_INLINE bool none(V8b v) { return _mm256_movemask_ps(v.v) == 0; } SIMD_INLINE bool any(V8b v) { return _mm256_movemask_ps(v.v) != 0; } SIMD_INLINE bool all(V8b v) { return _mm256_movemask_ps(v.v) == 31; } SIMD_INLINE void store(V8f v, float* ptr) { _mm256_store_ps(ptr, v.v); } SIMD_INLINE void store(V8i v, int* ptr) { _mm256_store_si256(reinterpret_cast<__m256i*>(ptr), v.v); } SIMD_INLINE void loadindexed4(V8f& v0, V8f& v1, V8f& v2, V8f& v3, const void* base, const int indices[8], unsigned int stride) { const char* ptr = static_cast<const char*>(base); __m128 hr0 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[0] * stride)); __m128 hr1 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[1] * stride)); __m128 hr2 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[2] * stride)); __m128 hr3 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[3] * stride)); __m128 hr4 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[4] * stride)); __m128 hr5 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[5] * stride)); __m128 hr6 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[6] * stride)); __m128 hr7 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[7] * stride)); __m256 r0 = _mm256_insertf128_ps(_mm256_castps128_ps256(hr0), hr4, 1); __m256 r1 = _mm256_insertf128_ps(_mm256_castps128_ps256(hr1), hr5, 1); __m256 r2 = _mm256_insertf128_ps(_mm256_castps128_ps256(hr2), hr6, 1); __m256 r3 = _mm256_insertf128_ps(_mm256_castps128_ps256(hr3), hr7, 1); _MM_TRANSPOSE8_LANE4_PS(r0, r1, r2, r3); v0.v = r0; v1.v = r1; v2.v = r2; v3.v = r3; } SIMD_INLINE void storeindexed4(const V8f& v0, const V8f& v1, const V8f& v2, const V8f& v3, void* base, const int indices[8], unsigned int stride) { char* ptr = static_cast<char*>(base); __m256 r0 = v0.v; __m256 r1 = v1.v; __m256 r2 = v2.v; __m256 r3 = v3.v; _MM_TRANSPOSE8_LANE4_PS(r0, r1, r2, r3); __m128 hr0 = _mm256_castps256_ps128(r0); __m128 hr1 = _mm256_castps256_ps128(r1); __m128 hr2 = _mm256_castps256_ps128(r2); __m128 hr3 = _mm256_castps256_ps128(r3); __m128 hr4 = _mm256_extractf128_ps(r0, 1); __m128 hr5 = _mm256_extractf128_ps(r1, 1); __m128 hr6 = _mm256_extractf128_ps(r2, 1); __m128 hr7 = _mm256_extractf128_ps(r3, 1); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[0] * stride), hr0); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[1] * stride), hr1); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[2] * stride), hr2); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[3] * stride), hr3); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[4] * stride), hr4); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[5] * stride), hr5); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[6] * stride), hr6); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[7] * stride), hr7); } SIMD_INLINE void loadindexed8(V8f& v0, V8f& v1, V8f& v2, V8f& v3, V8f& v4, V8f& v5, V8f& v6, V8f& v7, const void* base, const int indices[8], unsigned int stride) { const char* ptr = static_cast<const char*>(base); __m256 r0 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[0] * stride)); __m256 r1 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[1] * stride)); __m256 r2 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[2] * stride)); __m256 r3 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[3] * stride)); __m256 r4 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[4] * stride)); __m256 r5 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[5] * stride)); __m256 r6 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[6] * stride)); __m256 r7 = _mm256_load_ps(reinterpret_cast<const float*>(ptr + indices[7] * stride)); _MM_TRANSPOSE8_PS(r0, r1, r2, r3, r4, r5, r6, r7); v0.v = r0; v1.v = r1; v2.v = r2; v3.v = r3; v4.v = r4; v5.v = r5; v6.v = r6; v7.v = r7; } } namespace simd { template <> struct VNf_<8> { typedef V8f type; }; template <> struct VNi_<8> { typedef V8i type; }; template <> struct VNb_<8> { typedef V8b type; }; } using simd::V8f; using simd::V8i; using simd::V8b;
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/SIMD_AVX2_Transpose.h
C/C++ Header
#pragma once // Transpose 4x4 blocks within each lane #define _MM_TRANSPOSE8_LANE4_PS(row0, row1, row2, row3) \ do { \ __m256 __t0, __t1, __t2, __t3; \ __t0 = _mm256_unpacklo_ps(row0, row1); \ __t1 = _mm256_unpackhi_ps(row0, row1); \ __t2 = _mm256_unpacklo_ps(row2, row3); \ __t3 = _mm256_unpackhi_ps(row2, row3); \ row0 = _mm256_shuffle_ps(__t0, __t2, _MM_SHUFFLE(1, 0, 1, 0)); \ row1 = _mm256_shuffle_ps(__t0, __t2, _MM_SHUFFLE(3, 2, 3, 2)); \ row2 = _mm256_shuffle_ps(__t1, __t3, _MM_SHUFFLE(1, 0, 1, 0)); \ row3 = _mm256_shuffle_ps(__t1, __t3, _MM_SHUFFLE(3, 2, 3, 2)); \ } while (0) // http://stackoverflow.com/questions/25622745/transpose-an-8x8-float-using-avx-avx2 #define _MM_TRANSPOSE8_PS(row0, row1, row2, row3, row4, row5, row6, row7) \ do { \ __m256 __t0, __t1, __t2, __t3, __t4, __t5, __t6, __t7; \ __m256 __tt0, __tt1, __tt2, __tt3, __tt4, __tt5, __tt6, __tt7; \ __t0 = _mm256_unpacklo_ps(row0, row1); \ __t1 = _mm256_unpackhi_ps(row0, row1); \ __t2 = _mm256_unpacklo_ps(row2, row3); \ __t3 = _mm256_unpackhi_ps(row2, row3); \ __t4 = _mm256_unpacklo_ps(row4, row5); \ __t5 = _mm256_unpackhi_ps(row4, row5); \ __t6 = _mm256_unpacklo_ps(row6, row7); \ __t7 = _mm256_unpackhi_ps(row6, row7); \ __tt0 = _mm256_shuffle_ps(__t0, __t2, _MM_SHUFFLE(1, 0, 1, 0)); \ __tt1 = _mm256_shuffle_ps(__t0, __t2, _MM_SHUFFLE(3, 2, 3, 2)); \ __tt2 = _mm256_shuffle_ps(__t1, __t3, _MM_SHUFFLE(1, 0, 1, 0)); \ __tt3 = _mm256_shuffle_ps(__t1, __t3, _MM_SHUFFLE(3, 2, 3, 2)); \ __tt4 = _mm256_shuffle_ps(__t4, __t6, _MM_SHUFFLE(1, 0, 1, 0)); \ __tt5 = _mm256_shuffle_ps(__t4, __t6, _MM_SHUFFLE(3, 2, 3, 2)); \ __tt6 = _mm256_shuffle_ps(__t5, __t7, _MM_SHUFFLE(1, 0, 1, 0)); \ __tt7 = _mm256_shuffle_ps(__t5, __t7, _MM_SHUFFLE(3, 2, 3, 2)); \ row0 = _mm256_permute2f128_ps(__tt0, __tt4, 0x20); \ row1 = _mm256_permute2f128_ps(__tt1, __tt5, 0x20); \ row2 = _mm256_permute2f128_ps(__tt2, __tt6, 0x20); \ row3 = _mm256_permute2f128_ps(__tt3, __tt7, 0x20); \ row4 = _mm256_permute2f128_ps(__tt0, __tt4, 0x31); \ row5 = _mm256_permute2f128_ps(__tt1, __tt5, 0x31); \ row6 = _mm256_permute2f128_ps(__tt2, __tt6, 0x31); \ row7 = _mm256_permute2f128_ps(__tt3, __tt7, 0x31); \ } while (0)
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/SIMD_SSE2.h
C/C++ Header
#pragma once namespace simd { struct V4f { __m128 v; SIMD_INLINE V4f() { } SIMD_INLINE V4f(__m128 v): v(v) { } SIMD_INLINE operator __m128() const { return v; } SIMD_INLINE static V4f zero() { return _mm_setzero_ps(); } SIMD_INLINE static V4f one(float v) { return _mm_set1_ps(v); } SIMD_INLINE static V4f sign() { return _mm_castsi128_ps(_mm_set1_epi32(0x80000000)); } SIMD_INLINE static V4f load(const float* ptr) { return _mm_load_ps(ptr); } }; struct V4i { __m128i v; SIMD_INLINE V4i() { } SIMD_INLINE V4i(__m128i v): v(v) { } SIMD_INLINE operator __m128i() const { return v; } SIMD_INLINE static V4i zero() { return _mm_setzero_si128(); } SIMD_INLINE static V4i one(int v) { return _mm_set1_epi32(v); } SIMD_INLINE static V4i load(const int* ptr) { return _mm_load_si128(reinterpret_cast<const __m128i*>(ptr)); } }; struct V4b { __m128 v; SIMD_INLINE V4b() { } SIMD_INLINE V4b(__m128 v): v(v) { } SIMD_INLINE V4b(__m128i v): v(_mm_castsi128_ps(v)) { } SIMD_INLINE operator __m128() const { return v; } SIMD_INLINE static V4b zero() { return _mm_setzero_ps(); } }; SIMD_INLINE V4f bitcast(V4i v) { return _mm_castsi128_ps(v.v); } SIMD_INLINE V4i bitcast(V4f v) { return _mm_castps_si128(v.v); } SIMD_INLINE V4f operator+(V4f v) { return v; } SIMD_INLINE V4f operator-(V4f v) { return _mm_xor_ps(V4f::sign(), v.v); } SIMD_INLINE V4f operator+(V4f l, V4f r) { return _mm_add_ps(l.v, r.v); } SIMD_INLINE V4f operator-(V4f l, V4f r) { return _mm_sub_ps(l.v, r.v); } SIMD_INLINE V4f operator*(V4f l, V4f r) { return _mm_mul_ps(l.v, r.v); } SIMD_INLINE V4f operator/(V4f l, V4f r) { return _mm_div_ps(l.v, r.v); } SIMD_INLINE void operator+=(V4f& l, V4f r) { l.v = _mm_add_ps(l.v, r.v); } SIMD_INLINE void operator-=(V4f& l, V4f r) { l.v = _mm_sub_ps(l.v, r.v); } SIMD_INLINE void operator*=(V4f& l, V4f r) { l.v = _mm_mul_ps(l.v, r.v); } SIMD_INLINE void operator/=(V4f& l, V4f r) { l.v = _mm_div_ps(l.v, r.v); } SIMD_INLINE V4b operator==(V4f l, V4f r) { return _mm_cmpeq_ps(l.v, r.v); } SIMD_INLINE V4b operator==(V4i l, V4i r) { return _mm_cmpeq_epi32(l.v, r.v); } SIMD_INLINE V4b operator!=(V4f l, V4f r) { return _mm_cmpneq_ps(l.v, r.v); } SIMD_INLINE V4b operator!=(V4i l, V4i r) { return _mm_xor_si128(_mm_setzero_si128(), _mm_cmpeq_epi32(l.v, r.v)); } SIMD_INLINE V4b operator<(V4f l, V4f r) { return _mm_cmplt_ps(l.v, r.v); } SIMD_INLINE V4b operator<(V4i l, V4i r) { return _mm_cmplt_epi32(l.v, r.v); } SIMD_INLINE V4b operator<=(V4f l, V4f r) { return _mm_cmple_ps(l.v, r.v); } SIMD_INLINE V4b operator<=(V4i l, V4i r) { return _mm_xor_si128(_mm_setzero_si128(), _mm_cmplt_epi32(r.v, l.v)); } SIMD_INLINE V4b operator>(V4f l, V4f r) { return _mm_cmpgt_ps(l.v, r.v); } SIMD_INLINE V4b operator>(V4i l, V4i r) { return _mm_cmpgt_epi32(l.v, r.v); } SIMD_INLINE V4b operator>=(V4f l, V4f r) { return _mm_cmpge_ps(l.v, r.v); } SIMD_INLINE V4b operator>=(V4i l, V4i r) { return _mm_xor_si128(_mm_setzero_si128(), _mm_cmplt_epi32(l.v, r.v)); } SIMD_INLINE V4b operator!(V4b v) { return _mm_xor_ps(_mm_setzero_ps(), v.v); } SIMD_INLINE V4b operator&(V4b l, V4b r) { return _mm_and_ps(l.v, r.v); } SIMD_INLINE V4b operator|(V4b l, V4b r) { return _mm_or_ps(l.v, r.v); } SIMD_INLINE V4b operator^(V4b l, V4b r) { return _mm_xor_ps(l.v, r.v); } SIMD_INLINE void operator&=(V4b& l, V4b r) { l.v = _mm_and_ps(l.v, r.v); } SIMD_INLINE void operator|=(V4b& l, V4b r) { l.v = _mm_or_ps(l.v, r.v); } SIMD_INLINE void operator^=(V4b l, V4b r) { l.v = _mm_xor_ps(l.v, r.v); } SIMD_INLINE V4f abs(V4f v) { return _mm_andnot_ps(V4f::sign(), v.v); } SIMD_INLINE V4f copysign(V4f x, V4f y) { V4f sign = V4f::sign(); return _mm_or_ps(_mm_andnot_ps(sign.v, x.v), _mm_and_ps(y.v, sign.v)); } SIMD_INLINE V4f flipsign(V4f x, V4f y) { return _mm_xor_ps(x.v, _mm_and_ps(y.v, V4f::sign())); } SIMD_INLINE V4f min(V4f l, V4f r) { return _mm_min_ps(l.v, r.v); } SIMD_INLINE V4f max(V4f l, V4f r) { return _mm_max_ps(l.v, r.v); } SIMD_INLINE V4f select(V4f l, V4f r, V4b m) { return _mm_or_ps(_mm_andnot_ps(m.v, l.v), _mm_and_ps(r.v, m.v)); } SIMD_INLINE V4i select(V4i l, V4i r, V4b m) { __m128i mi = _mm_castps_si128(m.v); return _mm_or_si128(_mm_andnot_si128(mi, l.v), _mm_and_si128(r.v, mi)); } SIMD_INLINE bool none(V4b v) { return _mm_movemask_ps(v.v) == 0; } SIMD_INLINE bool any(V4b v) { return _mm_movemask_ps(v.v) != 0; } SIMD_INLINE bool all(V4b v) { return _mm_movemask_ps(v.v) == 15; } SIMD_INLINE void store(V4f v, float* ptr) { _mm_store_ps(ptr, v.v); } SIMD_INLINE void store(V4i v, int* ptr) { _mm_store_si128(reinterpret_cast<__m128i*>(ptr), v.v); } SIMD_INLINE void loadindexed4(V4f& v0, V4f& v1, V4f& v2, V4f& v3, const void* base, const int indices[4], unsigned int stride) { const char* ptr = static_cast<const char*>(base); __m128 r0 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[0] * stride)); __m128 r1 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[1] * stride)); __m128 r2 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[2] * stride)); __m128 r3 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[3] * stride)); _MM_TRANSPOSE4_PS(r0, r1, r2, r3); v0.v = r0; v1.v = r1; v2.v = r2; v3.v = r3; } SIMD_INLINE void storeindexed4(const V4f& v0, const V4f& v1, const V4f& v2, const V4f& v3, void* base, const int indices[4], unsigned int stride) { char* ptr = static_cast<char*>(base); __m128 r0 = v0.v; __m128 r1 = v1.v; __m128 r2 = v2.v; __m128 r3 = v3.v; _MM_TRANSPOSE4_PS(r0, r1, r2, r3); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[0] * stride), r0); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[1] * stride), r1); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[2] * stride), r2); _mm_store_ps(reinterpret_cast<float*>(ptr + indices[3] * stride), r3); } SIMD_INLINE void loadindexed8(V4f& v0, V4f& v1, V4f& v2, V4f& v3, V4f& v4, V4f& v5, V4f& v6, V4f& v7, const void* base, const int indices[4], unsigned int stride) { const char* ptr = static_cast<const char*>(base); const float* ptr0 = reinterpret_cast<const float*>(ptr + indices[0] * stride); const float* ptr1 = reinterpret_cast<const float*>(ptr + indices[1] * stride); const float* ptr2 = reinterpret_cast<const float*>(ptr + indices[2] * stride); const float* ptr3 = reinterpret_cast<const float*>(ptr + indices[3] * stride); __m128 r0 = _mm_load_ps(ptr0 + 0); __m128 r1 = _mm_load_ps(ptr1 + 0); __m128 r2 = _mm_load_ps(ptr2 + 0); __m128 r3 = _mm_load_ps(ptr3 + 0); __m128 r4 = _mm_load_ps(ptr0 + 4); __m128 r5 = _mm_load_ps(ptr1 + 4); __m128 r6 = _mm_load_ps(ptr2 + 4); __m128 r7 = _mm_load_ps(ptr3 + 4); _MM_TRANSPOSE4_PS(r0, r1, r2, r3); _MM_TRANSPOSE4_PS(r4, r5, r6, r7); v0.v = r0; v1.v = r1; v2.v = r2; v3.v = r3; v4.v = r4; v5.v = r5; v6.v = r6; v7.v = r7; } } namespace simd { template <> struct VNf_<4> { typedef V4f type; }; template <> struct VNi_<4> { typedef V4i type; }; template <> struct VNb_<4> { typedef V4b type; }; } using simd::V4f; using simd::V4i; using simd::V4b;
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/SIMD_Scalar.h
C/C++ Header
#pragma once #include <math.h> namespace simd { struct V1f { float v; SIMD_INLINE V1f() { } SIMD_INLINE V1f(float v): v(v) { } SIMD_INLINE operator float() const { return v; } SIMD_INLINE static V1f zero() { return 0.f; } SIMD_INLINE static V1f one(float v) { return v; } SIMD_INLINE static V1f load(const float* ptr) { return *ptr; } }; struct V1i { int v; SIMD_INLINE V1i() { } SIMD_INLINE V1i(int v): v(v) { } SIMD_INLINE operator int() const { return v; } SIMD_INLINE static V1i zero() { return 0; } SIMD_INLINE static V1i one(int v) { return v; } SIMD_INLINE static V1i load(const int* ptr) { return *ptr; } }; struct V1b { bool v; SIMD_INLINE V1b() { } SIMD_INLINE V1b(bool v): v(v) { } SIMD_INLINE operator bool() const { return v; } SIMD_INLINE static V1b zero() { return false; } }; SIMD_INLINE V1f bitcast(const V1i& v) { union { float f; int i; } u; u.i = v.v; return u.f; } SIMD_INLINE V1i bitcast(const V1f& v) { union { float f; int i; } u; u.f = v.v; return u.i; } SIMD_INLINE V1f operator+(V1f v) { return v; } SIMD_INLINE V1f operator-(V1f v) { return -v.v; } SIMD_INLINE V1f operator+(V1f l, V1f r) { return l.v + r.v; } SIMD_INLINE V1f operator-(V1f l, V1f r) { return l.v - r.v; } SIMD_INLINE V1f operator*(V1f l, V1f r) { return l.v * r.v; } SIMD_INLINE V1f operator/(V1f l, V1f r) { return l.v / r.v; } SIMD_INLINE void operator+=(V1f& l, V1f r) { l.v += r.v; } SIMD_INLINE void operator-=(V1f& l, V1f r) { l.v -= r.v; } SIMD_INLINE void operator*=(V1f& l, V1f r) { l.v *= r.v; } SIMD_INLINE void operator/=(V1f& l, V1f r) { l.v /= r.v; } SIMD_INLINE V1b operator==(V1f l, V1f r) { return l.v == r.v; } SIMD_INLINE V1b operator==(V1i l, V1i r) { return l.v == r.v; } SIMD_INLINE V1b operator!=(V1f l, V1f r) { return l.v != r.v; } SIMD_INLINE V1b operator!=(V1i l, V1i r) { return l.v != r.v; } SIMD_INLINE V1b operator<(V1f l, V1f r) { return l.v < r.v; } SIMD_INLINE V1b operator<(V1i l, V1i r) { return l.v < r.v; } SIMD_INLINE V1b operator<=(V1f l, V1f r) { return l.v <= r.v; } SIMD_INLINE V1b operator<=(V1i l, V1i r) { return l.v <= r.v; } SIMD_INLINE V1b operator>(V1f l, V1f r) { return l.v > r.v; } SIMD_INLINE V1b operator>(V1i l, V1i r) { return l.v > r.v; } SIMD_INLINE V1b operator>=(V1f l, V1f r) { return l.v >= r.v; } SIMD_INLINE V1b operator>=(V1i l, V1i r) { return l.v >= r.v; } SIMD_INLINE V1b operator!(V1b v) { return !v.v; } SIMD_INLINE V1b operator&(V1b l, V1b r) { return l.v & r.v; } SIMD_INLINE V1b operator|(V1b l, V1b r) { return l.v | r.v; } SIMD_INLINE V1b operator^(V1b l, V1b r) { return l.v ^ r.v; } SIMD_INLINE void operator&=(V1b& l, V1b r) { l.v &= r.v; } SIMD_INLINE void operator|=(V1b& l, V1b r) { l.v |= r.v; } SIMD_INLINE void operator^=(V1b l, V1b r) { l.v ^= r.v; } SIMD_INLINE V1f abs(V1f v) { return fabsf(v.v); } SIMD_INLINE V1f copysign(V1f x, V1f y) { return copysignf(x, y); } SIMD_INLINE V1f flipsign(V1f x, V1f y) { return y.v < 0.f ? -x.v : x.v; } SIMD_INLINE V1f min(V1f l, V1f r) { return l.v < r.v ? l.v : r.v; } SIMD_INLINE V1f max(V1f l, V1f r) { return l.v > r.v ? l.v : r.v; } SIMD_INLINE V1f select(V1f l, V1f r, V1b m) { return m.v ? r.v : l.v; } SIMD_INLINE V1i select(V1i l, V1i r, V1b m) { return m.v ? r.v : l.v; } SIMD_INLINE bool none(V1b v) { return !v.v; } SIMD_INLINE bool any(V1b v) { return v.v; } SIMD_INLINE bool all(V1b v) { return v.v; } SIMD_INLINE void store(V1f v, float* ptr) { *ptr = v.v; } SIMD_INLINE void store(V1i v, int* ptr) { *ptr = v.v; } SIMD_INLINE void loadindexed4(V1f& v0, V1f& v1, V1f& v2, V1f& v3, const void* base, const int indices[1], unsigned int stride) { const float* ptr = reinterpret_cast<const float*>(static_cast<const char*>(base) + indices[0] * stride); v0.v = ptr[0]; v1.v = ptr[1]; v2.v = ptr[2]; v3.v = ptr[3]; } SIMD_INLINE void storeindexed4(const V1f& v0, const V1f& v1, const V1f& v2, const V1f& v3, void* base, const int indices[1], unsigned int stride) { float* ptr = reinterpret_cast<float*>(static_cast<char*>(base) + indices[0] * stride); ptr[0] = v0.v; ptr[1] = v1.v; ptr[2] = v2.v; ptr[3] = v3.v; } SIMD_INLINE void loadindexed8(V1f& v0, V1f& v1, V1f& v2, V1f& v3, V1f& v4, V1f& v5, V1f& v6, V1f& v7, const void* base, const int indices[1], unsigned int stride) { const float* ptr = reinterpret_cast<const float*>(static_cast<const char*>(base) + indices[0] * stride); v0.v = ptr[0]; v1.v = ptr[1]; v2.v = ptr[2]; v3.v = ptr[3]; v4.v = ptr[4]; v5.v = ptr[5]; v6.v = ptr[6]; v7.v = ptr[7]; } } namespace simd { template <> struct VNf_<1> { typedef V1f type; }; template <> struct VNi_<1> { typedef V1i type; }; template <> struct VNb_<1> { typedef V1b type; }; } using simd::V1f; using simd::V1i; using simd::V1b;
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/WorkQueue.cpp
C++
#include "WorkQueue.h" #include "microprofile.h" unsigned int WorkQueue::getIdealWorkerCount() { return std::max(std::thread::hardware_concurrency(), 1u); } WorkQueue::WorkQueue(unsigned int workerCount) { for (unsigned int i = 0; i < workerCount; ++i) workers.emplace_back(workerThreadFun, this, i); } WorkQueue::~WorkQueue() { pushItem(std::shared_ptr<Item>(), workers.size()); for (unsigned int i = 0; i < workers.size(); ++i) workers[i].join(); } void WorkQueue::pushItem(std::shared_ptr<Item> item, int count) { MICROPROFILE_SCOPEI("WorkQueue", "Push", -1); std::unique_lock<std::mutex> lock(itemsMutex); items.push(std::make_pair(std::move(item), count)); lock.unlock(); MICROPROFILE_SCOPEI("WorkQueue", "Notify", -1); if (count > 1) itemsCondition.notify_all(); else itemsCondition.notify_one(); } void WorkQueue::workerThreadFun(WorkQueue* queue, int worker) { char name[16]; sprintf(name, "Worker %d", worker); MicroProfileOnThreadCreate(name); for (;;) { std::shared_ptr<Item> item; { std::unique_lock<std::mutex> lock(queue->itemsMutex); queue->itemsCondition.wait(lock, [&]() { return !queue->items.empty(); }); auto& slot = queue->items.front(); if (slot.second <= 1) { item = std::move(slot.first); queue->items.pop(); } else { item = slot.first; slot.second--; } } if (!item) break; MICROPROFILE_SCOPEI("WorkQueue", "JobRun", 0x606060); item->run(worker); } MicroProfileOnThreadExit(); }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/WorkQueue.h
C/C++ Header
#pragma once #include <vector> #include <thread> #include <functional> #include <queue> #include <mutex> #include <condition_variable> class WorkQueue { public: struct Item { virtual ~Item() {} virtual void run(int worker) = 0; }; static unsigned int getIdealWorkerCount(); WorkQueue(unsigned int workerCount); ~WorkQueue(); void pushItem(std::shared_ptr<Item> item, int count = 1); template <typename F> void pushFunction(F fun, int count = 1) { pushItem(std::make_shared<Item>(std::move(fun))); } unsigned int getWorkerCount() const { return workers.size(); } private: std::vector<std::thread> workers; std::mutex itemsMutex; std::condition_variable itemsCondition; std::queue<std::pair<std::shared_ptr<Item>, int>> items; static void workerThreadFun(WorkQueue* queue, int worker); template <typename T> struct ItemFunction: WorkQueue::Item { T function; ItemFunction(T function): function(std::move(function)) { } void run(int worker) override { function(); } }; };
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/base/microprofile.cpp
C++
#define MICROPROFILE_HELP_ALT "Right-Click" #define MICROPROFILE_HELP_MOD "Ctrl" #ifdef _WIN32 #include "../glad/glad.h" #endif #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> #ifdef __APPLE__ #define GL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED #include <OpenGL/gl3.h> #endif #define MICROPROFILE_WEBSERVER 1 #define MICROPROFILE_GPU_TIMERS_GL 1 #define MICROPROFILE_IMPL #include "microprofile.h" #define MICROPROFILEUI_IMPL #include "microprofileui.h" #define MICROPROFILEDRAW_IMPL #include "microprofiledraw.h" #ifdef __linux__ #define GL_PROC(ret, name, args, argcall) \ ret name args { \ static ret (*ptr) args = reinterpret_cast<ret (*) args>(glfwGetProcAddress(#name)); \ return ptr argcall; \ } GL_PROC(void, glQueryCounter, (GLuint id, GLenum target), (id, target)) GL_PROC(void, glGetQueryObjectui64v, (GLuint id, GLenum pname, GLuint64 *params), (id, pname, params)) #endif
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/glad/glad.c
C
/* OpenGL loader generated by glad 0.1.28 on Mon Nov 26 05:10:02 2018. Language/Generator: C/C++ Specification: gl APIs: gl=4.0 Profile: compatibility Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="compatibility" --api="gl=4.0" --generator="c" --spec="gl" --extensions="" Online: https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "glad.h" static void* get_proc(const char *namez); #if defined(_WIN32) || defined(__CYGWIN__) #include <windows.h> static HMODULE libGL; typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #ifdef _MSC_VER #ifdef __has_include #if __has_include(<winapifamily.h>) #define HAVE_WINAPIFAMILY 1 #endif #elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ #define HAVE_WINAPIFAMILY 1 #endif #endif #ifdef HAVE_WINAPIFAMILY #include <winapifamily.h> #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define IS_UWP 1 #endif #endif static int open_gl(void) { #ifndef IS_UWP libGL = LoadLibraryW(L"opengl32.dll"); if(libGL != NULL) { void (* tmp)(void); tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress"); gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp; return gladGetProcAddressPtr != NULL; } #endif return 0; } static void close_gl(void) { if(libGL != NULL) { FreeLibrary((HMODULE) libGL); libGL = NULL; } } #else #include <dlfcn.h> static void* libGL; #if !defined(__APPLE__) && !defined(__HAIKU__) typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #endif static int open_gl(void) { #ifdef __APPLE__ static const char *NAMES[] = { "../Frameworks/OpenGL.framework/OpenGL", "/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" }; #else static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; #endif unsigned int index = 0; for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); if(libGL != NULL) { #if defined(__APPLE__) || defined(__HAIKU__) return 1; #else gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, "glXGetProcAddressARB"); return gladGetProcAddressPtr != NULL; #endif } } return 0; } static void close_gl(void) { if(libGL != NULL) { dlclose(libGL); libGL = NULL; } } #endif static void* get_proc(const char *namez) { void* result = NULL; if(libGL == NULL) return NULL; #if !defined(__APPLE__) && !defined(__HAIKU__) if(gladGetProcAddressPtr != NULL) { result = gladGetProcAddressPtr(namez); } #endif if(result == NULL) { #if defined(_WIN32) || defined(__CYGWIN__) result = (void*)GetProcAddress((HMODULE) libGL, namez); #else result = dlsym(libGL, namez); #endif } return result; } int gladLoadGL(void) { int status = 0; if(open_gl()) { status = gladLoadGLLoader(&get_proc); close_gl(); } return status; } struct gladGLversionStruct GLVersion = { 0, 0 }; #if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) #define _GLAD_IS_SOME_NEW_VERSION 1 #endif static int max_loaded_major; static int max_loaded_minor; static const char *exts = NULL; static int num_exts_i = 0; static char **exts_i = NULL; static int get_exts(void) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif exts = (const char *)glGetString(GL_EXTENSIONS); #ifdef _GLAD_IS_SOME_NEW_VERSION } else { unsigned int index; num_exts_i = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); if (num_exts_i > 0) { char **tmp_exts_i = (char **)realloc((void *)exts_i, (size_t)num_exts_i * (sizeof *exts_i)); if (tmp_exts_i == NULL) { return 0; } exts_i = tmp_exts_i; } if (exts_i == NULL) { return 0; } for(index = 0; index < (unsigned)num_exts_i; index++) { const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); size_t len = strlen(gl_str_tmp); char *local_str = (char*)malloc((len+1) * sizeof(char)); if(local_str != NULL) { memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); } exts_i[index] = local_str; } } #endif return 1; } static void free_exts(void) { if (exts_i != NULL) { int index; for(index = 0; index < num_exts_i; index++) { free((char *)exts_i[index]); } free((void *)exts_i); exts_i = NULL; } } static int has_ext(const char *ext) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif const char *extensions; const char *loc; const char *terminator; extensions = exts; if(extensions == NULL || ext == NULL) { return 0; } while(1) { loc = strstr(extensions, ext); if(loc == NULL) { return 0; } terminator = loc + strlen(ext); if((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return 1; } extensions = terminator; } #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; if(exts_i == NULL) return 0; for(index = 0; index < num_exts_i; index++) { const char *e = exts_i[index]; if(exts_i[index] != NULL && strcmp(e, ext) == 0) { return 1; } } } #endif return 0; } int GLAD_GL_VERSION_1_0 = 0; int GLAD_GL_VERSION_1_1 = 0; int GLAD_GL_VERSION_1_2 = 0; int GLAD_GL_VERSION_1_3 = 0; int GLAD_GL_VERSION_1_4 = 0; int GLAD_GL_VERSION_1_5 = 0; int GLAD_GL_VERSION_2_0 = 0; int GLAD_GL_VERSION_2_1 = 0; int GLAD_GL_VERSION_3_0 = 0; int GLAD_GL_VERSION_3_1 = 0; int GLAD_GL_VERSION_3_2 = 0; int GLAD_GL_VERSION_3_3 = 0; int GLAD_GL_VERSION_4_0 = 0; PFNGLACCUMPROC glad_glAccum = NULL; PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; PFNGLALPHAFUNCPROC glad_glAlphaFunc = NULL; PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident = NULL; PFNGLARRAYELEMENTPROC glad_glArrayElement = NULL; PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; PFNGLBEGINPROC glad_glBegin = NULL; PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL; PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed = NULL; PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL; PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL; PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL; PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback = NULL; PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; PFNGLBITMAPPROC glad_glBitmap = NULL; PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei = NULL; PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi = NULL; PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei = NULL; PFNGLBLENDFUNCIPROC glad_glBlendFunci = NULL; PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; PFNGLBUFFERDATAPROC glad_glBufferData = NULL; PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; PFNGLCALLLISTPROC glad_glCallList = NULL; PFNGLCALLLISTSPROC glad_glCallLists = NULL; PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; PFNGLCLEARPROC glad_glClear = NULL; PFNGLCLEARACCUMPROC glad_glClearAccum = NULL; PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL; PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL; PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL; PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL; PFNGLCLEARCOLORPROC glad_glClearColor = NULL; PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; PFNGLCLEARINDEXPROC glad_glClearIndex = NULL; PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture = NULL; PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL; PFNGLCLIPPLANEPROC glad_glClipPlane = NULL; PFNGLCOLOR3BPROC glad_glColor3b = NULL; PFNGLCOLOR3BVPROC glad_glColor3bv = NULL; PFNGLCOLOR3DPROC glad_glColor3d = NULL; PFNGLCOLOR3DVPROC glad_glColor3dv = NULL; PFNGLCOLOR3FPROC glad_glColor3f = NULL; PFNGLCOLOR3FVPROC glad_glColor3fv = NULL; PFNGLCOLOR3IPROC glad_glColor3i = NULL; PFNGLCOLOR3IVPROC glad_glColor3iv = NULL; PFNGLCOLOR3SPROC glad_glColor3s = NULL; PFNGLCOLOR3SVPROC glad_glColor3sv = NULL; PFNGLCOLOR3UBPROC glad_glColor3ub = NULL; PFNGLCOLOR3UBVPROC glad_glColor3ubv = NULL; PFNGLCOLOR3UIPROC glad_glColor3ui = NULL; PFNGLCOLOR3UIVPROC glad_glColor3uiv = NULL; PFNGLCOLOR3USPROC glad_glColor3us = NULL; PFNGLCOLOR3USVPROC glad_glColor3usv = NULL; PFNGLCOLOR4BPROC glad_glColor4b = NULL; PFNGLCOLOR4BVPROC glad_glColor4bv = NULL; PFNGLCOLOR4DPROC glad_glColor4d = NULL; PFNGLCOLOR4DVPROC glad_glColor4dv = NULL; PFNGLCOLOR4FPROC glad_glColor4f = NULL; PFNGLCOLOR4FVPROC glad_glColor4fv = NULL; PFNGLCOLOR4IPROC glad_glColor4i = NULL; PFNGLCOLOR4IVPROC glad_glColor4iv = NULL; PFNGLCOLOR4SPROC glad_glColor4s = NULL; PFNGLCOLOR4SVPROC glad_glColor4sv = NULL; PFNGLCOLOR4UBPROC glad_glColor4ub = NULL; PFNGLCOLOR4UBVPROC glad_glColor4ubv = NULL; PFNGLCOLOR4UIPROC glad_glColor4ui = NULL; PFNGLCOLOR4UIVPROC glad_glColor4uiv = NULL; PFNGLCOLOR4USPROC glad_glColor4us = NULL; PFNGLCOLOR4USVPROC glad_glColor4usv = NULL; PFNGLCOLORMASKPROC glad_glColorMask = NULL; PFNGLCOLORMASKIPROC glad_glColorMaski = NULL; PFNGLCOLORMATERIALPROC glad_glColorMaterial = NULL; PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL; PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL; PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL; PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL; PFNGLCOLORPOINTERPROC glad_glColorPointer = NULL; PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL; PFNGLCOPYPIXELSPROC glad_glCopyPixels = NULL; PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; PFNGLCREATESHADERPROC glad_glCreateShader = NULL; PFNGLCULLFACEPROC glad_glCullFace = NULL; PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; PFNGLDELETELISTSPROC glad_glDeleteLists = NULL; PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL; PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; PFNGLDELETESYNCPROC glad_glDeleteSync = NULL; PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks = NULL; PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; PFNGLDISABLEPROC glad_glDisable = NULL; PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState = NULL; PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; PFNGLDISABLEIPROC glad_glDisablei = NULL; PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect = NULL; PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL; PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL; PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect = NULL; PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; PFNGLDRAWPIXELSPROC glad_glDrawPixels = NULL; PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback = NULL; PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream = NULL; PFNGLEDGEFLAGPROC glad_glEdgeFlag = NULL; PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer = NULL; PFNGLEDGEFLAGVPROC glad_glEdgeFlagv = NULL; PFNGLENABLEPROC glad_glEnable = NULL; PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState = NULL; PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; PFNGLENABLEIPROC glad_glEnablei = NULL; PFNGLENDPROC glad_glEnd = NULL; PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL; PFNGLENDLISTPROC glad_glEndList = NULL; PFNGLENDQUERYPROC glad_glEndQuery = NULL; PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed = NULL; PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL; PFNGLEVALCOORD1DPROC glad_glEvalCoord1d = NULL; PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv = NULL; PFNGLEVALCOORD1FPROC glad_glEvalCoord1f = NULL; PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv = NULL; PFNGLEVALCOORD2DPROC glad_glEvalCoord2d = NULL; PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv = NULL; PFNGLEVALCOORD2FPROC glad_glEvalCoord2f = NULL; PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv = NULL; PFNGLEVALMESH1PROC glad_glEvalMesh1 = NULL; PFNGLEVALMESH2PROC glad_glEvalMesh2 = NULL; PFNGLEVALPOINT1PROC glad_glEvalPoint1 = NULL; PFNGLEVALPOINT2PROC glad_glEvalPoint2 = NULL; PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer = NULL; PFNGLFENCESYNCPROC glad_glFenceSync = NULL; PFNGLFINISHPROC glad_glFinish = NULL; PFNGLFLUSHPROC glad_glFlush = NULL; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL; PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer = NULL; PFNGLFOGCOORDDPROC glad_glFogCoordd = NULL; PFNGLFOGCOORDDVPROC glad_glFogCoorddv = NULL; PFNGLFOGCOORDFPROC glad_glFogCoordf = NULL; PFNGLFOGCOORDFVPROC glad_glFogCoordfv = NULL; PFNGLFOGFPROC glad_glFogf = NULL; PFNGLFOGFVPROC glad_glFogfv = NULL; PFNGLFOGIPROC glad_glFogi = NULL; PFNGLFOGIVPROC glad_glFogiv = NULL; PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL; PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; PFNGLFRONTFACEPROC glad_glFrontFace = NULL; PFNGLFRUSTUMPROC glad_glFrustum = NULL; PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; PFNGLGENLISTSPROC glad_glGenLists = NULL; PFNGLGENQUERIESPROC glad_glGenQueries = NULL; PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL; PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks = NULL; PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName = NULL; PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName = NULL; PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv = NULL; PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL; PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL; PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL; PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL; PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL; PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; PFNGLGETCLIPPLANEPROC glad_glGetClipPlane = NULL; PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; PFNGLGETERRORPROC glad_glGetError = NULL; PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL; PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; PFNGLGETLIGHTFVPROC glad_glGetLightfv = NULL; PFNGLGETLIGHTIVPROC glad_glGetLightiv = NULL; PFNGLGETMAPDVPROC glad_glGetMapdv = NULL; PFNGLGETMAPFVPROC glad_glGetMapfv = NULL; PFNGLGETMAPIVPROC glad_glGetMapiv = NULL; PFNGLGETMATERIALFVPROC glad_glGetMaterialfv = NULL; PFNGLGETMATERIALIVPROC glad_glGetMaterialiv = NULL; PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL; PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv = NULL; PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv = NULL; PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv = NULL; PFNGLGETPOINTERVPROC glad_glGetPointerv = NULL; PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple = NULL; PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv = NULL; PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv = NULL; PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL; PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL; PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL; PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL; PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL; PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL; PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; PFNGLGETSTRINGPROC glad_glGetString = NULL; PFNGLGETSTRINGIPROC glad_glGetStringi = NULL; PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex = NULL; PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation = NULL; PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL; PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv = NULL; PFNGLGETTEXENVIVPROC glad_glGetTexEnviv = NULL; PFNGLGETTEXGENDVPROC glad_glGetTexGendv = NULL; PFNGLGETTEXGENFVPROC glad_glGetTexGenfv = NULL; PFNGLGETTEXGENIVPROC glad_glGetTexGeniv = NULL; PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL; PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL; PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL; PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL; PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL; PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv = NULL; PFNGLGETUNIFORMDVPROC glad_glGetUniformdv = NULL; PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL; PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL; PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL; PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; PFNGLHINTPROC glad_glHint = NULL; PFNGLINDEXMASKPROC glad_glIndexMask = NULL; PFNGLINDEXPOINTERPROC glad_glIndexPointer = NULL; PFNGLINDEXDPROC glad_glIndexd = NULL; PFNGLINDEXDVPROC glad_glIndexdv = NULL; PFNGLINDEXFPROC glad_glIndexf = NULL; PFNGLINDEXFVPROC glad_glIndexfv = NULL; PFNGLINDEXIPROC glad_glIndexi = NULL; PFNGLINDEXIVPROC glad_glIndexiv = NULL; PFNGLINDEXSPROC glad_glIndexs = NULL; PFNGLINDEXSVPROC glad_glIndexsv = NULL; PFNGLINDEXUBPROC glad_glIndexub = NULL; PFNGLINDEXUBVPROC glad_glIndexubv = NULL; PFNGLINITNAMESPROC glad_glInitNames = NULL; PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays = NULL; PFNGLISBUFFERPROC glad_glIsBuffer = NULL; PFNGLISENABLEDPROC glad_glIsEnabled = NULL; PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL; PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; PFNGLISLISTPROC glad_glIsList = NULL; PFNGLISPROGRAMPROC glad_glIsProgram = NULL; PFNGLISQUERYPROC glad_glIsQuery = NULL; PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; PFNGLISSAMPLERPROC glad_glIsSampler = NULL; PFNGLISSHADERPROC glad_glIsShader = NULL; PFNGLISSYNCPROC glad_glIsSync = NULL; PFNGLISTEXTUREPROC glad_glIsTexture = NULL; PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback = NULL; PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL; PFNGLLIGHTMODELFPROC glad_glLightModelf = NULL; PFNGLLIGHTMODELFVPROC glad_glLightModelfv = NULL; PFNGLLIGHTMODELIPROC glad_glLightModeli = NULL; PFNGLLIGHTMODELIVPROC glad_glLightModeliv = NULL; PFNGLLIGHTFPROC glad_glLightf = NULL; PFNGLLIGHTFVPROC glad_glLightfv = NULL; PFNGLLIGHTIPROC glad_glLighti = NULL; PFNGLLIGHTIVPROC glad_glLightiv = NULL; PFNGLLINESTIPPLEPROC glad_glLineStipple = NULL; PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; PFNGLLISTBASEPROC glad_glListBase = NULL; PFNGLLOADIDENTITYPROC glad_glLoadIdentity = NULL; PFNGLLOADMATRIXDPROC glad_glLoadMatrixd = NULL; PFNGLLOADMATRIXFPROC glad_glLoadMatrixf = NULL; PFNGLLOADNAMEPROC glad_glLoadName = NULL; PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd = NULL; PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf = NULL; PFNGLLOGICOPPROC glad_glLogicOp = NULL; PFNGLMAP1DPROC glad_glMap1d = NULL; PFNGLMAP1FPROC glad_glMap1f = NULL; PFNGLMAP2DPROC glad_glMap2d = NULL; PFNGLMAP2FPROC glad_glMap2f = NULL; PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL; PFNGLMAPGRID1DPROC glad_glMapGrid1d = NULL; PFNGLMAPGRID1FPROC glad_glMapGrid1f = NULL; PFNGLMAPGRID2DPROC glad_glMapGrid2d = NULL; PFNGLMAPGRID2FPROC glad_glMapGrid2f = NULL; PFNGLMATERIALFPROC glad_glMaterialf = NULL; PFNGLMATERIALFVPROC glad_glMaterialfv = NULL; PFNGLMATERIALIPROC glad_glMateriali = NULL; PFNGLMATERIALIVPROC glad_glMaterialiv = NULL; PFNGLMATRIXMODEPROC glad_glMatrixMode = NULL; PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading = NULL; PFNGLMULTMATRIXDPROC glad_glMultMatrixd = NULL; PFNGLMULTMATRIXFPROC glad_glMultMatrixf = NULL; PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd = NULL; PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf = NULL; PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL; PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d = NULL; PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv = NULL; PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f = NULL; PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv = NULL; PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i = NULL; PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv = NULL; PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s = NULL; PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv = NULL; PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d = NULL; PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv = NULL; PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f = NULL; PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv = NULL; PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i = NULL; PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv = NULL; PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s = NULL; PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv = NULL; PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d = NULL; PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv = NULL; PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f = NULL; PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv = NULL; PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i = NULL; PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv = NULL; PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s = NULL; PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv = NULL; PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d = NULL; PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv = NULL; PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f = NULL; PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv = NULL; PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i = NULL; PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv = NULL; PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s = NULL; PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv = NULL; PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL; PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL; PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL; PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL; PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL; PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL; PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL; PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL; PFNGLNEWLISTPROC glad_glNewList = NULL; PFNGLNORMAL3BPROC glad_glNormal3b = NULL; PFNGLNORMAL3BVPROC glad_glNormal3bv = NULL; PFNGLNORMAL3DPROC glad_glNormal3d = NULL; PFNGLNORMAL3DVPROC glad_glNormal3dv = NULL; PFNGLNORMAL3FPROC glad_glNormal3f = NULL; PFNGLNORMAL3FVPROC glad_glNormal3fv = NULL; PFNGLNORMAL3IPROC glad_glNormal3i = NULL; PFNGLNORMAL3IVPROC glad_glNormal3iv = NULL; PFNGLNORMAL3SPROC glad_glNormal3s = NULL; PFNGLNORMAL3SVPROC glad_glNormal3sv = NULL; PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL; PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL; PFNGLNORMALPOINTERPROC glad_glNormalPointer = NULL; PFNGLORTHOPROC glad_glOrtho = NULL; PFNGLPASSTHROUGHPROC glad_glPassThrough = NULL; PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv = NULL; PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri = NULL; PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback = NULL; PFNGLPIXELMAPFVPROC glad_glPixelMapfv = NULL; PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv = NULL; PFNGLPIXELMAPUSVPROC glad_glPixelMapusv = NULL; PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf = NULL; PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi = NULL; PFNGLPIXELZOOMPROC glad_glPixelZoom = NULL; PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; PFNGLPOINTSIZEPROC glad_glPointSize = NULL; PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple = NULL; PFNGLPOPATTRIBPROC glad_glPopAttrib = NULL; PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib = NULL; PFNGLPOPMATRIXPROC glad_glPopMatrix = NULL; PFNGLPOPNAMEPROC glad_glPopName = NULL; PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL; PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures = NULL; PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL; PFNGLPUSHATTRIBPROC glad_glPushAttrib = NULL; PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib = NULL; PFNGLPUSHMATRIXPROC glad_glPushMatrix = NULL; PFNGLPUSHNAMEPROC glad_glPushName = NULL; PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL; PFNGLRASTERPOS2DPROC glad_glRasterPos2d = NULL; PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv = NULL; PFNGLRASTERPOS2FPROC glad_glRasterPos2f = NULL; PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv = NULL; PFNGLRASTERPOS2IPROC glad_glRasterPos2i = NULL; PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv = NULL; PFNGLRASTERPOS2SPROC glad_glRasterPos2s = NULL; PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv = NULL; PFNGLRASTERPOS3DPROC glad_glRasterPos3d = NULL; PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv = NULL; PFNGLRASTERPOS3FPROC glad_glRasterPos3f = NULL; PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv = NULL; PFNGLRASTERPOS3IPROC glad_glRasterPos3i = NULL; PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv = NULL; PFNGLRASTERPOS3SPROC glad_glRasterPos3s = NULL; PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv = NULL; PFNGLRASTERPOS4DPROC glad_glRasterPos4d = NULL; PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv = NULL; PFNGLRASTERPOS4FPROC glad_glRasterPos4f = NULL; PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv = NULL; PFNGLRASTERPOS4IPROC glad_glRasterPos4i = NULL; PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv = NULL; PFNGLRASTERPOS4SPROC glad_glRasterPos4s = NULL; PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv = NULL; PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; PFNGLREADPIXELSPROC glad_glReadPixels = NULL; PFNGLRECTDPROC glad_glRectd = NULL; PFNGLRECTDVPROC glad_glRectdv = NULL; PFNGLRECTFPROC glad_glRectf = NULL; PFNGLRECTFVPROC glad_glRectfv = NULL; PFNGLRECTIPROC glad_glRecti = NULL; PFNGLRECTIVPROC glad_glRectiv = NULL; PFNGLRECTSPROC glad_glRects = NULL; PFNGLRECTSVPROC glad_glRectsv = NULL; PFNGLRENDERMODEPROC glad_glRenderMode = NULL; PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback = NULL; PFNGLROTATEDPROC glad_glRotated = NULL; PFNGLROTATEFPROC glad_glRotatef = NULL; PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL; PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL; PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL; PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL; PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL; PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL; PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL; PFNGLSCALEDPROC glad_glScaled = NULL; PFNGLSCALEFPROC glad_glScalef = NULL; PFNGLSCISSORPROC glad_glScissor = NULL; PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b = NULL; PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv = NULL; PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d = NULL; PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv = NULL; PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f = NULL; PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv = NULL; PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i = NULL; PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv = NULL; PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s = NULL; PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv = NULL; PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub = NULL; PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv = NULL; PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui = NULL; PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv = NULL; PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us = NULL; PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv = NULL; PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL; PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL; PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer = NULL; PFNGLSELECTBUFFERPROC glad_glSelectBuffer = NULL; PFNGLSHADEMODELPROC glad_glShadeModel = NULL; PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; PFNGLSTENCILOPPROC glad_glStencilOp = NULL; PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL; PFNGLTEXCOORD1DPROC glad_glTexCoord1d = NULL; PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv = NULL; PFNGLTEXCOORD1FPROC glad_glTexCoord1f = NULL; PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv = NULL; PFNGLTEXCOORD1IPROC glad_glTexCoord1i = NULL; PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv = NULL; PFNGLTEXCOORD1SPROC glad_glTexCoord1s = NULL; PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv = NULL; PFNGLTEXCOORD2DPROC glad_glTexCoord2d = NULL; PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv = NULL; PFNGLTEXCOORD2FPROC glad_glTexCoord2f = NULL; PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv = NULL; PFNGLTEXCOORD2IPROC glad_glTexCoord2i = NULL; PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv = NULL; PFNGLTEXCOORD2SPROC glad_glTexCoord2s = NULL; PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv = NULL; PFNGLTEXCOORD3DPROC glad_glTexCoord3d = NULL; PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv = NULL; PFNGLTEXCOORD3FPROC glad_glTexCoord3f = NULL; PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv = NULL; PFNGLTEXCOORD3IPROC glad_glTexCoord3i = NULL; PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv = NULL; PFNGLTEXCOORD3SPROC glad_glTexCoord3s = NULL; PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv = NULL; PFNGLTEXCOORD4DPROC glad_glTexCoord4d = NULL; PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv = NULL; PFNGLTEXCOORD4FPROC glad_glTexCoord4f = NULL; PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv = NULL; PFNGLTEXCOORD4IPROC glad_glTexCoord4i = NULL; PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv = NULL; PFNGLTEXCOORD4SPROC glad_glTexCoord4s = NULL; PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv = NULL; PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL; PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL; PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL; PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL; PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL; PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL; PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL; PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL; PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer = NULL; PFNGLTEXENVFPROC glad_glTexEnvf = NULL; PFNGLTEXENVFVPROC glad_glTexEnvfv = NULL; PFNGLTEXENVIPROC glad_glTexEnvi = NULL; PFNGLTEXENVIVPROC glad_glTexEnviv = NULL; PFNGLTEXGENDPROC glad_glTexGend = NULL; PFNGLTEXGENDVPROC glad_glTexGendv = NULL; PFNGLTEXGENFPROC glad_glTexGenf = NULL; PFNGLTEXGENFVPROC glad_glTexGenfv = NULL; PFNGLTEXGENIPROC glad_glTexGeni = NULL; PFNGLTEXGENIVPROC glad_glTexGeniv = NULL; PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL; PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL; PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL; PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL; PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL; PFNGLTRANSLATEDPROC glad_glTranslated = NULL; PFNGLTRANSLATEFPROC glad_glTranslatef = NULL; PFNGLUNIFORM1DPROC glad_glUniform1d = NULL; PFNGLUNIFORM1DVPROC glad_glUniform1dv = NULL; PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL; PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL; PFNGLUNIFORM2DPROC glad_glUniform2d = NULL; PFNGLUNIFORM2DVPROC glad_glUniform2dv = NULL; PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL; PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL; PFNGLUNIFORM3DPROC glad_glUniform3d = NULL; PFNGLUNIFORM3DVPROC glad_glUniform3dv = NULL; PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL; PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL; PFNGLUNIFORM4DPROC glad_glUniform4d = NULL; PFNGLUNIFORM4DVPROC glad_glUniform4dv = NULL; PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL; PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL; PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL; PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv = NULL; PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv = NULL; PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv = NULL; PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv = NULL; PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv = NULL; PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv = NULL; PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv = NULL; PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv = NULL; PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv = NULL; PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv = NULL; PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; PFNGLVERTEX2DPROC glad_glVertex2d = NULL; PFNGLVERTEX2DVPROC glad_glVertex2dv = NULL; PFNGLVERTEX2FPROC glad_glVertex2f = NULL; PFNGLVERTEX2FVPROC glad_glVertex2fv = NULL; PFNGLVERTEX2IPROC glad_glVertex2i = NULL; PFNGLVERTEX2IVPROC glad_glVertex2iv = NULL; PFNGLVERTEX2SPROC glad_glVertex2s = NULL; PFNGLVERTEX2SVPROC glad_glVertex2sv = NULL; PFNGLVERTEX3DPROC glad_glVertex3d = NULL; PFNGLVERTEX3DVPROC glad_glVertex3dv = NULL; PFNGLVERTEX3FPROC glad_glVertex3f = NULL; PFNGLVERTEX3FVPROC glad_glVertex3fv = NULL; PFNGLVERTEX3IPROC glad_glVertex3i = NULL; PFNGLVERTEX3IVPROC glad_glVertex3iv = NULL; PFNGLVERTEX3SPROC glad_glVertex3s = NULL; PFNGLVERTEX3SVPROC glad_glVertex3sv = NULL; PFNGLVERTEX4DPROC glad_glVertex4d = NULL; PFNGLVERTEX4DVPROC glad_glVertex4dv = NULL; PFNGLVERTEX4FPROC glad_glVertex4f = NULL; PFNGLVERTEX4FVPROC glad_glVertex4fv = NULL; PFNGLVERTEX4IPROC glad_glVertex4i = NULL; PFNGLVERTEX4IVPROC glad_glVertex4iv = NULL; PFNGLVERTEX4SPROC glad_glVertex4s = NULL; PFNGLVERTEX4SVPROC glad_glVertex4sv = NULL; PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL; PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL; PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL; PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL; PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL; PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL; PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL; PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL; PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL; PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL; PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL; PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL; PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL; PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL; PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL; PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL; PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL; PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL; PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL; PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL; PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL; PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL; PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL; PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL; PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL; PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL; PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL; PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL; PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL; PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL; PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL; PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL; PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL; PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL; PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL; PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL; PFNGLVERTEXPOINTERPROC glad_glVertexPointer = NULL; PFNGLVIEWPORTPROC glad_glViewport = NULL; PFNGLWAITSYNCPROC glad_glWaitSync = NULL; PFNGLWINDOWPOS2DPROC glad_glWindowPos2d = NULL; PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv = NULL; PFNGLWINDOWPOS2FPROC glad_glWindowPos2f = NULL; PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv = NULL; PFNGLWINDOWPOS2IPROC glad_glWindowPos2i = NULL; PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv = NULL; PFNGLWINDOWPOS2SPROC glad_glWindowPos2s = NULL; PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv = NULL; PFNGLWINDOWPOS3DPROC glad_glWindowPos3d = NULL; PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv = NULL; PFNGLWINDOWPOS3FPROC glad_glWindowPos3f = NULL; PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv = NULL; PFNGLWINDOWPOS3IPROC glad_glWindowPos3i = NULL; PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv = NULL; PFNGLWINDOWPOS3SPROC glad_glWindowPos3s = NULL; PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv = NULL; static void load_GL_VERSION_1_0(GLADloadproc load) { if(!GLAD_GL_VERSION_1_0) return; glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); glad_glHint = (PFNGLHINTPROC)load("glHint"); glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); glad_glClear = (PFNGLCLEARPROC)load("glClear"); glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); glad_glEnd = (PFNGLENDPROC)load("glEnd"); glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); glad_glRects = (PFNGLRECTSPROC)load("glRects"); glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); } static void load_GL_VERSION_1_1(GLADloadproc load) { if(!GLAD_GL_VERSION_1_1) return; glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); } static void load_GL_VERSION_1_2(GLADloadproc load) { if(!GLAD_GL_VERSION_1_2) return; glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); } static void load_GL_VERSION_1_3(GLADloadproc load) { if(!GLAD_GL_VERSION_1_3) return; glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); } static void load_GL_VERSION_1_4(GLADloadproc load) { if(!GLAD_GL_VERSION_1_4) return; glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); } static void load_GL_VERSION_1_5(GLADloadproc load) { if(!GLAD_GL_VERSION_1_5) return; glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); } static void load_GL_VERSION_2_0(GLADloadproc load) { if(!GLAD_GL_VERSION_2_0) return; glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); } static void load_GL_VERSION_2_1(GLADloadproc load) { if(!GLAD_GL_VERSION_2_1) return; glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); } static void load_GL_VERSION_3_0(GLADloadproc load) { if(!GLAD_GL_VERSION_3_0) return; glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); } static void load_GL_VERSION_3_1(GLADloadproc load) { if(!GLAD_GL_VERSION_3_1) return; glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); } static void load_GL_VERSION_3_2(GLADloadproc load) { if(!GLAD_GL_VERSION_3_2) return; glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); } static void load_GL_VERSION_3_3(GLADloadproc load) { if(!GLAD_GL_VERSION_3_3) return; glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); } static void load_GL_VERSION_4_0(GLADloadproc load) { if(!GLAD_GL_VERSION_4_0) return; glad_glMinSampleShading = (PFNGLMINSAMPLESHADINGPROC)load("glMinSampleShading"); glad_glBlendEquationi = (PFNGLBLENDEQUATIONIPROC)load("glBlendEquationi"); glad_glBlendEquationSeparatei = (PFNGLBLENDEQUATIONSEPARATEIPROC)load("glBlendEquationSeparatei"); glad_glBlendFunci = (PFNGLBLENDFUNCIPROC)load("glBlendFunci"); glad_glBlendFuncSeparatei = (PFNGLBLENDFUNCSEPARATEIPROC)load("glBlendFuncSeparatei"); glad_glDrawArraysIndirect = (PFNGLDRAWARRAYSINDIRECTPROC)load("glDrawArraysIndirect"); glad_glDrawElementsIndirect = (PFNGLDRAWELEMENTSINDIRECTPROC)load("glDrawElementsIndirect"); glad_glUniform1d = (PFNGLUNIFORM1DPROC)load("glUniform1d"); glad_glUniform2d = (PFNGLUNIFORM2DPROC)load("glUniform2d"); glad_glUniform3d = (PFNGLUNIFORM3DPROC)load("glUniform3d"); glad_glUniform4d = (PFNGLUNIFORM4DPROC)load("glUniform4d"); glad_glUniform1dv = (PFNGLUNIFORM1DVPROC)load("glUniform1dv"); glad_glUniform2dv = (PFNGLUNIFORM2DVPROC)load("glUniform2dv"); glad_glUniform3dv = (PFNGLUNIFORM3DVPROC)load("glUniform3dv"); glad_glUniform4dv = (PFNGLUNIFORM4DVPROC)load("glUniform4dv"); glad_glUniformMatrix2dv = (PFNGLUNIFORMMATRIX2DVPROC)load("glUniformMatrix2dv"); glad_glUniformMatrix3dv = (PFNGLUNIFORMMATRIX3DVPROC)load("glUniformMatrix3dv"); glad_glUniformMatrix4dv = (PFNGLUNIFORMMATRIX4DVPROC)load("glUniformMatrix4dv"); glad_glUniformMatrix2x3dv = (PFNGLUNIFORMMATRIX2X3DVPROC)load("glUniformMatrix2x3dv"); glad_glUniformMatrix2x4dv = (PFNGLUNIFORMMATRIX2X4DVPROC)load("glUniformMatrix2x4dv"); glad_glUniformMatrix3x2dv = (PFNGLUNIFORMMATRIX3X2DVPROC)load("glUniformMatrix3x2dv"); glad_glUniformMatrix3x4dv = (PFNGLUNIFORMMATRIX3X4DVPROC)load("glUniformMatrix3x4dv"); glad_glUniformMatrix4x2dv = (PFNGLUNIFORMMATRIX4X2DVPROC)load("glUniformMatrix4x2dv"); glad_glUniformMatrix4x3dv = (PFNGLUNIFORMMATRIX4X3DVPROC)load("glUniformMatrix4x3dv"); glad_glGetUniformdv = (PFNGLGETUNIFORMDVPROC)load("glGetUniformdv"); glad_glGetSubroutineUniformLocation = (PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)load("glGetSubroutineUniformLocation"); glad_glGetSubroutineIndex = (PFNGLGETSUBROUTINEINDEXPROC)load("glGetSubroutineIndex"); glad_glGetActiveSubroutineUniformiv = (PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)load("glGetActiveSubroutineUniformiv"); glad_glGetActiveSubroutineUniformName = (PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)load("glGetActiveSubroutineUniformName"); glad_glGetActiveSubroutineName = (PFNGLGETACTIVESUBROUTINENAMEPROC)load("glGetActiveSubroutineName"); glad_glUniformSubroutinesuiv = (PFNGLUNIFORMSUBROUTINESUIVPROC)load("glUniformSubroutinesuiv"); glad_glGetUniformSubroutineuiv = (PFNGLGETUNIFORMSUBROUTINEUIVPROC)load("glGetUniformSubroutineuiv"); glad_glGetProgramStageiv = (PFNGLGETPROGRAMSTAGEIVPROC)load("glGetProgramStageiv"); glad_glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)load("glPatchParameteri"); glad_glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)load("glPatchParameterfv"); glad_glBindTransformFeedback = (PFNGLBINDTRANSFORMFEEDBACKPROC)load("glBindTransformFeedback"); glad_glDeleteTransformFeedbacks = (PFNGLDELETETRANSFORMFEEDBACKSPROC)load("glDeleteTransformFeedbacks"); glad_glGenTransformFeedbacks = (PFNGLGENTRANSFORMFEEDBACKSPROC)load("glGenTransformFeedbacks"); glad_glIsTransformFeedback = (PFNGLISTRANSFORMFEEDBACKPROC)load("glIsTransformFeedback"); glad_glPauseTransformFeedback = (PFNGLPAUSETRANSFORMFEEDBACKPROC)load("glPauseTransformFeedback"); glad_glResumeTransformFeedback = (PFNGLRESUMETRANSFORMFEEDBACKPROC)load("glResumeTransformFeedback"); glad_glDrawTransformFeedback = (PFNGLDRAWTRANSFORMFEEDBACKPROC)load("glDrawTransformFeedback"); glad_glDrawTransformFeedbackStream = (PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)load("glDrawTransformFeedbackStream"); glad_glBeginQueryIndexed = (PFNGLBEGINQUERYINDEXEDPROC)load("glBeginQueryIndexed"); glad_glEndQueryIndexed = (PFNGLENDQUERYINDEXEDPROC)load("glEndQueryIndexed"); glad_glGetQueryIndexediv = (PFNGLGETQUERYINDEXEDIVPROC)load("glGetQueryIndexediv"); } static int find_extensionsGL(void) { if (!get_exts()) return 0; (void)&has_ext; free_exts(); return 1; } static void find_coreGL(void) { /* Thank you @elmindreda * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 * https://github.com/glfw/glfw/blob/master/src/context.c#L36 */ int i, major, minor; const char* version; const char* prefixes[] = { "OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL }; version = (const char*) glGetString(GL_VERSION); if (!version) return; for (i = 0; prefixes[i]; i++) { const size_t length = strlen(prefixes[i]); if (strncmp(version, prefixes[i], length) == 0) { version += length; break; } } /* PR #18 */ #ifdef _MSC_VER sscanf_s(version, "%d.%d", &major, &minor); #else sscanf(version, "%d.%d", &major, &minor); #endif GLVersion.major = major; GLVersion.minor = minor; max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; GLAD_GL_VERSION_4_0 = (major == 4 && minor >= 0) || major > 4; if (GLVersion.major > 4 || (GLVersion.major >= 4 && GLVersion.minor >= 0)) { max_loaded_major = 4; max_loaded_minor = 0; } } int gladLoadGLLoader(GLADloadproc load) { GLVersion.major = 0; GLVersion.minor = 0; glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); if(glGetString == NULL) return 0; if(glGetString(GL_VERSION) == NULL) return 0; find_coreGL(); load_GL_VERSION_1_0(load); load_GL_VERSION_1_1(load); load_GL_VERSION_1_2(load); load_GL_VERSION_1_3(load); load_GL_VERSION_1_4(load); load_GL_VERSION_1_5(load); load_GL_VERSION_2_0(load); load_GL_VERSION_2_1(load); load_GL_VERSION_3_0(load); load_GL_VERSION_3_1(load); load_GL_VERSION_3_2(load); load_GL_VERSION_3_3(load); load_GL_VERSION_4_0(load); if (!find_extensionsGL()) return 0; return GLVersion.major != 0 || GLVersion.minor != 0; }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/glad/glad.h
C/C++ Header
/* OpenGL loader generated by glad 0.1.28 on Mon Nov 26 05:10:02 2018. Language/Generator: C/C++ Specification: gl APIs: gl=4.0 Profile: compatibility Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="compatibility" --api="gl=4.0" --generator="c" --spec="gl" --extensions="" Online: https://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D4.0 */ #ifndef __glad_h_ #define __glad_h_ #ifdef __gl_h_ #error OpenGL header already included, remove this include, glad already provides it #endif #define __gl_h_ #if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #ifndef NOMINMAX #define NOMINMAX 1 #endif #include <windows.h> #endif #ifndef APIENTRY #define APIENTRY #endif #ifndef APIENTRYP #define APIENTRYP APIENTRY * #endif #ifndef GLAPIENTRY #define GLAPIENTRY APIENTRY #endif #ifdef __cplusplus extern "C" { #endif struct gladGLversionStruct { int major; int minor; }; typedef void* (* GLADloadproc)(const char *name); #ifndef GLAPI # if defined(GLAD_GLAPI_EXPORT) # if defined(_WIN32) || defined(__CYGWIN__) # if defined(GLAD_GLAPI_EXPORT_BUILD) # if defined(__GNUC__) # define GLAPI __attribute__ ((dllexport)) extern # else # define GLAPI __declspec(dllexport) extern # endif # else # if defined(__GNUC__) # define GLAPI __attribute__ ((dllimport)) extern # else # define GLAPI __declspec(dllimport) extern # endif # endif # elif defined(__GNUC__) && defined(GLAD_GLAPI_EXPORT_BUILD) # define GLAPI __attribute__ ((visibility ("default"))) extern # else # define GLAPI extern # endif # else # define GLAPI extern # endif #endif GLAPI struct gladGLversionStruct GLVersion; GLAPI int gladLoadGL(void); GLAPI int gladLoadGLLoader(GLADloadproc); #include "khrplatform.h" typedef unsigned int GLenum; typedef unsigned char GLboolean; typedef unsigned int GLbitfield; typedef void GLvoid; typedef khronos_int8_t GLbyte; typedef khronos_uint8_t GLubyte; typedef khronos_int16_t GLshort; typedef khronos_uint16_t GLushort; typedef int GLint; typedef unsigned int GLuint; typedef khronos_int32_t GLclampx; typedef int GLsizei; typedef khronos_float_t GLfloat; typedef khronos_float_t GLclampf; typedef double GLdouble; typedef double GLclampd; typedef void *GLeglClientBufferEXT; typedef void *GLeglImageOES; typedef char GLchar; typedef char GLcharARB; #ifdef __APPLE__ typedef void *GLhandleARB; #else typedef unsigned int GLhandleARB; #endif typedef khronos_uint16_t GLhalf; typedef khronos_uint16_t GLhalfARB; typedef khronos_int32_t GLfixed; typedef khronos_intptr_t GLintptr; typedef khronos_intptr_t GLintptrARB; typedef khronos_ssize_t GLsizeiptr; typedef khronos_ssize_t GLsizeiptrARB; typedef khronos_int64_t GLint64; typedef khronos_int64_t GLint64EXT; typedef khronos_uint64_t GLuint64; typedef khronos_uint64_t GLuint64EXT; typedef struct __GLsync *GLsync; struct _cl_context; struct _cl_event; typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCKHR)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); typedef unsigned short GLhalfNV; typedef GLintptr GLvdpauSurfaceNV; typedef void (APIENTRY *GLVULKANPROCNV)(void); #define GL_DEPTH_BUFFER_BIT 0x00000100 #define GL_STENCIL_BUFFER_BIT 0x00000400 #define GL_COLOR_BUFFER_BIT 0x00004000 #define GL_FALSE 0 #define GL_TRUE 1 #define GL_POINTS 0x0000 #define GL_LINES 0x0001 #define GL_LINE_LOOP 0x0002 #define GL_LINE_STRIP 0x0003 #define GL_TRIANGLES 0x0004 #define GL_TRIANGLE_STRIP 0x0005 #define GL_TRIANGLE_FAN 0x0006 #define GL_QUADS 0x0007 #define GL_NEVER 0x0200 #define GL_LESS 0x0201 #define GL_EQUAL 0x0202 #define GL_LEQUAL 0x0203 #define GL_GREATER 0x0204 #define GL_NOTEQUAL 0x0205 #define GL_GEQUAL 0x0206 #define GL_ALWAYS 0x0207 #define GL_ZERO 0 #define GL_ONE 1 #define GL_SRC_COLOR 0x0300 #define GL_ONE_MINUS_SRC_COLOR 0x0301 #define GL_SRC_ALPHA 0x0302 #define GL_ONE_MINUS_SRC_ALPHA 0x0303 #define GL_DST_ALPHA 0x0304 #define GL_ONE_MINUS_DST_ALPHA 0x0305 #define GL_DST_COLOR 0x0306 #define GL_ONE_MINUS_DST_COLOR 0x0307 #define GL_SRC_ALPHA_SATURATE 0x0308 #define GL_NONE 0 #define GL_FRONT_LEFT 0x0400 #define GL_FRONT_RIGHT 0x0401 #define GL_BACK_LEFT 0x0402 #define GL_BACK_RIGHT 0x0403 #define GL_FRONT 0x0404 #define GL_BACK 0x0405 #define GL_LEFT 0x0406 #define GL_RIGHT 0x0407 #define GL_FRONT_AND_BACK 0x0408 #define GL_NO_ERROR 0 #define GL_INVALID_ENUM 0x0500 #define GL_INVALID_VALUE 0x0501 #define GL_INVALID_OPERATION 0x0502 #define GL_OUT_OF_MEMORY 0x0505 #define GL_CW 0x0900 #define GL_CCW 0x0901 #define GL_POINT_SIZE 0x0B11 #define GL_POINT_SIZE_RANGE 0x0B12 #define GL_POINT_SIZE_GRANULARITY 0x0B13 #define GL_LINE_SMOOTH 0x0B20 #define GL_LINE_WIDTH 0x0B21 #define GL_LINE_WIDTH_RANGE 0x0B22 #define GL_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_POLYGON_MODE 0x0B40 #define GL_POLYGON_SMOOTH 0x0B41 #define GL_CULL_FACE 0x0B44 #define GL_CULL_FACE_MODE 0x0B45 #define GL_FRONT_FACE 0x0B46 #define GL_DEPTH_RANGE 0x0B70 #define GL_DEPTH_TEST 0x0B71 #define GL_DEPTH_WRITEMASK 0x0B72 #define GL_DEPTH_CLEAR_VALUE 0x0B73 #define GL_DEPTH_FUNC 0x0B74 #define GL_STENCIL_TEST 0x0B90 #define GL_STENCIL_CLEAR_VALUE 0x0B91 #define GL_STENCIL_FUNC 0x0B92 #define GL_STENCIL_VALUE_MASK 0x0B93 #define GL_STENCIL_FAIL 0x0B94 #define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 #define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 #define GL_STENCIL_REF 0x0B97 #define GL_STENCIL_WRITEMASK 0x0B98 #define GL_VIEWPORT 0x0BA2 #define GL_DITHER 0x0BD0 #define GL_BLEND_DST 0x0BE0 #define GL_BLEND_SRC 0x0BE1 #define GL_BLEND 0x0BE2 #define GL_LOGIC_OP_MODE 0x0BF0 #define GL_DRAW_BUFFER 0x0C01 #define GL_READ_BUFFER 0x0C02 #define GL_SCISSOR_BOX 0x0C10 #define GL_SCISSOR_TEST 0x0C11 #define GL_COLOR_CLEAR_VALUE 0x0C22 #define GL_COLOR_WRITEMASK 0x0C23 #define GL_DOUBLEBUFFER 0x0C32 #define GL_STEREO 0x0C33 #define GL_LINE_SMOOTH_HINT 0x0C52 #define GL_POLYGON_SMOOTH_HINT 0x0C53 #define GL_UNPACK_SWAP_BYTES 0x0CF0 #define GL_UNPACK_LSB_FIRST 0x0CF1 #define GL_UNPACK_ROW_LENGTH 0x0CF2 #define GL_UNPACK_SKIP_ROWS 0x0CF3 #define GL_UNPACK_SKIP_PIXELS 0x0CF4 #define GL_UNPACK_ALIGNMENT 0x0CF5 #define GL_PACK_SWAP_BYTES 0x0D00 #define GL_PACK_LSB_FIRST 0x0D01 #define GL_PACK_ROW_LENGTH 0x0D02 #define GL_PACK_SKIP_ROWS 0x0D03 #define GL_PACK_SKIP_PIXELS 0x0D04 #define GL_PACK_ALIGNMENT 0x0D05 #define GL_MAX_TEXTURE_SIZE 0x0D33 #define GL_MAX_VIEWPORT_DIMS 0x0D3A #define GL_SUBPIXEL_BITS 0x0D50 #define GL_TEXTURE_1D 0x0DE0 #define GL_TEXTURE_2D 0x0DE1 #define GL_TEXTURE_WIDTH 0x1000 #define GL_TEXTURE_HEIGHT 0x1001 #define GL_TEXTURE_BORDER_COLOR 0x1004 #define GL_DONT_CARE 0x1100 #define GL_FASTEST 0x1101 #define GL_NICEST 0x1102 #define GL_BYTE 0x1400 #define GL_UNSIGNED_BYTE 0x1401 #define GL_SHORT 0x1402 #define GL_UNSIGNED_SHORT 0x1403 #define GL_INT 0x1404 #define GL_UNSIGNED_INT 0x1405 #define GL_FLOAT 0x1406 #define GL_STACK_OVERFLOW 0x0503 #define GL_STACK_UNDERFLOW 0x0504 #define GL_CLEAR 0x1500 #define GL_AND 0x1501 #define GL_AND_REVERSE 0x1502 #define GL_COPY 0x1503 #define GL_AND_INVERTED 0x1504 #define GL_NOOP 0x1505 #define GL_XOR 0x1506 #define GL_OR 0x1507 #define GL_NOR 0x1508 #define GL_EQUIV 0x1509 #define GL_INVERT 0x150A #define GL_OR_REVERSE 0x150B #define GL_COPY_INVERTED 0x150C #define GL_OR_INVERTED 0x150D #define GL_NAND 0x150E #define GL_SET 0x150F #define GL_TEXTURE 0x1702 #define GL_COLOR 0x1800 #define GL_DEPTH 0x1801 #define GL_STENCIL 0x1802 #define GL_STENCIL_INDEX 0x1901 #define GL_DEPTH_COMPONENT 0x1902 #define GL_RED 0x1903 #define GL_GREEN 0x1904 #define GL_BLUE 0x1905 #define GL_ALPHA 0x1906 #define GL_RGB 0x1907 #define GL_RGBA 0x1908 #define GL_POINT 0x1B00 #define GL_LINE 0x1B01 #define GL_FILL 0x1B02 #define GL_KEEP 0x1E00 #define GL_REPLACE 0x1E01 #define GL_INCR 0x1E02 #define GL_DECR 0x1E03 #define GL_VENDOR 0x1F00 #define GL_RENDERER 0x1F01 #define GL_VERSION 0x1F02 #define GL_EXTENSIONS 0x1F03 #define GL_NEAREST 0x2600 #define GL_LINEAR 0x2601 #define GL_NEAREST_MIPMAP_NEAREST 0x2700 #define GL_LINEAR_MIPMAP_NEAREST 0x2701 #define GL_NEAREST_MIPMAP_LINEAR 0x2702 #define GL_LINEAR_MIPMAP_LINEAR 0x2703 #define GL_TEXTURE_MAG_FILTER 0x2800 #define GL_TEXTURE_MIN_FILTER 0x2801 #define GL_TEXTURE_WRAP_S 0x2802 #define GL_TEXTURE_WRAP_T 0x2803 #define GL_REPEAT 0x2901 #define GL_CURRENT_BIT 0x00000001 #define GL_POINT_BIT 0x00000002 #define GL_LINE_BIT 0x00000004 #define GL_POLYGON_BIT 0x00000008 #define GL_POLYGON_STIPPLE_BIT 0x00000010 #define GL_PIXEL_MODE_BIT 0x00000020 #define GL_LIGHTING_BIT 0x00000040 #define GL_FOG_BIT 0x00000080 #define GL_ACCUM_BUFFER_BIT 0x00000200 #define GL_VIEWPORT_BIT 0x00000800 #define GL_TRANSFORM_BIT 0x00001000 #define GL_ENABLE_BIT 0x00002000 #define GL_HINT_BIT 0x00008000 #define GL_EVAL_BIT 0x00010000 #define GL_LIST_BIT 0x00020000 #define GL_TEXTURE_BIT 0x00040000 #define GL_SCISSOR_BIT 0x00080000 #define GL_ALL_ATTRIB_BITS 0xFFFFFFFF #define GL_QUAD_STRIP 0x0008 #define GL_POLYGON 0x0009 #define GL_ACCUM 0x0100 #define GL_LOAD 0x0101 #define GL_RETURN 0x0102 #define GL_MULT 0x0103 #define GL_ADD 0x0104 #define GL_AUX0 0x0409 #define GL_AUX1 0x040A #define GL_AUX2 0x040B #define GL_AUX3 0x040C #define GL_2D 0x0600 #define GL_3D 0x0601 #define GL_3D_COLOR 0x0602 #define GL_3D_COLOR_TEXTURE 0x0603 #define GL_4D_COLOR_TEXTURE 0x0604 #define GL_PASS_THROUGH_TOKEN 0x0700 #define GL_POINT_TOKEN 0x0701 #define GL_LINE_TOKEN 0x0702 #define GL_POLYGON_TOKEN 0x0703 #define GL_BITMAP_TOKEN 0x0704 #define GL_DRAW_PIXEL_TOKEN 0x0705 #define GL_COPY_PIXEL_TOKEN 0x0706 #define GL_LINE_RESET_TOKEN 0x0707 #define GL_EXP 0x0800 #define GL_EXP2 0x0801 #define GL_COEFF 0x0A00 #define GL_ORDER 0x0A01 #define GL_DOMAIN 0x0A02 #define GL_PIXEL_MAP_I_TO_I 0x0C70 #define GL_PIXEL_MAP_S_TO_S 0x0C71 #define GL_PIXEL_MAP_I_TO_R 0x0C72 #define GL_PIXEL_MAP_I_TO_G 0x0C73 #define GL_PIXEL_MAP_I_TO_B 0x0C74 #define GL_PIXEL_MAP_I_TO_A 0x0C75 #define GL_PIXEL_MAP_R_TO_R 0x0C76 #define GL_PIXEL_MAP_G_TO_G 0x0C77 #define GL_PIXEL_MAP_B_TO_B 0x0C78 #define GL_PIXEL_MAP_A_TO_A 0x0C79 #define GL_CURRENT_COLOR 0x0B00 #define GL_CURRENT_INDEX 0x0B01 #define GL_CURRENT_NORMAL 0x0B02 #define GL_CURRENT_TEXTURE_COORDS 0x0B03 #define GL_CURRENT_RASTER_COLOR 0x0B04 #define GL_CURRENT_RASTER_INDEX 0x0B05 #define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 #define GL_CURRENT_RASTER_POSITION 0x0B07 #define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 #define GL_CURRENT_RASTER_DISTANCE 0x0B09 #define GL_POINT_SMOOTH 0x0B10 #define GL_LINE_STIPPLE 0x0B24 #define GL_LINE_STIPPLE_PATTERN 0x0B25 #define GL_LINE_STIPPLE_REPEAT 0x0B26 #define GL_LIST_MODE 0x0B30 #define GL_MAX_LIST_NESTING 0x0B31 #define GL_LIST_BASE 0x0B32 #define GL_LIST_INDEX 0x0B33 #define GL_POLYGON_STIPPLE 0x0B42 #define GL_EDGE_FLAG 0x0B43 #define GL_LIGHTING 0x0B50 #define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 #define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 #define GL_LIGHT_MODEL_AMBIENT 0x0B53 #define GL_SHADE_MODEL 0x0B54 #define GL_COLOR_MATERIAL_FACE 0x0B55 #define GL_COLOR_MATERIAL_PARAMETER 0x0B56 #define GL_COLOR_MATERIAL 0x0B57 #define GL_FOG 0x0B60 #define GL_FOG_INDEX 0x0B61 #define GL_FOG_DENSITY 0x0B62 #define GL_FOG_START 0x0B63 #define GL_FOG_END 0x0B64 #define GL_FOG_MODE 0x0B65 #define GL_FOG_COLOR 0x0B66 #define GL_ACCUM_CLEAR_VALUE 0x0B80 #define GL_MATRIX_MODE 0x0BA0 #define GL_NORMALIZE 0x0BA1 #define GL_MODELVIEW_STACK_DEPTH 0x0BA3 #define GL_PROJECTION_STACK_DEPTH 0x0BA4 #define GL_TEXTURE_STACK_DEPTH 0x0BA5 #define GL_MODELVIEW_MATRIX 0x0BA6 #define GL_PROJECTION_MATRIX 0x0BA7 #define GL_TEXTURE_MATRIX 0x0BA8 #define GL_ATTRIB_STACK_DEPTH 0x0BB0 #define GL_ALPHA_TEST 0x0BC0 #define GL_ALPHA_TEST_FUNC 0x0BC1 #define GL_ALPHA_TEST_REF 0x0BC2 #define GL_LOGIC_OP 0x0BF1 #define GL_AUX_BUFFERS 0x0C00 #define GL_INDEX_CLEAR_VALUE 0x0C20 #define GL_INDEX_WRITEMASK 0x0C21 #define GL_INDEX_MODE 0x0C30 #define GL_RGBA_MODE 0x0C31 #define GL_RENDER_MODE 0x0C40 #define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 #define GL_POINT_SMOOTH_HINT 0x0C51 #define GL_FOG_HINT 0x0C54 #define GL_TEXTURE_GEN_S 0x0C60 #define GL_TEXTURE_GEN_T 0x0C61 #define GL_TEXTURE_GEN_R 0x0C62 #define GL_TEXTURE_GEN_Q 0x0C63 #define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 #define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 #define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 #define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 #define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 #define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 #define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 #define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 #define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 #define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 #define GL_MAP_COLOR 0x0D10 #define GL_MAP_STENCIL 0x0D11 #define GL_INDEX_SHIFT 0x0D12 #define GL_INDEX_OFFSET 0x0D13 #define GL_RED_SCALE 0x0D14 #define GL_RED_BIAS 0x0D15 #define GL_ZOOM_X 0x0D16 #define GL_ZOOM_Y 0x0D17 #define GL_GREEN_SCALE 0x0D18 #define GL_GREEN_BIAS 0x0D19 #define GL_BLUE_SCALE 0x0D1A #define GL_BLUE_BIAS 0x0D1B #define GL_ALPHA_SCALE 0x0D1C #define GL_ALPHA_BIAS 0x0D1D #define GL_DEPTH_SCALE 0x0D1E #define GL_DEPTH_BIAS 0x0D1F #define GL_MAX_EVAL_ORDER 0x0D30 #define GL_MAX_LIGHTS 0x0D31 #define GL_MAX_CLIP_PLANES 0x0D32 #define GL_MAX_PIXEL_MAP_TABLE 0x0D34 #define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 #define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 #define GL_MAX_NAME_STACK_DEPTH 0x0D37 #define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 #define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 #define GL_INDEX_BITS 0x0D51 #define GL_RED_BITS 0x0D52 #define GL_GREEN_BITS 0x0D53 #define GL_BLUE_BITS 0x0D54 #define GL_ALPHA_BITS 0x0D55 #define GL_DEPTH_BITS 0x0D56 #define GL_STENCIL_BITS 0x0D57 #define GL_ACCUM_RED_BITS 0x0D58 #define GL_ACCUM_GREEN_BITS 0x0D59 #define GL_ACCUM_BLUE_BITS 0x0D5A #define GL_ACCUM_ALPHA_BITS 0x0D5B #define GL_NAME_STACK_DEPTH 0x0D70 #define GL_AUTO_NORMAL 0x0D80 #define GL_MAP1_COLOR_4 0x0D90 #define GL_MAP1_INDEX 0x0D91 #define GL_MAP1_NORMAL 0x0D92 #define GL_MAP1_TEXTURE_COORD_1 0x0D93 #define GL_MAP1_TEXTURE_COORD_2 0x0D94 #define GL_MAP1_TEXTURE_COORD_3 0x0D95 #define GL_MAP1_TEXTURE_COORD_4 0x0D96 #define GL_MAP1_VERTEX_3 0x0D97 #define GL_MAP1_VERTEX_4 0x0D98 #define GL_MAP2_COLOR_4 0x0DB0 #define GL_MAP2_INDEX 0x0DB1 #define GL_MAP2_NORMAL 0x0DB2 #define GL_MAP2_TEXTURE_COORD_1 0x0DB3 #define GL_MAP2_TEXTURE_COORD_2 0x0DB4 #define GL_MAP2_TEXTURE_COORD_3 0x0DB5 #define GL_MAP2_TEXTURE_COORD_4 0x0DB6 #define GL_MAP2_VERTEX_3 0x0DB7 #define GL_MAP2_VERTEX_4 0x0DB8 #define GL_MAP1_GRID_DOMAIN 0x0DD0 #define GL_MAP1_GRID_SEGMENTS 0x0DD1 #define GL_MAP2_GRID_DOMAIN 0x0DD2 #define GL_MAP2_GRID_SEGMENTS 0x0DD3 #define GL_TEXTURE_COMPONENTS 0x1003 #define GL_TEXTURE_BORDER 0x1005 #define GL_AMBIENT 0x1200 #define GL_DIFFUSE 0x1201 #define GL_SPECULAR 0x1202 #define GL_POSITION 0x1203 #define GL_SPOT_DIRECTION 0x1204 #define GL_SPOT_EXPONENT 0x1205 #define GL_SPOT_CUTOFF 0x1206 #define GL_CONSTANT_ATTENUATION 0x1207 #define GL_LINEAR_ATTENUATION 0x1208 #define GL_QUADRATIC_ATTENUATION 0x1209 #define GL_COMPILE 0x1300 #define GL_COMPILE_AND_EXECUTE 0x1301 #define GL_2_BYTES 0x1407 #define GL_3_BYTES 0x1408 #define GL_4_BYTES 0x1409 #define GL_EMISSION 0x1600 #define GL_SHININESS 0x1601 #define GL_AMBIENT_AND_DIFFUSE 0x1602 #define GL_COLOR_INDEXES 0x1603 #define GL_MODELVIEW 0x1700 #define GL_PROJECTION 0x1701 #define GL_COLOR_INDEX 0x1900 #define GL_LUMINANCE 0x1909 #define GL_LUMINANCE_ALPHA 0x190A #define GL_BITMAP 0x1A00 #define GL_RENDER 0x1C00 #define GL_FEEDBACK 0x1C01 #define GL_SELECT 0x1C02 #define GL_FLAT 0x1D00 #define GL_SMOOTH 0x1D01 #define GL_S 0x2000 #define GL_T 0x2001 #define GL_R 0x2002 #define GL_Q 0x2003 #define GL_MODULATE 0x2100 #define GL_DECAL 0x2101 #define GL_TEXTURE_ENV_MODE 0x2200 #define GL_TEXTURE_ENV_COLOR 0x2201 #define GL_TEXTURE_ENV 0x2300 #define GL_EYE_LINEAR 0x2400 #define GL_OBJECT_LINEAR 0x2401 #define GL_SPHERE_MAP 0x2402 #define GL_TEXTURE_GEN_MODE 0x2500 #define GL_OBJECT_PLANE 0x2501 #define GL_EYE_PLANE 0x2502 #define GL_CLAMP 0x2900 #define GL_CLIP_PLANE0 0x3000 #define GL_CLIP_PLANE1 0x3001 #define GL_CLIP_PLANE2 0x3002 #define GL_CLIP_PLANE3 0x3003 #define GL_CLIP_PLANE4 0x3004 #define GL_CLIP_PLANE5 0x3005 #define GL_LIGHT0 0x4000 #define GL_LIGHT1 0x4001 #define GL_LIGHT2 0x4002 #define GL_LIGHT3 0x4003 #define GL_LIGHT4 0x4004 #define GL_LIGHT5 0x4005 #define GL_LIGHT6 0x4006 #define GL_LIGHT7 0x4007 #define GL_COLOR_LOGIC_OP 0x0BF2 #define GL_POLYGON_OFFSET_UNITS 0x2A00 #define GL_POLYGON_OFFSET_POINT 0x2A01 #define GL_POLYGON_OFFSET_LINE 0x2A02 #define GL_POLYGON_OFFSET_FILL 0x8037 #define GL_POLYGON_OFFSET_FACTOR 0x8038 #define GL_TEXTURE_BINDING_1D 0x8068 #define GL_TEXTURE_BINDING_2D 0x8069 #define GL_TEXTURE_INTERNAL_FORMAT 0x1003 #define GL_TEXTURE_RED_SIZE 0x805C #define GL_TEXTURE_GREEN_SIZE 0x805D #define GL_TEXTURE_BLUE_SIZE 0x805E #define GL_TEXTURE_ALPHA_SIZE 0x805F #define GL_DOUBLE 0x140A #define GL_PROXY_TEXTURE_1D 0x8063 #define GL_PROXY_TEXTURE_2D 0x8064 #define GL_R3_G3_B2 0x2A10 #define GL_RGB4 0x804F #define GL_RGB5 0x8050 #define GL_RGB8 0x8051 #define GL_RGB10 0x8052 #define GL_RGB12 0x8053 #define GL_RGB16 0x8054 #define GL_RGBA2 0x8055 #define GL_RGBA4 0x8056 #define GL_RGB5_A1 0x8057 #define GL_RGBA8 0x8058 #define GL_RGB10_A2 0x8059 #define GL_RGBA12 0x805A #define GL_RGBA16 0x805B #define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 #define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 #define GL_CLIENT_ALL_ATTRIB_BITS 0xFFFFFFFF #define GL_VERTEX_ARRAY_POINTER 0x808E #define GL_NORMAL_ARRAY_POINTER 0x808F #define GL_COLOR_ARRAY_POINTER 0x8090 #define GL_INDEX_ARRAY_POINTER 0x8091 #define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 #define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 #define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 #define GL_SELECTION_BUFFER_POINTER 0x0DF3 #define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 #define GL_INDEX_LOGIC_OP 0x0BF1 #define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B #define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 #define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 #define GL_SELECTION_BUFFER_SIZE 0x0DF4 #define GL_VERTEX_ARRAY 0x8074 #define GL_NORMAL_ARRAY 0x8075 #define GL_COLOR_ARRAY 0x8076 #define GL_INDEX_ARRAY 0x8077 #define GL_TEXTURE_COORD_ARRAY 0x8078 #define GL_EDGE_FLAG_ARRAY 0x8079 #define GL_VERTEX_ARRAY_SIZE 0x807A #define GL_VERTEX_ARRAY_TYPE 0x807B #define GL_VERTEX_ARRAY_STRIDE 0x807C #define GL_NORMAL_ARRAY_TYPE 0x807E #define GL_NORMAL_ARRAY_STRIDE 0x807F #define GL_COLOR_ARRAY_SIZE 0x8081 #define GL_COLOR_ARRAY_TYPE 0x8082 #define GL_COLOR_ARRAY_STRIDE 0x8083 #define GL_INDEX_ARRAY_TYPE 0x8085 #define GL_INDEX_ARRAY_STRIDE 0x8086 #define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 #define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 #define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A #define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C #define GL_TEXTURE_LUMINANCE_SIZE 0x8060 #define GL_TEXTURE_INTENSITY_SIZE 0x8061 #define GL_TEXTURE_PRIORITY 0x8066 #define GL_TEXTURE_RESIDENT 0x8067 #define GL_ALPHA4 0x803B #define GL_ALPHA8 0x803C #define GL_ALPHA12 0x803D #define GL_ALPHA16 0x803E #define GL_LUMINANCE4 0x803F #define GL_LUMINANCE8 0x8040 #define GL_LUMINANCE12 0x8041 #define GL_LUMINANCE16 0x8042 #define GL_LUMINANCE4_ALPHA4 0x8043 #define GL_LUMINANCE6_ALPHA2 0x8044 #define GL_LUMINANCE8_ALPHA8 0x8045 #define GL_LUMINANCE12_ALPHA4 0x8046 #define GL_LUMINANCE12_ALPHA12 0x8047 #define GL_LUMINANCE16_ALPHA16 0x8048 #define GL_INTENSITY 0x8049 #define GL_INTENSITY4 0x804A #define GL_INTENSITY8 0x804B #define GL_INTENSITY12 0x804C #define GL_INTENSITY16 0x804D #define GL_V2F 0x2A20 #define GL_V3F 0x2A21 #define GL_C4UB_V2F 0x2A22 #define GL_C4UB_V3F 0x2A23 #define GL_C3F_V3F 0x2A24 #define GL_N3F_V3F 0x2A25 #define GL_C4F_N3F_V3F 0x2A26 #define GL_T2F_V3F 0x2A27 #define GL_T4F_V4F 0x2A28 #define GL_T2F_C4UB_V3F 0x2A29 #define GL_T2F_C3F_V3F 0x2A2A #define GL_T2F_N3F_V3F 0x2A2B #define GL_T2F_C4F_N3F_V3F 0x2A2C #define GL_T4F_C4F_N3F_V4F 0x2A2D #define GL_UNSIGNED_BYTE_3_3_2 0x8032 #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 #define GL_UNSIGNED_INT_8_8_8_8 0x8035 #define GL_UNSIGNED_INT_10_10_10_2 0x8036 #define GL_TEXTURE_BINDING_3D 0x806A #define GL_PACK_SKIP_IMAGES 0x806B #define GL_PACK_IMAGE_HEIGHT 0x806C #define GL_UNPACK_SKIP_IMAGES 0x806D #define GL_UNPACK_IMAGE_HEIGHT 0x806E #define GL_TEXTURE_3D 0x806F #define GL_PROXY_TEXTURE_3D 0x8070 #define GL_TEXTURE_DEPTH 0x8071 #define GL_TEXTURE_WRAP_R 0x8072 #define GL_MAX_3D_TEXTURE_SIZE 0x8073 #define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 #define GL_UNSIGNED_SHORT_5_6_5 0x8363 #define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 #define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 #define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 #define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 #define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 #define GL_BGR 0x80E0 #define GL_BGRA 0x80E1 #define GL_MAX_ELEMENTS_VERTICES 0x80E8 #define GL_MAX_ELEMENTS_INDICES 0x80E9 #define GL_CLAMP_TO_EDGE 0x812F #define GL_TEXTURE_MIN_LOD 0x813A #define GL_TEXTURE_MAX_LOD 0x813B #define GL_TEXTURE_BASE_LEVEL 0x813C #define GL_TEXTURE_MAX_LEVEL 0x813D #define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 #define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 #define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 #define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 #define GL_ALIASED_LINE_WIDTH_RANGE 0x846E #define GL_RESCALE_NORMAL 0x803A #define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 #define GL_SINGLE_COLOR 0x81F9 #define GL_SEPARATE_SPECULAR_COLOR 0x81FA #define GL_ALIASED_POINT_SIZE_RANGE 0x846D #define GL_TEXTURE0 0x84C0 #define GL_TEXTURE1 0x84C1 #define GL_TEXTURE2 0x84C2 #define GL_TEXTURE3 0x84C3 #define GL_TEXTURE4 0x84C4 #define GL_TEXTURE5 0x84C5 #define GL_TEXTURE6 0x84C6 #define GL_TEXTURE7 0x84C7 #define GL_TEXTURE8 0x84C8 #define GL_TEXTURE9 0x84C9 #define GL_TEXTURE10 0x84CA #define GL_TEXTURE11 0x84CB #define GL_TEXTURE12 0x84CC #define GL_TEXTURE13 0x84CD #define GL_TEXTURE14 0x84CE #define GL_TEXTURE15 0x84CF #define GL_TEXTURE16 0x84D0 #define GL_TEXTURE17 0x84D1 #define GL_TEXTURE18 0x84D2 #define GL_TEXTURE19 0x84D3 #define GL_TEXTURE20 0x84D4 #define GL_TEXTURE21 0x84D5 #define GL_TEXTURE22 0x84D6 #define GL_TEXTURE23 0x84D7 #define GL_TEXTURE24 0x84D8 #define GL_TEXTURE25 0x84D9 #define GL_TEXTURE26 0x84DA #define GL_TEXTURE27 0x84DB #define GL_TEXTURE28 0x84DC #define GL_TEXTURE29 0x84DD #define GL_TEXTURE30 0x84DE #define GL_TEXTURE31 0x84DF #define GL_ACTIVE_TEXTURE 0x84E0 #define GL_MULTISAMPLE 0x809D #define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E #define GL_SAMPLE_ALPHA_TO_ONE 0x809F #define GL_SAMPLE_COVERAGE 0x80A0 #define GL_SAMPLE_BUFFERS 0x80A8 #define GL_SAMPLES 0x80A9 #define GL_SAMPLE_COVERAGE_VALUE 0x80AA #define GL_SAMPLE_COVERAGE_INVERT 0x80AB #define GL_TEXTURE_CUBE_MAP 0x8513 #define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 #define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 #define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 #define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A #define GL_PROXY_TEXTURE_CUBE_MAP 0x851B #define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C #define GL_COMPRESSED_RGB 0x84ED #define GL_COMPRESSED_RGBA 0x84EE #define GL_TEXTURE_COMPRESSION_HINT 0x84EF #define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 #define GL_TEXTURE_COMPRESSED 0x86A1 #define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 #define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 #define GL_CLAMP_TO_BORDER 0x812D #define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 #define GL_MAX_TEXTURE_UNITS 0x84E2 #define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 #define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 #define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 #define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 #define GL_MULTISAMPLE_BIT 0x20000000 #define GL_NORMAL_MAP 0x8511 #define GL_REFLECTION_MAP 0x8512 #define GL_COMPRESSED_ALPHA 0x84E9 #define GL_COMPRESSED_LUMINANCE 0x84EA #define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB #define GL_COMPRESSED_INTENSITY 0x84EC #define GL_COMBINE 0x8570 #define GL_COMBINE_RGB 0x8571 #define GL_COMBINE_ALPHA 0x8572 #define GL_SOURCE0_RGB 0x8580 #define GL_SOURCE1_RGB 0x8581 #define GL_SOURCE2_RGB 0x8582 #define GL_SOURCE0_ALPHA 0x8588 #define GL_SOURCE1_ALPHA 0x8589 #define GL_SOURCE2_ALPHA 0x858A #define GL_OPERAND0_RGB 0x8590 #define GL_OPERAND1_RGB 0x8591 #define GL_OPERAND2_RGB 0x8592 #define GL_OPERAND0_ALPHA 0x8598 #define GL_OPERAND1_ALPHA 0x8599 #define GL_OPERAND2_ALPHA 0x859A #define GL_RGB_SCALE 0x8573 #define GL_ADD_SIGNED 0x8574 #define GL_INTERPOLATE 0x8575 #define GL_SUBTRACT 0x84E7 #define GL_CONSTANT 0x8576 #define GL_PRIMARY_COLOR 0x8577 #define GL_PREVIOUS 0x8578 #define GL_DOT3_RGB 0x86AE #define GL_DOT3_RGBA 0x86AF #define GL_BLEND_DST_RGB 0x80C8 #define GL_BLEND_SRC_RGB 0x80C9 #define GL_BLEND_DST_ALPHA 0x80CA #define GL_BLEND_SRC_ALPHA 0x80CB #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #define GL_MIRRORED_REPEAT 0x8370 #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_LOD_BIAS 0x8501 #define GL_INCR_WRAP 0x8507 #define GL_DECR_WRAP 0x8508 #define GL_TEXTURE_DEPTH_SIZE 0x884A #define GL_TEXTURE_COMPARE_MODE 0x884C #define GL_TEXTURE_COMPARE_FUNC 0x884D #define GL_POINT_SIZE_MIN 0x8126 #define GL_POINT_SIZE_MAX 0x8127 #define GL_POINT_DISTANCE_ATTENUATION 0x8129 #define GL_GENERATE_MIPMAP 0x8191 #define GL_GENERATE_MIPMAP_HINT 0x8192 #define GL_FOG_COORDINATE_SOURCE 0x8450 #define GL_FOG_COORDINATE 0x8451 #define GL_FRAGMENT_DEPTH 0x8452 #define GL_CURRENT_FOG_COORDINATE 0x8453 #define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 #define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 #define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 #define GL_FOG_COORDINATE_ARRAY 0x8457 #define GL_COLOR_SUM 0x8458 #define GL_CURRENT_SECONDARY_COLOR 0x8459 #define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A #define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B #define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C #define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D #define GL_SECONDARY_COLOR_ARRAY 0x845E #define GL_TEXTURE_FILTER_CONTROL 0x8500 #define GL_DEPTH_TEXTURE_MODE 0x884B #define GL_COMPARE_R_TO_TEXTURE 0x884E #define GL_BLEND_COLOR 0x8005 #define GL_BLEND_EQUATION 0x8009 #define GL_CONSTANT_COLOR 0x8001 #define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 #define GL_CONSTANT_ALPHA 0x8003 #define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 #define GL_FUNC_ADD 0x8006 #define GL_FUNC_REVERSE_SUBTRACT 0x800B #define GL_FUNC_SUBTRACT 0x800A #define GL_MIN 0x8007 #define GL_MAX 0x8008 #define GL_BUFFER_SIZE 0x8764 #define GL_BUFFER_USAGE 0x8765 #define GL_QUERY_COUNTER_BITS 0x8864 #define GL_CURRENT_QUERY 0x8865 #define GL_QUERY_RESULT 0x8866 #define GL_QUERY_RESULT_AVAILABLE 0x8867 #define GL_ARRAY_BUFFER 0x8892 #define GL_ELEMENT_ARRAY_BUFFER 0x8893 #define GL_ARRAY_BUFFER_BINDING 0x8894 #define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 #define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F #define GL_READ_ONLY 0x88B8 #define GL_WRITE_ONLY 0x88B9 #define GL_READ_WRITE 0x88BA #define GL_BUFFER_ACCESS 0x88BB #define GL_BUFFER_MAPPED 0x88BC #define GL_BUFFER_MAP_POINTER 0x88BD #define GL_STREAM_DRAW 0x88E0 #define GL_STREAM_READ 0x88E1 #define GL_STREAM_COPY 0x88E2 #define GL_STATIC_DRAW 0x88E4 #define GL_STATIC_READ 0x88E5 #define GL_STATIC_COPY 0x88E6 #define GL_DYNAMIC_DRAW 0x88E8 #define GL_DYNAMIC_READ 0x88E9 #define GL_DYNAMIC_COPY 0x88EA #define GL_SAMPLES_PASSED 0x8914 #define GL_SRC1_ALPHA 0x8589 #define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 #define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 #define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 #define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 #define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A #define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B #define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C #define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D #define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E #define GL_FOG_COORD_SRC 0x8450 #define GL_FOG_COORD 0x8451 #define GL_CURRENT_FOG_COORD 0x8453 #define GL_FOG_COORD_ARRAY_TYPE 0x8454 #define GL_FOG_COORD_ARRAY_STRIDE 0x8455 #define GL_FOG_COORD_ARRAY_POINTER 0x8456 #define GL_FOG_COORD_ARRAY 0x8457 #define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D #define GL_SRC0_RGB 0x8580 #define GL_SRC1_RGB 0x8581 #define GL_SRC2_RGB 0x8582 #define GL_SRC0_ALPHA 0x8588 #define GL_SRC2_ALPHA 0x858A #define GL_BLEND_EQUATION_RGB 0x8009 #define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 #define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 #define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 #define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 #define GL_CURRENT_VERTEX_ATTRIB 0x8626 #define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 #define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 #define GL_STENCIL_BACK_FUNC 0x8800 #define GL_STENCIL_BACK_FAIL 0x8801 #define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 #define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 #define GL_MAX_DRAW_BUFFERS 0x8824 #define GL_DRAW_BUFFER0 0x8825 #define GL_DRAW_BUFFER1 0x8826 #define GL_DRAW_BUFFER2 0x8827 #define GL_DRAW_BUFFER3 0x8828 #define GL_DRAW_BUFFER4 0x8829 #define GL_DRAW_BUFFER5 0x882A #define GL_DRAW_BUFFER6 0x882B #define GL_DRAW_BUFFER7 0x882C #define GL_DRAW_BUFFER8 0x882D #define GL_DRAW_BUFFER9 0x882E #define GL_DRAW_BUFFER10 0x882F #define GL_DRAW_BUFFER11 0x8830 #define GL_DRAW_BUFFER12 0x8831 #define GL_DRAW_BUFFER13 0x8832 #define GL_DRAW_BUFFER14 0x8833 #define GL_DRAW_BUFFER15 0x8834 #define GL_BLEND_EQUATION_ALPHA 0x883D #define GL_MAX_VERTEX_ATTRIBS 0x8869 #define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A #define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 #define GL_FRAGMENT_SHADER 0x8B30 #define GL_VERTEX_SHADER 0x8B31 #define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 #define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A #define GL_MAX_VARYING_FLOATS 0x8B4B #define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C #define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D #define GL_SHADER_TYPE 0x8B4F #define GL_FLOAT_VEC2 0x8B50 #define GL_FLOAT_VEC3 0x8B51 #define GL_FLOAT_VEC4 0x8B52 #define GL_INT_VEC2 0x8B53 #define GL_INT_VEC3 0x8B54 #define GL_INT_VEC4 0x8B55 #define GL_BOOL 0x8B56 #define GL_BOOL_VEC2 0x8B57 #define GL_BOOL_VEC3 0x8B58 #define GL_BOOL_VEC4 0x8B59 #define GL_FLOAT_MAT2 0x8B5A #define GL_FLOAT_MAT3 0x8B5B #define GL_FLOAT_MAT4 0x8B5C #define GL_SAMPLER_1D 0x8B5D #define GL_SAMPLER_2D 0x8B5E #define GL_SAMPLER_3D 0x8B5F #define GL_SAMPLER_CUBE 0x8B60 #define GL_SAMPLER_1D_SHADOW 0x8B61 #define GL_SAMPLER_2D_SHADOW 0x8B62 #define GL_DELETE_STATUS 0x8B80 #define GL_COMPILE_STATUS 0x8B81 #define GL_LINK_STATUS 0x8B82 #define GL_VALIDATE_STATUS 0x8B83 #define GL_INFO_LOG_LENGTH 0x8B84 #define GL_ATTACHED_SHADERS 0x8B85 #define GL_ACTIVE_UNIFORMS 0x8B86 #define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 #define GL_SHADER_SOURCE_LENGTH 0x8B88 #define GL_ACTIVE_ATTRIBUTES 0x8B89 #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #define GL_CURRENT_PROGRAM 0x8B8D #define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 #define GL_LOWER_LEFT 0x8CA1 #define GL_UPPER_LEFT 0x8CA2 #define GL_STENCIL_BACK_REF 0x8CA3 #define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 #define GL_STENCIL_BACK_WRITEMASK 0x8CA5 #define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 #define GL_POINT_SPRITE 0x8861 #define GL_COORD_REPLACE 0x8862 #define GL_MAX_TEXTURE_COORDS 0x8871 #define GL_PIXEL_PACK_BUFFER 0x88EB #define GL_PIXEL_UNPACK_BUFFER 0x88EC #define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED #define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF #define GL_FLOAT_MAT2x3 0x8B65 #define GL_FLOAT_MAT2x4 0x8B66 #define GL_FLOAT_MAT3x2 0x8B67 #define GL_FLOAT_MAT3x4 0x8B68 #define GL_FLOAT_MAT4x2 0x8B69 #define GL_FLOAT_MAT4x3 0x8B6A #define GL_SRGB 0x8C40 #define GL_SRGB8 0x8C41 #define GL_SRGB_ALPHA 0x8C42 #define GL_SRGB8_ALPHA8 0x8C43 #define GL_COMPRESSED_SRGB 0x8C48 #define GL_COMPRESSED_SRGB_ALPHA 0x8C49 #define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F #define GL_SLUMINANCE_ALPHA 0x8C44 #define GL_SLUMINANCE8_ALPHA8 0x8C45 #define GL_SLUMINANCE 0x8C46 #define GL_SLUMINANCE8 0x8C47 #define GL_COMPRESSED_SLUMINANCE 0x8C4A #define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B #define GL_COMPARE_REF_TO_TEXTURE 0x884E #define GL_CLIP_DISTANCE0 0x3000 #define GL_CLIP_DISTANCE1 0x3001 #define GL_CLIP_DISTANCE2 0x3002 #define GL_CLIP_DISTANCE3 0x3003 #define GL_CLIP_DISTANCE4 0x3004 #define GL_CLIP_DISTANCE5 0x3005 #define GL_CLIP_DISTANCE6 0x3006 #define GL_CLIP_DISTANCE7 0x3007 #define GL_MAX_CLIP_DISTANCES 0x0D32 #define GL_MAJOR_VERSION 0x821B #define GL_MINOR_VERSION 0x821C #define GL_NUM_EXTENSIONS 0x821D #define GL_CONTEXT_FLAGS 0x821E #define GL_COMPRESSED_RED 0x8225 #define GL_COMPRESSED_RG 0x8226 #define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 #define GL_RGBA32F 0x8814 #define GL_RGB32F 0x8815 #define GL_RGBA16F 0x881A #define GL_RGB16F 0x881B #define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD #define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF #define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 #define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 #define GL_CLAMP_READ_COLOR 0x891C #define GL_FIXED_ONLY 0x891D #define GL_MAX_VARYING_COMPONENTS 0x8B4B #define GL_TEXTURE_1D_ARRAY 0x8C18 #define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 #define GL_TEXTURE_2D_ARRAY 0x8C1A #define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B #define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C #define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D #define GL_R11F_G11F_B10F 0x8C3A #define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B #define GL_RGB9_E5 0x8C3D #define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E #define GL_TEXTURE_SHARED_SIZE 0x8C3F #define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 #define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 #define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 #define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 #define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 #define GL_PRIMITIVES_GENERATED 0x8C87 #define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 #define GL_RASTERIZER_DISCARD 0x8C89 #define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A #define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B #define GL_INTERLEAVED_ATTRIBS 0x8C8C #define GL_SEPARATE_ATTRIBS 0x8C8D #define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E #define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F #define GL_RGBA32UI 0x8D70 #define GL_RGB32UI 0x8D71 #define GL_RGBA16UI 0x8D76 #define GL_RGB16UI 0x8D77 #define GL_RGBA8UI 0x8D7C #define GL_RGB8UI 0x8D7D #define GL_RGBA32I 0x8D82 #define GL_RGB32I 0x8D83 #define GL_RGBA16I 0x8D88 #define GL_RGB16I 0x8D89 #define GL_RGBA8I 0x8D8E #define GL_RGB8I 0x8D8F #define GL_RED_INTEGER 0x8D94 #define GL_GREEN_INTEGER 0x8D95 #define GL_BLUE_INTEGER 0x8D96 #define GL_RGB_INTEGER 0x8D98 #define GL_RGBA_INTEGER 0x8D99 #define GL_BGR_INTEGER 0x8D9A #define GL_BGRA_INTEGER 0x8D9B #define GL_SAMPLER_1D_ARRAY 0x8DC0 #define GL_SAMPLER_2D_ARRAY 0x8DC1 #define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 #define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 #define GL_SAMPLER_CUBE_SHADOW 0x8DC5 #define GL_UNSIGNED_INT_VEC2 0x8DC6 #define GL_UNSIGNED_INT_VEC3 0x8DC7 #define GL_UNSIGNED_INT_VEC4 0x8DC8 #define GL_INT_SAMPLER_1D 0x8DC9 #define GL_INT_SAMPLER_2D 0x8DCA #define GL_INT_SAMPLER_3D 0x8DCB #define GL_INT_SAMPLER_CUBE 0x8DCC #define GL_INT_SAMPLER_1D_ARRAY 0x8DCE #define GL_INT_SAMPLER_2D_ARRAY 0x8DCF #define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 #define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 #define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 #define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 #define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 #define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 #define GL_QUERY_WAIT 0x8E13 #define GL_QUERY_NO_WAIT 0x8E14 #define GL_QUERY_BY_REGION_WAIT 0x8E15 #define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 #define GL_BUFFER_ACCESS_FLAGS 0x911F #define GL_BUFFER_MAP_LENGTH 0x9120 #define GL_BUFFER_MAP_OFFSET 0x9121 #define GL_DEPTH_COMPONENT32F 0x8CAC #define GL_DEPTH32F_STENCIL8 0x8CAD #define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD #define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 #define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 #define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 #define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 #define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 #define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 #define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 #define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 #define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 #define GL_FRAMEBUFFER_DEFAULT 0x8218 #define GL_FRAMEBUFFER_UNDEFINED 0x8219 #define GL_DEPTH_STENCIL_ATTACHMENT 0x821A #define GL_MAX_RENDERBUFFER_SIZE 0x84E8 #define GL_DEPTH_STENCIL 0x84F9 #define GL_UNSIGNED_INT_24_8 0x84FA #define GL_DEPTH24_STENCIL8 0x88F0 #define GL_TEXTURE_STENCIL_SIZE 0x88F1 #define GL_TEXTURE_RED_TYPE 0x8C10 #define GL_TEXTURE_GREEN_TYPE 0x8C11 #define GL_TEXTURE_BLUE_TYPE 0x8C12 #define GL_TEXTURE_ALPHA_TYPE 0x8C13 #define GL_TEXTURE_DEPTH_TYPE 0x8C16 #define GL_UNSIGNED_NORMALIZED 0x8C17 #define GL_FRAMEBUFFER_BINDING 0x8CA6 #define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 #define GL_RENDERBUFFER_BINDING 0x8CA7 #define GL_READ_FRAMEBUFFER 0x8CA8 #define GL_DRAW_FRAMEBUFFER 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING 0x8CAA #define GL_RENDERBUFFER_SAMPLES 0x8CAB #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 #define GL_FRAMEBUFFER_COMPLETE 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD #define GL_MAX_COLOR_ATTACHMENTS 0x8CDF #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_COLOR_ATTACHMENT1 0x8CE1 #define GL_COLOR_ATTACHMENT2 0x8CE2 #define GL_COLOR_ATTACHMENT3 0x8CE3 #define GL_COLOR_ATTACHMENT4 0x8CE4 #define GL_COLOR_ATTACHMENT5 0x8CE5 #define GL_COLOR_ATTACHMENT6 0x8CE6 #define GL_COLOR_ATTACHMENT7 0x8CE7 #define GL_COLOR_ATTACHMENT8 0x8CE8 #define GL_COLOR_ATTACHMENT9 0x8CE9 #define GL_COLOR_ATTACHMENT10 0x8CEA #define GL_COLOR_ATTACHMENT11 0x8CEB #define GL_COLOR_ATTACHMENT12 0x8CEC #define GL_COLOR_ATTACHMENT13 0x8CED #define GL_COLOR_ATTACHMENT14 0x8CEE #define GL_COLOR_ATTACHMENT15 0x8CEF #define GL_COLOR_ATTACHMENT16 0x8CF0 #define GL_COLOR_ATTACHMENT17 0x8CF1 #define GL_COLOR_ATTACHMENT18 0x8CF2 #define GL_COLOR_ATTACHMENT19 0x8CF3 #define GL_COLOR_ATTACHMENT20 0x8CF4 #define GL_COLOR_ATTACHMENT21 0x8CF5 #define GL_COLOR_ATTACHMENT22 0x8CF6 #define GL_COLOR_ATTACHMENT23 0x8CF7 #define GL_COLOR_ATTACHMENT24 0x8CF8 #define GL_COLOR_ATTACHMENT25 0x8CF9 #define GL_COLOR_ATTACHMENT26 0x8CFA #define GL_COLOR_ATTACHMENT27 0x8CFB #define GL_COLOR_ATTACHMENT28 0x8CFC #define GL_COLOR_ATTACHMENT29 0x8CFD #define GL_COLOR_ATTACHMENT30 0x8CFE #define GL_COLOR_ATTACHMENT31 0x8CFF #define GL_DEPTH_ATTACHMENT 0x8D00 #define GL_STENCIL_ATTACHMENT 0x8D20 #define GL_FRAMEBUFFER 0x8D40 #define GL_RENDERBUFFER 0x8D41 #define GL_RENDERBUFFER_WIDTH 0x8D42 #define GL_RENDERBUFFER_HEIGHT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 #define GL_STENCIL_INDEX1 0x8D46 #define GL_STENCIL_INDEX4 0x8D47 #define GL_STENCIL_INDEX8 0x8D48 #define GL_STENCIL_INDEX16 0x8D49 #define GL_RENDERBUFFER_RED_SIZE 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 #define GL_MAX_SAMPLES 0x8D57 #define GL_INDEX 0x8222 #define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 #define GL_TEXTURE_INTENSITY_TYPE 0x8C15 #define GL_FRAMEBUFFER_SRGB 0x8DB9 #define GL_HALF_FLOAT 0x140B #define GL_MAP_READ_BIT 0x0001 #define GL_MAP_WRITE_BIT 0x0002 #define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 #define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 #define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 #define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 #define GL_COMPRESSED_RED_RGTC1 0x8DBB #define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC #define GL_COMPRESSED_RG_RGTC2 0x8DBD #define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE #define GL_RG 0x8227 #define GL_RG_INTEGER 0x8228 #define GL_R8 0x8229 #define GL_R16 0x822A #define GL_RG8 0x822B #define GL_RG16 0x822C #define GL_R16F 0x822D #define GL_R32F 0x822E #define GL_RG16F 0x822F #define GL_RG32F 0x8230 #define GL_R8I 0x8231 #define GL_R8UI 0x8232 #define GL_R16I 0x8233 #define GL_R16UI 0x8234 #define GL_R32I 0x8235 #define GL_R32UI 0x8236 #define GL_RG8I 0x8237 #define GL_RG8UI 0x8238 #define GL_RG16I 0x8239 #define GL_RG16UI 0x823A #define GL_RG32I 0x823B #define GL_RG32UI 0x823C #define GL_VERTEX_ARRAY_BINDING 0x85B5 #define GL_CLAMP_VERTEX_COLOR 0x891A #define GL_CLAMP_FRAGMENT_COLOR 0x891B #define GL_ALPHA_INTEGER 0x8D97 #define GL_SAMPLER_2D_RECT 0x8B63 #define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 #define GL_SAMPLER_BUFFER 0x8DC2 #define GL_INT_SAMPLER_2D_RECT 0x8DCD #define GL_INT_SAMPLER_BUFFER 0x8DD0 #define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 #define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 #define GL_TEXTURE_BUFFER 0x8C2A #define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B #define GL_TEXTURE_BINDING_BUFFER 0x8C2C #define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D #define GL_TEXTURE_RECTANGLE 0x84F5 #define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 #define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 #define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 #define GL_R8_SNORM 0x8F94 #define GL_RG8_SNORM 0x8F95 #define GL_RGB8_SNORM 0x8F96 #define GL_RGBA8_SNORM 0x8F97 #define GL_R16_SNORM 0x8F98 #define GL_RG16_SNORM 0x8F99 #define GL_RGB16_SNORM 0x8F9A #define GL_RGBA16_SNORM 0x8F9B #define GL_SIGNED_NORMALIZED 0x8F9C #define GL_PRIMITIVE_RESTART 0x8F9D #define GL_PRIMITIVE_RESTART_INDEX 0x8F9E #define GL_COPY_READ_BUFFER 0x8F36 #define GL_COPY_WRITE_BUFFER 0x8F37 #define GL_UNIFORM_BUFFER 0x8A11 #define GL_UNIFORM_BUFFER_BINDING 0x8A28 #define GL_UNIFORM_BUFFER_START 0x8A29 #define GL_UNIFORM_BUFFER_SIZE 0x8A2A #define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B #define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C #define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D #define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E #define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F #define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 #define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 #define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 #define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 #define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 #define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 #define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 #define GL_UNIFORM_TYPE 0x8A37 #define GL_UNIFORM_SIZE 0x8A38 #define GL_UNIFORM_NAME_LENGTH 0x8A39 #define GL_UNIFORM_BLOCK_INDEX 0x8A3A #define GL_UNIFORM_OFFSET 0x8A3B #define GL_UNIFORM_ARRAY_STRIDE 0x8A3C #define GL_UNIFORM_MATRIX_STRIDE 0x8A3D #define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E #define GL_UNIFORM_BLOCK_BINDING 0x8A3F #define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 #define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 #define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 #define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 #define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 #define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 #define GL_INVALID_INDEX 0xFFFFFFFF #define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 #define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 #define GL_LINES_ADJACENCY 0x000A #define GL_LINE_STRIP_ADJACENCY 0x000B #define GL_TRIANGLES_ADJACENCY 0x000C #define GL_TRIANGLE_STRIP_ADJACENCY 0x000D #define GL_PROGRAM_POINT_SIZE 0x8642 #define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 #define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 #define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 #define GL_GEOMETRY_SHADER 0x8DD9 #define GL_GEOMETRY_VERTICES_OUT 0x8916 #define GL_GEOMETRY_INPUT_TYPE 0x8917 #define GL_GEOMETRY_OUTPUT_TYPE 0x8918 #define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF #define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 #define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 #define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 #define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 #define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 #define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 #define GL_CONTEXT_PROFILE_MASK 0x9126 #define GL_DEPTH_CLAMP 0x864F #define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C #define GL_FIRST_VERTEX_CONVENTION 0x8E4D #define GL_LAST_VERTEX_CONVENTION 0x8E4E #define GL_PROVOKING_VERTEX 0x8E4F #define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F #define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 #define GL_OBJECT_TYPE 0x9112 #define GL_SYNC_CONDITION 0x9113 #define GL_SYNC_STATUS 0x9114 #define GL_SYNC_FLAGS 0x9115 #define GL_SYNC_FENCE 0x9116 #define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 #define GL_UNSIGNALED 0x9118 #define GL_SIGNALED 0x9119 #define GL_ALREADY_SIGNALED 0x911A #define GL_TIMEOUT_EXPIRED 0x911B #define GL_CONDITION_SATISFIED 0x911C #define GL_WAIT_FAILED 0x911D #define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFF #define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 #define GL_SAMPLE_POSITION 0x8E50 #define GL_SAMPLE_MASK 0x8E51 #define GL_SAMPLE_MASK_VALUE 0x8E52 #define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 #define GL_TEXTURE_2D_MULTISAMPLE 0x9100 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 #define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 #define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 #define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 #define GL_TEXTURE_SAMPLES 0x9106 #define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 #define GL_SAMPLER_2D_MULTISAMPLE 0x9108 #define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A #define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B #define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C #define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D #define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E #define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F #define GL_MAX_INTEGER_SAMPLES 0x9110 #define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE #define GL_SRC1_COLOR 0x88F9 #define GL_ONE_MINUS_SRC1_COLOR 0x88FA #define GL_ONE_MINUS_SRC1_ALPHA 0x88FB #define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC #define GL_ANY_SAMPLES_PASSED 0x8C2F #define GL_SAMPLER_BINDING 0x8919 #define GL_RGB10_A2UI 0x906F #define GL_TEXTURE_SWIZZLE_R 0x8E42 #define GL_TEXTURE_SWIZZLE_G 0x8E43 #define GL_TEXTURE_SWIZZLE_B 0x8E44 #define GL_TEXTURE_SWIZZLE_A 0x8E45 #define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 #define GL_TIME_ELAPSED 0x88BF #define GL_TIMESTAMP 0x8E28 #define GL_INT_2_10_10_10_REV 0x8D9F #define GL_SAMPLE_SHADING 0x8C36 #define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 #define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E #define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F #define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 #define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A #define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B #define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C #define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D #define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E #define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F #define GL_DRAW_INDIRECT_BUFFER 0x8F3F #define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 #define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F #define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A #define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B #define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C #define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D #define GL_MAX_VERTEX_STREAMS 0x8E71 #define GL_DOUBLE_VEC2 0x8FFC #define GL_DOUBLE_VEC3 0x8FFD #define GL_DOUBLE_VEC4 0x8FFE #define GL_DOUBLE_MAT2 0x8F46 #define GL_DOUBLE_MAT3 0x8F47 #define GL_DOUBLE_MAT4 0x8F48 #define GL_DOUBLE_MAT2x3 0x8F49 #define GL_DOUBLE_MAT2x4 0x8F4A #define GL_DOUBLE_MAT3x2 0x8F4B #define GL_DOUBLE_MAT3x4 0x8F4C #define GL_DOUBLE_MAT4x2 0x8F4D #define GL_DOUBLE_MAT4x3 0x8F4E #define GL_ACTIVE_SUBROUTINES 0x8DE5 #define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 #define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 #define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 #define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 #define GL_MAX_SUBROUTINES 0x8DE7 #define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 #define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A #define GL_COMPATIBLE_SUBROUTINES 0x8E4B #define GL_PATCHES 0x000E #define GL_PATCH_VERTICES 0x8E72 #define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 #define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 #define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 #define GL_TESS_GEN_MODE 0x8E76 #define GL_TESS_GEN_SPACING 0x8E77 #define GL_TESS_GEN_VERTEX_ORDER 0x8E78 #define GL_TESS_GEN_POINT_MODE 0x8E79 #define GL_ISOLINES 0x8E7A #define GL_FRACTIONAL_ODD 0x8E7B #define GL_FRACTIONAL_EVEN 0x8E7C #define GL_MAX_PATCH_VERTICES 0x8E7D #define GL_MAX_TESS_GEN_LEVEL 0x8E7E #define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F #define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 #define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 #define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 #define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 #define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 #define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 #define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 #define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 #define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A #define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C #define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D #define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E #define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 #define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 #define GL_TESS_EVALUATION_SHADER 0x8E87 #define GL_TESS_CONTROL_SHADER 0x8E88 #define GL_TRANSFORM_FEEDBACK 0x8E22 #define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 #define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 #define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 #define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 #ifndef GL_VERSION_1_0 #define GL_VERSION_1_0 1 GLAPI int GLAD_GL_VERSION_1_0; typedef void (APIENTRYP PFNGLCULLFACEPROC)(GLenum mode); GLAPI PFNGLCULLFACEPROC glad_glCullFace; #define glCullFace glad_glCullFace typedef void (APIENTRYP PFNGLFRONTFACEPROC)(GLenum mode); GLAPI PFNGLFRONTFACEPROC glad_glFrontFace; #define glFrontFace glad_glFrontFace typedef void (APIENTRYP PFNGLHINTPROC)(GLenum target, GLenum mode); GLAPI PFNGLHINTPROC glad_glHint; #define glHint glad_glHint typedef void (APIENTRYP PFNGLLINEWIDTHPROC)(GLfloat width); GLAPI PFNGLLINEWIDTHPROC glad_glLineWidth; #define glLineWidth glad_glLineWidth typedef void (APIENTRYP PFNGLPOINTSIZEPROC)(GLfloat size); GLAPI PFNGLPOINTSIZEPROC glad_glPointSize; #define glPointSize glad_glPointSize typedef void (APIENTRYP PFNGLPOLYGONMODEPROC)(GLenum face, GLenum mode); GLAPI PFNGLPOLYGONMODEPROC glad_glPolygonMode; #define glPolygonMode glad_glPolygonMode typedef void (APIENTRYP PFNGLSCISSORPROC)(GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLSCISSORPROC glad_glScissor; #define glScissor glad_glScissor typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC)(GLenum target, GLenum pname, GLfloat param); GLAPI PFNGLTEXPARAMETERFPROC glad_glTexParameterf; #define glTexParameterf glad_glTexParameterf typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC)(GLenum target, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; #define glTexParameterfv glad_glTexParameterfv typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC)(GLenum target, GLenum pname, GLint param); GLAPI PFNGLTEXPARAMETERIPROC glad_glTexParameteri; #define glTexParameteri glad_glTexParameteri typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; #define glTexParameteriv glad_glTexParameteriv typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE1DPROC glad_glTexImage1D; #define glTexImage1D glad_glTexImage1D typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE2DPROC glad_glTexImage2D; #define glTexImage2D glad_glTexImage2D typedef void (APIENTRYP PFNGLDRAWBUFFERPROC)(GLenum buf); GLAPI PFNGLDRAWBUFFERPROC glad_glDrawBuffer; #define glDrawBuffer glad_glDrawBuffer typedef void (APIENTRYP PFNGLCLEARPROC)(GLbitfield mask); GLAPI PFNGLCLEARPROC glad_glClear; #define glClear glad_glClear typedef void (APIENTRYP PFNGLCLEARCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCLEARCOLORPROC glad_glClearColor; #define glClearColor glad_glClearColor typedef void (APIENTRYP PFNGLCLEARSTENCILPROC)(GLint s); GLAPI PFNGLCLEARSTENCILPROC glad_glClearStencil; #define glClearStencil glad_glClearStencil typedef void (APIENTRYP PFNGLCLEARDEPTHPROC)(GLdouble depth); GLAPI PFNGLCLEARDEPTHPROC glad_glClearDepth; #define glClearDepth glad_glClearDepth typedef void (APIENTRYP PFNGLSTENCILMASKPROC)(GLuint mask); GLAPI PFNGLSTENCILMASKPROC glad_glStencilMask; #define glStencilMask glad_glStencilMask typedef void (APIENTRYP PFNGLCOLORMASKPROC)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); GLAPI PFNGLCOLORMASKPROC glad_glColorMask; #define glColorMask glad_glColorMask typedef void (APIENTRYP PFNGLDEPTHMASKPROC)(GLboolean flag); GLAPI PFNGLDEPTHMASKPROC glad_glDepthMask; #define glDepthMask glad_glDepthMask typedef void (APIENTRYP PFNGLDISABLEPROC)(GLenum cap); GLAPI PFNGLDISABLEPROC glad_glDisable; #define glDisable glad_glDisable typedef void (APIENTRYP PFNGLENABLEPROC)(GLenum cap); GLAPI PFNGLENABLEPROC glad_glEnable; #define glEnable glad_glEnable typedef void (APIENTRYP PFNGLFINISHPROC)(void); GLAPI PFNGLFINISHPROC glad_glFinish; #define glFinish glad_glFinish typedef void (APIENTRYP PFNGLFLUSHPROC)(void); GLAPI PFNGLFLUSHPROC glad_glFlush; #define glFlush glad_glFlush typedef void (APIENTRYP PFNGLBLENDFUNCPROC)(GLenum sfactor, GLenum dfactor); GLAPI PFNGLBLENDFUNCPROC glad_glBlendFunc; #define glBlendFunc glad_glBlendFunc typedef void (APIENTRYP PFNGLLOGICOPPROC)(GLenum opcode); GLAPI PFNGLLOGICOPPROC glad_glLogicOp; #define glLogicOp glad_glLogicOp typedef void (APIENTRYP PFNGLSTENCILFUNCPROC)(GLenum func, GLint ref, GLuint mask); GLAPI PFNGLSTENCILFUNCPROC glad_glStencilFunc; #define glStencilFunc glad_glStencilFunc typedef void (APIENTRYP PFNGLSTENCILOPPROC)(GLenum fail, GLenum zfail, GLenum zpass); GLAPI PFNGLSTENCILOPPROC glad_glStencilOp; #define glStencilOp glad_glStencilOp typedef void (APIENTRYP PFNGLDEPTHFUNCPROC)(GLenum func); GLAPI PFNGLDEPTHFUNCPROC glad_glDepthFunc; #define glDepthFunc glad_glDepthFunc typedef void (APIENTRYP PFNGLPIXELSTOREFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPIXELSTOREFPROC glad_glPixelStoref; #define glPixelStoref glad_glPixelStoref typedef void (APIENTRYP PFNGLPIXELSTOREIPROC)(GLenum pname, GLint param); GLAPI PFNGLPIXELSTOREIPROC glad_glPixelStorei; #define glPixelStorei glad_glPixelStorei typedef void (APIENTRYP PFNGLREADBUFFERPROC)(GLenum src); GLAPI PFNGLREADBUFFERPROC glad_glReadBuffer; #define glReadBuffer glad_glReadBuffer typedef void (APIENTRYP PFNGLREADPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); GLAPI PFNGLREADPIXELSPROC glad_glReadPixels; #define glReadPixels glad_glReadPixels typedef void (APIENTRYP PFNGLGETBOOLEANVPROC)(GLenum pname, GLboolean *data); GLAPI PFNGLGETBOOLEANVPROC glad_glGetBooleanv; #define glGetBooleanv glad_glGetBooleanv typedef void (APIENTRYP PFNGLGETDOUBLEVPROC)(GLenum pname, GLdouble *data); GLAPI PFNGLGETDOUBLEVPROC glad_glGetDoublev; #define glGetDoublev glad_glGetDoublev typedef GLenum (APIENTRYP PFNGLGETERRORPROC)(void); GLAPI PFNGLGETERRORPROC glad_glGetError; #define glGetError glad_glGetError typedef void (APIENTRYP PFNGLGETFLOATVPROC)(GLenum pname, GLfloat *data); GLAPI PFNGLGETFLOATVPROC glad_glGetFloatv; #define glGetFloatv glad_glGetFloatv typedef void (APIENTRYP PFNGLGETINTEGERVPROC)(GLenum pname, GLint *data); GLAPI PFNGLGETINTEGERVPROC glad_glGetIntegerv; #define glGetIntegerv glad_glGetIntegerv typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGPROC)(GLenum name); GLAPI PFNGLGETSTRINGPROC glad_glGetString; #define glGetString glad_glGetString typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, void *pixels); GLAPI PFNGLGETTEXIMAGEPROC glad_glGetTexImage; #define glGetTexImage glad_glGetTexImage typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC)(GLenum target, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; #define glGetTexParameterfv glad_glGetTexParameterfv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; #define glGetTexParameteriv glad_glGetTexParameteriv typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC)(GLenum target, GLint level, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; #define glGetTexLevelParameterfv glad_glGetTexLevelParameterfv typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC)(GLenum target, GLint level, GLenum pname, GLint *params); GLAPI PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; #define glGetTexLevelParameteriv glad_glGetTexLevelParameteriv typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC)(GLenum cap); GLAPI PFNGLISENABLEDPROC glad_glIsEnabled; #define glIsEnabled glad_glIsEnabled typedef void (APIENTRYP PFNGLDEPTHRANGEPROC)(GLdouble n, GLdouble f); GLAPI PFNGLDEPTHRANGEPROC glad_glDepthRange; #define glDepthRange glad_glDepthRange typedef void (APIENTRYP PFNGLVIEWPORTPROC)(GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLVIEWPORTPROC glad_glViewport; #define glViewport glad_glViewport typedef void (APIENTRYP PFNGLNEWLISTPROC)(GLuint list, GLenum mode); GLAPI PFNGLNEWLISTPROC glad_glNewList; #define glNewList glad_glNewList typedef void (APIENTRYP PFNGLENDLISTPROC)(void); GLAPI PFNGLENDLISTPROC glad_glEndList; #define glEndList glad_glEndList typedef void (APIENTRYP PFNGLCALLLISTPROC)(GLuint list); GLAPI PFNGLCALLLISTPROC glad_glCallList; #define glCallList glad_glCallList typedef void (APIENTRYP PFNGLCALLLISTSPROC)(GLsizei n, GLenum type, const void *lists); GLAPI PFNGLCALLLISTSPROC glad_glCallLists; #define glCallLists glad_glCallLists typedef void (APIENTRYP PFNGLDELETELISTSPROC)(GLuint list, GLsizei range); GLAPI PFNGLDELETELISTSPROC glad_glDeleteLists; #define glDeleteLists glad_glDeleteLists typedef GLuint (APIENTRYP PFNGLGENLISTSPROC)(GLsizei range); GLAPI PFNGLGENLISTSPROC glad_glGenLists; #define glGenLists glad_glGenLists typedef void (APIENTRYP PFNGLLISTBASEPROC)(GLuint base); GLAPI PFNGLLISTBASEPROC glad_glListBase; #define glListBase glad_glListBase typedef void (APIENTRYP PFNGLBEGINPROC)(GLenum mode); GLAPI PFNGLBEGINPROC glad_glBegin; #define glBegin glad_glBegin typedef void (APIENTRYP PFNGLBITMAPPROC)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); GLAPI PFNGLBITMAPPROC glad_glBitmap; #define glBitmap glad_glBitmap typedef void (APIENTRYP PFNGLCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); GLAPI PFNGLCOLOR3BPROC glad_glColor3b; #define glColor3b glad_glColor3b typedef void (APIENTRYP PFNGLCOLOR3BVPROC)(const GLbyte *v); GLAPI PFNGLCOLOR3BVPROC glad_glColor3bv; #define glColor3bv glad_glColor3bv typedef void (APIENTRYP PFNGLCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); GLAPI PFNGLCOLOR3DPROC glad_glColor3d; #define glColor3d glad_glColor3d typedef void (APIENTRYP PFNGLCOLOR3DVPROC)(const GLdouble *v); GLAPI PFNGLCOLOR3DVPROC glad_glColor3dv; #define glColor3dv glad_glColor3dv typedef void (APIENTRYP PFNGLCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); GLAPI PFNGLCOLOR3FPROC glad_glColor3f; #define glColor3f glad_glColor3f typedef void (APIENTRYP PFNGLCOLOR3FVPROC)(const GLfloat *v); GLAPI PFNGLCOLOR3FVPROC glad_glColor3fv; #define glColor3fv glad_glColor3fv typedef void (APIENTRYP PFNGLCOLOR3IPROC)(GLint red, GLint green, GLint blue); GLAPI PFNGLCOLOR3IPROC glad_glColor3i; #define glColor3i glad_glColor3i typedef void (APIENTRYP PFNGLCOLOR3IVPROC)(const GLint *v); GLAPI PFNGLCOLOR3IVPROC glad_glColor3iv; #define glColor3iv glad_glColor3iv typedef void (APIENTRYP PFNGLCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); GLAPI PFNGLCOLOR3SPROC glad_glColor3s; #define glColor3s glad_glColor3s typedef void (APIENTRYP PFNGLCOLOR3SVPROC)(const GLshort *v); GLAPI PFNGLCOLOR3SVPROC glad_glColor3sv; #define glColor3sv glad_glColor3sv typedef void (APIENTRYP PFNGLCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); GLAPI PFNGLCOLOR3UBPROC glad_glColor3ub; #define glColor3ub glad_glColor3ub typedef void (APIENTRYP PFNGLCOLOR3UBVPROC)(const GLubyte *v); GLAPI PFNGLCOLOR3UBVPROC glad_glColor3ubv; #define glColor3ubv glad_glColor3ubv typedef void (APIENTRYP PFNGLCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); GLAPI PFNGLCOLOR3UIPROC glad_glColor3ui; #define glColor3ui glad_glColor3ui typedef void (APIENTRYP PFNGLCOLOR3UIVPROC)(const GLuint *v); GLAPI PFNGLCOLOR3UIVPROC glad_glColor3uiv; #define glColor3uiv glad_glColor3uiv typedef void (APIENTRYP PFNGLCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); GLAPI PFNGLCOLOR3USPROC glad_glColor3us; #define glColor3us glad_glColor3us typedef void (APIENTRYP PFNGLCOLOR3USVPROC)(const GLushort *v); GLAPI PFNGLCOLOR3USVPROC glad_glColor3usv; #define glColor3usv glad_glColor3usv typedef void (APIENTRYP PFNGLCOLOR4BPROC)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); GLAPI PFNGLCOLOR4BPROC glad_glColor4b; #define glColor4b glad_glColor4b typedef void (APIENTRYP PFNGLCOLOR4BVPROC)(const GLbyte *v); GLAPI PFNGLCOLOR4BVPROC glad_glColor4bv; #define glColor4bv glad_glColor4bv typedef void (APIENTRYP PFNGLCOLOR4DPROC)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); GLAPI PFNGLCOLOR4DPROC glad_glColor4d; #define glColor4d glad_glColor4d typedef void (APIENTRYP PFNGLCOLOR4DVPROC)(const GLdouble *v); GLAPI PFNGLCOLOR4DVPROC glad_glColor4dv; #define glColor4dv glad_glColor4dv typedef void (APIENTRYP PFNGLCOLOR4FPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCOLOR4FPROC glad_glColor4f; #define glColor4f glad_glColor4f typedef void (APIENTRYP PFNGLCOLOR4FVPROC)(const GLfloat *v); GLAPI PFNGLCOLOR4FVPROC glad_glColor4fv; #define glColor4fv glad_glColor4fv typedef void (APIENTRYP PFNGLCOLOR4IPROC)(GLint red, GLint green, GLint blue, GLint alpha); GLAPI PFNGLCOLOR4IPROC glad_glColor4i; #define glColor4i glad_glColor4i typedef void (APIENTRYP PFNGLCOLOR4IVPROC)(const GLint *v); GLAPI PFNGLCOLOR4IVPROC glad_glColor4iv; #define glColor4iv glad_glColor4iv typedef void (APIENTRYP PFNGLCOLOR4SPROC)(GLshort red, GLshort green, GLshort blue, GLshort alpha); GLAPI PFNGLCOLOR4SPROC glad_glColor4s; #define glColor4s glad_glColor4s typedef void (APIENTRYP PFNGLCOLOR4SVPROC)(const GLshort *v); GLAPI PFNGLCOLOR4SVPROC glad_glColor4sv; #define glColor4sv glad_glColor4sv typedef void (APIENTRYP PFNGLCOLOR4UBPROC)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); GLAPI PFNGLCOLOR4UBPROC glad_glColor4ub; #define glColor4ub glad_glColor4ub typedef void (APIENTRYP PFNGLCOLOR4UBVPROC)(const GLubyte *v); GLAPI PFNGLCOLOR4UBVPROC glad_glColor4ubv; #define glColor4ubv glad_glColor4ubv typedef void (APIENTRYP PFNGLCOLOR4UIPROC)(GLuint red, GLuint green, GLuint blue, GLuint alpha); GLAPI PFNGLCOLOR4UIPROC glad_glColor4ui; #define glColor4ui glad_glColor4ui typedef void (APIENTRYP PFNGLCOLOR4UIVPROC)(const GLuint *v); GLAPI PFNGLCOLOR4UIVPROC glad_glColor4uiv; #define glColor4uiv glad_glColor4uiv typedef void (APIENTRYP PFNGLCOLOR4USPROC)(GLushort red, GLushort green, GLushort blue, GLushort alpha); GLAPI PFNGLCOLOR4USPROC glad_glColor4us; #define glColor4us glad_glColor4us typedef void (APIENTRYP PFNGLCOLOR4USVPROC)(const GLushort *v); GLAPI PFNGLCOLOR4USVPROC glad_glColor4usv; #define glColor4usv glad_glColor4usv typedef void (APIENTRYP PFNGLEDGEFLAGPROC)(GLboolean flag); GLAPI PFNGLEDGEFLAGPROC glad_glEdgeFlag; #define glEdgeFlag glad_glEdgeFlag typedef void (APIENTRYP PFNGLEDGEFLAGVPROC)(const GLboolean *flag); GLAPI PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; #define glEdgeFlagv glad_glEdgeFlagv typedef void (APIENTRYP PFNGLENDPROC)(void); GLAPI PFNGLENDPROC glad_glEnd; #define glEnd glad_glEnd typedef void (APIENTRYP PFNGLINDEXDPROC)(GLdouble c); GLAPI PFNGLINDEXDPROC glad_glIndexd; #define glIndexd glad_glIndexd typedef void (APIENTRYP PFNGLINDEXDVPROC)(const GLdouble *c); GLAPI PFNGLINDEXDVPROC glad_glIndexdv; #define glIndexdv glad_glIndexdv typedef void (APIENTRYP PFNGLINDEXFPROC)(GLfloat c); GLAPI PFNGLINDEXFPROC glad_glIndexf; #define glIndexf glad_glIndexf typedef void (APIENTRYP PFNGLINDEXFVPROC)(const GLfloat *c); GLAPI PFNGLINDEXFVPROC glad_glIndexfv; #define glIndexfv glad_glIndexfv typedef void (APIENTRYP PFNGLINDEXIPROC)(GLint c); GLAPI PFNGLINDEXIPROC glad_glIndexi; #define glIndexi glad_glIndexi typedef void (APIENTRYP PFNGLINDEXIVPROC)(const GLint *c); GLAPI PFNGLINDEXIVPROC glad_glIndexiv; #define glIndexiv glad_glIndexiv typedef void (APIENTRYP PFNGLINDEXSPROC)(GLshort c); GLAPI PFNGLINDEXSPROC glad_glIndexs; #define glIndexs glad_glIndexs typedef void (APIENTRYP PFNGLINDEXSVPROC)(const GLshort *c); GLAPI PFNGLINDEXSVPROC glad_glIndexsv; #define glIndexsv glad_glIndexsv typedef void (APIENTRYP PFNGLNORMAL3BPROC)(GLbyte nx, GLbyte ny, GLbyte nz); GLAPI PFNGLNORMAL3BPROC glad_glNormal3b; #define glNormal3b glad_glNormal3b typedef void (APIENTRYP PFNGLNORMAL3BVPROC)(const GLbyte *v); GLAPI PFNGLNORMAL3BVPROC glad_glNormal3bv; #define glNormal3bv glad_glNormal3bv typedef void (APIENTRYP PFNGLNORMAL3DPROC)(GLdouble nx, GLdouble ny, GLdouble nz); GLAPI PFNGLNORMAL3DPROC glad_glNormal3d; #define glNormal3d glad_glNormal3d typedef void (APIENTRYP PFNGLNORMAL3DVPROC)(const GLdouble *v); GLAPI PFNGLNORMAL3DVPROC glad_glNormal3dv; #define glNormal3dv glad_glNormal3dv typedef void (APIENTRYP PFNGLNORMAL3FPROC)(GLfloat nx, GLfloat ny, GLfloat nz); GLAPI PFNGLNORMAL3FPROC glad_glNormal3f; #define glNormal3f glad_glNormal3f typedef void (APIENTRYP PFNGLNORMAL3FVPROC)(const GLfloat *v); GLAPI PFNGLNORMAL3FVPROC glad_glNormal3fv; #define glNormal3fv glad_glNormal3fv typedef void (APIENTRYP PFNGLNORMAL3IPROC)(GLint nx, GLint ny, GLint nz); GLAPI PFNGLNORMAL3IPROC glad_glNormal3i; #define glNormal3i glad_glNormal3i typedef void (APIENTRYP PFNGLNORMAL3IVPROC)(const GLint *v); GLAPI PFNGLNORMAL3IVPROC glad_glNormal3iv; #define glNormal3iv glad_glNormal3iv typedef void (APIENTRYP PFNGLNORMAL3SPROC)(GLshort nx, GLshort ny, GLshort nz); GLAPI PFNGLNORMAL3SPROC glad_glNormal3s; #define glNormal3s glad_glNormal3s typedef void (APIENTRYP PFNGLNORMAL3SVPROC)(const GLshort *v); GLAPI PFNGLNORMAL3SVPROC glad_glNormal3sv; #define glNormal3sv glad_glNormal3sv typedef void (APIENTRYP PFNGLRASTERPOS2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLRASTERPOS2DPROC glad_glRasterPos2d; #define glRasterPos2d glad_glRasterPos2d typedef void (APIENTRYP PFNGLRASTERPOS2DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; #define glRasterPos2dv glad_glRasterPos2dv typedef void (APIENTRYP PFNGLRASTERPOS2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLRASTERPOS2FPROC glad_glRasterPos2f; #define glRasterPos2f glad_glRasterPos2f typedef void (APIENTRYP PFNGLRASTERPOS2FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; #define glRasterPos2fv glad_glRasterPos2fv typedef void (APIENTRYP PFNGLRASTERPOS2IPROC)(GLint x, GLint y); GLAPI PFNGLRASTERPOS2IPROC glad_glRasterPos2i; #define glRasterPos2i glad_glRasterPos2i typedef void (APIENTRYP PFNGLRASTERPOS2IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; #define glRasterPos2iv glad_glRasterPos2iv typedef void (APIENTRYP PFNGLRASTERPOS2SPROC)(GLshort x, GLshort y); GLAPI PFNGLRASTERPOS2SPROC glad_glRasterPos2s; #define glRasterPos2s glad_glRasterPos2s typedef void (APIENTRYP PFNGLRASTERPOS2SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; #define glRasterPos2sv glad_glRasterPos2sv typedef void (APIENTRYP PFNGLRASTERPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLRASTERPOS3DPROC glad_glRasterPos3d; #define glRasterPos3d glad_glRasterPos3d typedef void (APIENTRYP PFNGLRASTERPOS3DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; #define glRasterPos3dv glad_glRasterPos3dv typedef void (APIENTRYP PFNGLRASTERPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLRASTERPOS3FPROC glad_glRasterPos3f; #define glRasterPos3f glad_glRasterPos3f typedef void (APIENTRYP PFNGLRASTERPOS3FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; #define glRasterPos3fv glad_glRasterPos3fv typedef void (APIENTRYP PFNGLRASTERPOS3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLRASTERPOS3IPROC glad_glRasterPos3i; #define glRasterPos3i glad_glRasterPos3i typedef void (APIENTRYP PFNGLRASTERPOS3IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; #define glRasterPos3iv glad_glRasterPos3iv typedef void (APIENTRYP PFNGLRASTERPOS3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLRASTERPOS3SPROC glad_glRasterPos3s; #define glRasterPos3s glad_glRasterPos3s typedef void (APIENTRYP PFNGLRASTERPOS3SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; #define glRasterPos3sv glad_glRasterPos3sv typedef void (APIENTRYP PFNGLRASTERPOS4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLRASTERPOS4DPROC glad_glRasterPos4d; #define glRasterPos4d glad_glRasterPos4d typedef void (APIENTRYP PFNGLRASTERPOS4DVPROC)(const GLdouble *v); GLAPI PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; #define glRasterPos4dv glad_glRasterPos4dv typedef void (APIENTRYP PFNGLRASTERPOS4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLRASTERPOS4FPROC glad_glRasterPos4f; #define glRasterPos4f glad_glRasterPos4f typedef void (APIENTRYP PFNGLRASTERPOS4FVPROC)(const GLfloat *v); GLAPI PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; #define glRasterPos4fv glad_glRasterPos4fv typedef void (APIENTRYP PFNGLRASTERPOS4IPROC)(GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLRASTERPOS4IPROC glad_glRasterPos4i; #define glRasterPos4i glad_glRasterPos4i typedef void (APIENTRYP PFNGLRASTERPOS4IVPROC)(const GLint *v); GLAPI PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; #define glRasterPos4iv glad_glRasterPos4iv typedef void (APIENTRYP PFNGLRASTERPOS4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLRASTERPOS4SPROC glad_glRasterPos4s; #define glRasterPos4s glad_glRasterPos4s typedef void (APIENTRYP PFNGLRASTERPOS4SVPROC)(const GLshort *v); GLAPI PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; #define glRasterPos4sv glad_glRasterPos4sv typedef void (APIENTRYP PFNGLRECTDPROC)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); GLAPI PFNGLRECTDPROC glad_glRectd; #define glRectd glad_glRectd typedef void (APIENTRYP PFNGLRECTDVPROC)(const GLdouble *v1, const GLdouble *v2); GLAPI PFNGLRECTDVPROC glad_glRectdv; #define glRectdv glad_glRectdv typedef void (APIENTRYP PFNGLRECTFPROC)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); GLAPI PFNGLRECTFPROC glad_glRectf; #define glRectf glad_glRectf typedef void (APIENTRYP PFNGLRECTFVPROC)(const GLfloat *v1, const GLfloat *v2); GLAPI PFNGLRECTFVPROC glad_glRectfv; #define glRectfv glad_glRectfv typedef void (APIENTRYP PFNGLRECTIPROC)(GLint x1, GLint y1, GLint x2, GLint y2); GLAPI PFNGLRECTIPROC glad_glRecti; #define glRecti glad_glRecti typedef void (APIENTRYP PFNGLRECTIVPROC)(const GLint *v1, const GLint *v2); GLAPI PFNGLRECTIVPROC glad_glRectiv; #define glRectiv glad_glRectiv typedef void (APIENTRYP PFNGLRECTSPROC)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); GLAPI PFNGLRECTSPROC glad_glRects; #define glRects glad_glRects typedef void (APIENTRYP PFNGLRECTSVPROC)(const GLshort *v1, const GLshort *v2); GLAPI PFNGLRECTSVPROC glad_glRectsv; #define glRectsv glad_glRectsv typedef void (APIENTRYP PFNGLTEXCOORD1DPROC)(GLdouble s); GLAPI PFNGLTEXCOORD1DPROC glad_glTexCoord1d; #define glTexCoord1d glad_glTexCoord1d typedef void (APIENTRYP PFNGLTEXCOORD1DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; #define glTexCoord1dv glad_glTexCoord1dv typedef void (APIENTRYP PFNGLTEXCOORD1FPROC)(GLfloat s); GLAPI PFNGLTEXCOORD1FPROC glad_glTexCoord1f; #define glTexCoord1f glad_glTexCoord1f typedef void (APIENTRYP PFNGLTEXCOORD1FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; #define glTexCoord1fv glad_glTexCoord1fv typedef void (APIENTRYP PFNGLTEXCOORD1IPROC)(GLint s); GLAPI PFNGLTEXCOORD1IPROC glad_glTexCoord1i; #define glTexCoord1i glad_glTexCoord1i typedef void (APIENTRYP PFNGLTEXCOORD1IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; #define glTexCoord1iv glad_glTexCoord1iv typedef void (APIENTRYP PFNGLTEXCOORD1SPROC)(GLshort s); GLAPI PFNGLTEXCOORD1SPROC glad_glTexCoord1s; #define glTexCoord1s glad_glTexCoord1s typedef void (APIENTRYP PFNGLTEXCOORD1SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; #define glTexCoord1sv glad_glTexCoord1sv typedef void (APIENTRYP PFNGLTEXCOORD2DPROC)(GLdouble s, GLdouble t); GLAPI PFNGLTEXCOORD2DPROC glad_glTexCoord2d; #define glTexCoord2d glad_glTexCoord2d typedef void (APIENTRYP PFNGLTEXCOORD2DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; #define glTexCoord2dv glad_glTexCoord2dv typedef void (APIENTRYP PFNGLTEXCOORD2FPROC)(GLfloat s, GLfloat t); GLAPI PFNGLTEXCOORD2FPROC glad_glTexCoord2f; #define glTexCoord2f glad_glTexCoord2f typedef void (APIENTRYP PFNGLTEXCOORD2FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; #define glTexCoord2fv glad_glTexCoord2fv typedef void (APIENTRYP PFNGLTEXCOORD2IPROC)(GLint s, GLint t); GLAPI PFNGLTEXCOORD2IPROC glad_glTexCoord2i; #define glTexCoord2i glad_glTexCoord2i typedef void (APIENTRYP PFNGLTEXCOORD2IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; #define glTexCoord2iv glad_glTexCoord2iv typedef void (APIENTRYP PFNGLTEXCOORD2SPROC)(GLshort s, GLshort t); GLAPI PFNGLTEXCOORD2SPROC glad_glTexCoord2s; #define glTexCoord2s glad_glTexCoord2s typedef void (APIENTRYP PFNGLTEXCOORD2SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; #define glTexCoord2sv glad_glTexCoord2sv typedef void (APIENTRYP PFNGLTEXCOORD3DPROC)(GLdouble s, GLdouble t, GLdouble r); GLAPI PFNGLTEXCOORD3DPROC glad_glTexCoord3d; #define glTexCoord3d glad_glTexCoord3d typedef void (APIENTRYP PFNGLTEXCOORD3DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; #define glTexCoord3dv glad_glTexCoord3dv typedef void (APIENTRYP PFNGLTEXCOORD3FPROC)(GLfloat s, GLfloat t, GLfloat r); GLAPI PFNGLTEXCOORD3FPROC glad_glTexCoord3f; #define glTexCoord3f glad_glTexCoord3f typedef void (APIENTRYP PFNGLTEXCOORD3FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; #define glTexCoord3fv glad_glTexCoord3fv typedef void (APIENTRYP PFNGLTEXCOORD3IPROC)(GLint s, GLint t, GLint r); GLAPI PFNGLTEXCOORD3IPROC glad_glTexCoord3i; #define glTexCoord3i glad_glTexCoord3i typedef void (APIENTRYP PFNGLTEXCOORD3IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; #define glTexCoord3iv glad_glTexCoord3iv typedef void (APIENTRYP PFNGLTEXCOORD3SPROC)(GLshort s, GLshort t, GLshort r); GLAPI PFNGLTEXCOORD3SPROC glad_glTexCoord3s; #define glTexCoord3s glad_glTexCoord3s typedef void (APIENTRYP PFNGLTEXCOORD3SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; #define glTexCoord3sv glad_glTexCoord3sv typedef void (APIENTRYP PFNGLTEXCOORD4DPROC)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); GLAPI PFNGLTEXCOORD4DPROC glad_glTexCoord4d; #define glTexCoord4d glad_glTexCoord4d typedef void (APIENTRYP PFNGLTEXCOORD4DVPROC)(const GLdouble *v); GLAPI PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; #define glTexCoord4dv glad_glTexCoord4dv typedef void (APIENTRYP PFNGLTEXCOORD4FPROC)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); GLAPI PFNGLTEXCOORD4FPROC glad_glTexCoord4f; #define glTexCoord4f glad_glTexCoord4f typedef void (APIENTRYP PFNGLTEXCOORD4FVPROC)(const GLfloat *v); GLAPI PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; #define glTexCoord4fv glad_glTexCoord4fv typedef void (APIENTRYP PFNGLTEXCOORD4IPROC)(GLint s, GLint t, GLint r, GLint q); GLAPI PFNGLTEXCOORD4IPROC glad_glTexCoord4i; #define glTexCoord4i glad_glTexCoord4i typedef void (APIENTRYP PFNGLTEXCOORD4IVPROC)(const GLint *v); GLAPI PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; #define glTexCoord4iv glad_glTexCoord4iv typedef void (APIENTRYP PFNGLTEXCOORD4SPROC)(GLshort s, GLshort t, GLshort r, GLshort q); GLAPI PFNGLTEXCOORD4SPROC glad_glTexCoord4s; #define glTexCoord4s glad_glTexCoord4s typedef void (APIENTRYP PFNGLTEXCOORD4SVPROC)(const GLshort *v); GLAPI PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; #define glTexCoord4sv glad_glTexCoord4sv typedef void (APIENTRYP PFNGLVERTEX2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLVERTEX2DPROC glad_glVertex2d; #define glVertex2d glad_glVertex2d typedef void (APIENTRYP PFNGLVERTEX2DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX2DVPROC glad_glVertex2dv; #define glVertex2dv glad_glVertex2dv typedef void (APIENTRYP PFNGLVERTEX2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLVERTEX2FPROC glad_glVertex2f; #define glVertex2f glad_glVertex2f typedef void (APIENTRYP PFNGLVERTEX2FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX2FVPROC glad_glVertex2fv; #define glVertex2fv glad_glVertex2fv typedef void (APIENTRYP PFNGLVERTEX2IPROC)(GLint x, GLint y); GLAPI PFNGLVERTEX2IPROC glad_glVertex2i; #define glVertex2i glad_glVertex2i typedef void (APIENTRYP PFNGLVERTEX2IVPROC)(const GLint *v); GLAPI PFNGLVERTEX2IVPROC glad_glVertex2iv; #define glVertex2iv glad_glVertex2iv typedef void (APIENTRYP PFNGLVERTEX2SPROC)(GLshort x, GLshort y); GLAPI PFNGLVERTEX2SPROC glad_glVertex2s; #define glVertex2s glad_glVertex2s typedef void (APIENTRYP PFNGLVERTEX2SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX2SVPROC glad_glVertex2sv; #define glVertex2sv glad_glVertex2sv typedef void (APIENTRYP PFNGLVERTEX3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLVERTEX3DPROC glad_glVertex3d; #define glVertex3d glad_glVertex3d typedef void (APIENTRYP PFNGLVERTEX3DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX3DVPROC glad_glVertex3dv; #define glVertex3dv glad_glVertex3dv typedef void (APIENTRYP PFNGLVERTEX3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLVERTEX3FPROC glad_glVertex3f; #define glVertex3f glad_glVertex3f typedef void (APIENTRYP PFNGLVERTEX3FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX3FVPROC glad_glVertex3fv; #define glVertex3fv glad_glVertex3fv typedef void (APIENTRYP PFNGLVERTEX3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLVERTEX3IPROC glad_glVertex3i; #define glVertex3i glad_glVertex3i typedef void (APIENTRYP PFNGLVERTEX3IVPROC)(const GLint *v); GLAPI PFNGLVERTEX3IVPROC glad_glVertex3iv; #define glVertex3iv glad_glVertex3iv typedef void (APIENTRYP PFNGLVERTEX3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLVERTEX3SPROC glad_glVertex3s; #define glVertex3s glad_glVertex3s typedef void (APIENTRYP PFNGLVERTEX3SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX3SVPROC glad_glVertex3sv; #define glVertex3sv glad_glVertex3sv typedef void (APIENTRYP PFNGLVERTEX4DPROC)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLVERTEX4DPROC glad_glVertex4d; #define glVertex4d glad_glVertex4d typedef void (APIENTRYP PFNGLVERTEX4DVPROC)(const GLdouble *v); GLAPI PFNGLVERTEX4DVPROC glad_glVertex4dv; #define glVertex4dv glad_glVertex4dv typedef void (APIENTRYP PFNGLVERTEX4FPROC)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLVERTEX4FPROC glad_glVertex4f; #define glVertex4f glad_glVertex4f typedef void (APIENTRYP PFNGLVERTEX4FVPROC)(const GLfloat *v); GLAPI PFNGLVERTEX4FVPROC glad_glVertex4fv; #define glVertex4fv glad_glVertex4fv typedef void (APIENTRYP PFNGLVERTEX4IPROC)(GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLVERTEX4IPROC glad_glVertex4i; #define glVertex4i glad_glVertex4i typedef void (APIENTRYP PFNGLVERTEX4IVPROC)(const GLint *v); GLAPI PFNGLVERTEX4IVPROC glad_glVertex4iv; #define glVertex4iv glad_glVertex4iv typedef void (APIENTRYP PFNGLVERTEX4SPROC)(GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLVERTEX4SPROC glad_glVertex4s; #define glVertex4s glad_glVertex4s typedef void (APIENTRYP PFNGLVERTEX4SVPROC)(const GLshort *v); GLAPI PFNGLVERTEX4SVPROC glad_glVertex4sv; #define glVertex4sv glad_glVertex4sv typedef void (APIENTRYP PFNGLCLIPPLANEPROC)(GLenum plane, const GLdouble *equation); GLAPI PFNGLCLIPPLANEPROC glad_glClipPlane; #define glClipPlane glad_glClipPlane typedef void (APIENTRYP PFNGLCOLORMATERIALPROC)(GLenum face, GLenum mode); GLAPI PFNGLCOLORMATERIALPROC glad_glColorMaterial; #define glColorMaterial glad_glColorMaterial typedef void (APIENTRYP PFNGLFOGFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLFOGFPROC glad_glFogf; #define glFogf glad_glFogf typedef void (APIENTRYP PFNGLFOGFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLFOGFVPROC glad_glFogfv; #define glFogfv glad_glFogfv typedef void (APIENTRYP PFNGLFOGIPROC)(GLenum pname, GLint param); GLAPI PFNGLFOGIPROC glad_glFogi; #define glFogi glad_glFogi typedef void (APIENTRYP PFNGLFOGIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLFOGIVPROC glad_glFogiv; #define glFogiv glad_glFogiv typedef void (APIENTRYP PFNGLLIGHTFPROC)(GLenum light, GLenum pname, GLfloat param); GLAPI PFNGLLIGHTFPROC glad_glLightf; #define glLightf glad_glLightf typedef void (APIENTRYP PFNGLLIGHTFVPROC)(GLenum light, GLenum pname, const GLfloat *params); GLAPI PFNGLLIGHTFVPROC glad_glLightfv; #define glLightfv glad_glLightfv typedef void (APIENTRYP PFNGLLIGHTIPROC)(GLenum light, GLenum pname, GLint param); GLAPI PFNGLLIGHTIPROC glad_glLighti; #define glLighti glad_glLighti typedef void (APIENTRYP PFNGLLIGHTIVPROC)(GLenum light, GLenum pname, const GLint *params); GLAPI PFNGLLIGHTIVPROC glad_glLightiv; #define glLightiv glad_glLightiv typedef void (APIENTRYP PFNGLLIGHTMODELFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLLIGHTMODELFPROC glad_glLightModelf; #define glLightModelf glad_glLightModelf typedef void (APIENTRYP PFNGLLIGHTMODELFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLLIGHTMODELFVPROC glad_glLightModelfv; #define glLightModelfv glad_glLightModelfv typedef void (APIENTRYP PFNGLLIGHTMODELIPROC)(GLenum pname, GLint param); GLAPI PFNGLLIGHTMODELIPROC glad_glLightModeli; #define glLightModeli glad_glLightModeli typedef void (APIENTRYP PFNGLLIGHTMODELIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLLIGHTMODELIVPROC glad_glLightModeliv; #define glLightModeliv glad_glLightModeliv typedef void (APIENTRYP PFNGLLINESTIPPLEPROC)(GLint factor, GLushort pattern); GLAPI PFNGLLINESTIPPLEPROC glad_glLineStipple; #define glLineStipple glad_glLineStipple typedef void (APIENTRYP PFNGLMATERIALFPROC)(GLenum face, GLenum pname, GLfloat param); GLAPI PFNGLMATERIALFPROC glad_glMaterialf; #define glMaterialf glad_glMaterialf typedef void (APIENTRYP PFNGLMATERIALFVPROC)(GLenum face, GLenum pname, const GLfloat *params); GLAPI PFNGLMATERIALFVPROC glad_glMaterialfv; #define glMaterialfv glad_glMaterialfv typedef void (APIENTRYP PFNGLMATERIALIPROC)(GLenum face, GLenum pname, GLint param); GLAPI PFNGLMATERIALIPROC glad_glMateriali; #define glMateriali glad_glMateriali typedef void (APIENTRYP PFNGLMATERIALIVPROC)(GLenum face, GLenum pname, const GLint *params); GLAPI PFNGLMATERIALIVPROC glad_glMaterialiv; #define glMaterialiv glad_glMaterialiv typedef void (APIENTRYP PFNGLPOLYGONSTIPPLEPROC)(const GLubyte *mask); GLAPI PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; #define glPolygonStipple glad_glPolygonStipple typedef void (APIENTRYP PFNGLSHADEMODELPROC)(GLenum mode); GLAPI PFNGLSHADEMODELPROC glad_glShadeModel; #define glShadeModel glad_glShadeModel typedef void (APIENTRYP PFNGLTEXENVFPROC)(GLenum target, GLenum pname, GLfloat param); GLAPI PFNGLTEXENVFPROC glad_glTexEnvf; #define glTexEnvf glad_glTexEnvf typedef void (APIENTRYP PFNGLTEXENVFVPROC)(GLenum target, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXENVFVPROC glad_glTexEnvfv; #define glTexEnvfv glad_glTexEnvfv typedef void (APIENTRYP PFNGLTEXENVIPROC)(GLenum target, GLenum pname, GLint param); GLAPI PFNGLTEXENVIPROC glad_glTexEnvi; #define glTexEnvi glad_glTexEnvi typedef void (APIENTRYP PFNGLTEXENVIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXENVIVPROC glad_glTexEnviv; #define glTexEnviv glad_glTexEnviv typedef void (APIENTRYP PFNGLTEXGENDPROC)(GLenum coord, GLenum pname, GLdouble param); GLAPI PFNGLTEXGENDPROC glad_glTexGend; #define glTexGend glad_glTexGend typedef void (APIENTRYP PFNGLTEXGENDVPROC)(GLenum coord, GLenum pname, const GLdouble *params); GLAPI PFNGLTEXGENDVPROC glad_glTexGendv; #define glTexGendv glad_glTexGendv typedef void (APIENTRYP PFNGLTEXGENFPROC)(GLenum coord, GLenum pname, GLfloat param); GLAPI PFNGLTEXGENFPROC glad_glTexGenf; #define glTexGenf glad_glTexGenf typedef void (APIENTRYP PFNGLTEXGENFVPROC)(GLenum coord, GLenum pname, const GLfloat *params); GLAPI PFNGLTEXGENFVPROC glad_glTexGenfv; #define glTexGenfv glad_glTexGenfv typedef void (APIENTRYP PFNGLTEXGENIPROC)(GLenum coord, GLenum pname, GLint param); GLAPI PFNGLTEXGENIPROC glad_glTexGeni; #define glTexGeni glad_glTexGeni typedef void (APIENTRYP PFNGLTEXGENIVPROC)(GLenum coord, GLenum pname, const GLint *params); GLAPI PFNGLTEXGENIVPROC glad_glTexGeniv; #define glTexGeniv glad_glTexGeniv typedef void (APIENTRYP PFNGLFEEDBACKBUFFERPROC)(GLsizei size, GLenum type, GLfloat *buffer); GLAPI PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; #define glFeedbackBuffer glad_glFeedbackBuffer typedef void (APIENTRYP PFNGLSELECTBUFFERPROC)(GLsizei size, GLuint *buffer); GLAPI PFNGLSELECTBUFFERPROC glad_glSelectBuffer; #define glSelectBuffer glad_glSelectBuffer typedef GLint (APIENTRYP PFNGLRENDERMODEPROC)(GLenum mode); GLAPI PFNGLRENDERMODEPROC glad_glRenderMode; #define glRenderMode glad_glRenderMode typedef void (APIENTRYP PFNGLINITNAMESPROC)(void); GLAPI PFNGLINITNAMESPROC glad_glInitNames; #define glInitNames glad_glInitNames typedef void (APIENTRYP PFNGLLOADNAMEPROC)(GLuint name); GLAPI PFNGLLOADNAMEPROC glad_glLoadName; #define glLoadName glad_glLoadName typedef void (APIENTRYP PFNGLPASSTHROUGHPROC)(GLfloat token); GLAPI PFNGLPASSTHROUGHPROC glad_glPassThrough; #define glPassThrough glad_glPassThrough typedef void (APIENTRYP PFNGLPOPNAMEPROC)(void); GLAPI PFNGLPOPNAMEPROC glad_glPopName; #define glPopName glad_glPopName typedef void (APIENTRYP PFNGLPUSHNAMEPROC)(GLuint name); GLAPI PFNGLPUSHNAMEPROC glad_glPushName; #define glPushName glad_glPushName typedef void (APIENTRYP PFNGLCLEARACCUMPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLCLEARACCUMPROC glad_glClearAccum; #define glClearAccum glad_glClearAccum typedef void (APIENTRYP PFNGLCLEARINDEXPROC)(GLfloat c); GLAPI PFNGLCLEARINDEXPROC glad_glClearIndex; #define glClearIndex glad_glClearIndex typedef void (APIENTRYP PFNGLINDEXMASKPROC)(GLuint mask); GLAPI PFNGLINDEXMASKPROC glad_glIndexMask; #define glIndexMask glad_glIndexMask typedef void (APIENTRYP PFNGLACCUMPROC)(GLenum op, GLfloat value); GLAPI PFNGLACCUMPROC glad_glAccum; #define glAccum glad_glAccum typedef void (APIENTRYP PFNGLPOPATTRIBPROC)(void); GLAPI PFNGLPOPATTRIBPROC glad_glPopAttrib; #define glPopAttrib glad_glPopAttrib typedef void (APIENTRYP PFNGLPUSHATTRIBPROC)(GLbitfield mask); GLAPI PFNGLPUSHATTRIBPROC glad_glPushAttrib; #define glPushAttrib glad_glPushAttrib typedef void (APIENTRYP PFNGLMAP1DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); GLAPI PFNGLMAP1DPROC glad_glMap1d; #define glMap1d glad_glMap1d typedef void (APIENTRYP PFNGLMAP1FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); GLAPI PFNGLMAP1FPROC glad_glMap1f; #define glMap1f glad_glMap1f typedef void (APIENTRYP PFNGLMAP2DPROC)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); GLAPI PFNGLMAP2DPROC glad_glMap2d; #define glMap2d glad_glMap2d typedef void (APIENTRYP PFNGLMAP2FPROC)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); GLAPI PFNGLMAP2FPROC glad_glMap2f; #define glMap2f glad_glMap2f typedef void (APIENTRYP PFNGLMAPGRID1DPROC)(GLint un, GLdouble u1, GLdouble u2); GLAPI PFNGLMAPGRID1DPROC glad_glMapGrid1d; #define glMapGrid1d glad_glMapGrid1d typedef void (APIENTRYP PFNGLMAPGRID1FPROC)(GLint un, GLfloat u1, GLfloat u2); GLAPI PFNGLMAPGRID1FPROC glad_glMapGrid1f; #define glMapGrid1f glad_glMapGrid1f typedef void (APIENTRYP PFNGLMAPGRID2DPROC)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); GLAPI PFNGLMAPGRID2DPROC glad_glMapGrid2d; #define glMapGrid2d glad_glMapGrid2d typedef void (APIENTRYP PFNGLMAPGRID2FPROC)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); GLAPI PFNGLMAPGRID2FPROC glad_glMapGrid2f; #define glMapGrid2f glad_glMapGrid2f typedef void (APIENTRYP PFNGLEVALCOORD1DPROC)(GLdouble u); GLAPI PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; #define glEvalCoord1d glad_glEvalCoord1d typedef void (APIENTRYP PFNGLEVALCOORD1DVPROC)(const GLdouble *u); GLAPI PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; #define glEvalCoord1dv glad_glEvalCoord1dv typedef void (APIENTRYP PFNGLEVALCOORD1FPROC)(GLfloat u); GLAPI PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; #define glEvalCoord1f glad_glEvalCoord1f typedef void (APIENTRYP PFNGLEVALCOORD1FVPROC)(const GLfloat *u); GLAPI PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; #define glEvalCoord1fv glad_glEvalCoord1fv typedef void (APIENTRYP PFNGLEVALCOORD2DPROC)(GLdouble u, GLdouble v); GLAPI PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; #define glEvalCoord2d glad_glEvalCoord2d typedef void (APIENTRYP PFNGLEVALCOORD2DVPROC)(const GLdouble *u); GLAPI PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; #define glEvalCoord2dv glad_glEvalCoord2dv typedef void (APIENTRYP PFNGLEVALCOORD2FPROC)(GLfloat u, GLfloat v); GLAPI PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; #define glEvalCoord2f glad_glEvalCoord2f typedef void (APIENTRYP PFNGLEVALCOORD2FVPROC)(const GLfloat *u); GLAPI PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; #define glEvalCoord2fv glad_glEvalCoord2fv typedef void (APIENTRYP PFNGLEVALMESH1PROC)(GLenum mode, GLint i1, GLint i2); GLAPI PFNGLEVALMESH1PROC glad_glEvalMesh1; #define glEvalMesh1 glad_glEvalMesh1 typedef void (APIENTRYP PFNGLEVALPOINT1PROC)(GLint i); GLAPI PFNGLEVALPOINT1PROC glad_glEvalPoint1; #define glEvalPoint1 glad_glEvalPoint1 typedef void (APIENTRYP PFNGLEVALMESH2PROC)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); GLAPI PFNGLEVALMESH2PROC glad_glEvalMesh2; #define glEvalMesh2 glad_glEvalMesh2 typedef void (APIENTRYP PFNGLEVALPOINT2PROC)(GLint i, GLint j); GLAPI PFNGLEVALPOINT2PROC glad_glEvalPoint2; #define glEvalPoint2 glad_glEvalPoint2 typedef void (APIENTRYP PFNGLALPHAFUNCPROC)(GLenum func, GLfloat ref); GLAPI PFNGLALPHAFUNCPROC glad_glAlphaFunc; #define glAlphaFunc glad_glAlphaFunc typedef void (APIENTRYP PFNGLPIXELZOOMPROC)(GLfloat xfactor, GLfloat yfactor); GLAPI PFNGLPIXELZOOMPROC glad_glPixelZoom; #define glPixelZoom glad_glPixelZoom typedef void (APIENTRYP PFNGLPIXELTRANSFERFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; #define glPixelTransferf glad_glPixelTransferf typedef void (APIENTRYP PFNGLPIXELTRANSFERIPROC)(GLenum pname, GLint param); GLAPI PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; #define glPixelTransferi glad_glPixelTransferi typedef void (APIENTRYP PFNGLPIXELMAPFVPROC)(GLenum map, GLsizei mapsize, const GLfloat *values); GLAPI PFNGLPIXELMAPFVPROC glad_glPixelMapfv; #define glPixelMapfv glad_glPixelMapfv typedef void (APIENTRYP PFNGLPIXELMAPUIVPROC)(GLenum map, GLsizei mapsize, const GLuint *values); GLAPI PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; #define glPixelMapuiv glad_glPixelMapuiv typedef void (APIENTRYP PFNGLPIXELMAPUSVPROC)(GLenum map, GLsizei mapsize, const GLushort *values); GLAPI PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; #define glPixelMapusv glad_glPixelMapusv typedef void (APIENTRYP PFNGLCOPYPIXELSPROC)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); GLAPI PFNGLCOPYPIXELSPROC glad_glCopyPixels; #define glCopyPixels glad_glCopyPixels typedef void (APIENTRYP PFNGLDRAWPIXELSPROC)(GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLDRAWPIXELSPROC glad_glDrawPixels; #define glDrawPixels glad_glDrawPixels typedef void (APIENTRYP PFNGLGETCLIPPLANEPROC)(GLenum plane, GLdouble *equation); GLAPI PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; #define glGetClipPlane glad_glGetClipPlane typedef void (APIENTRYP PFNGLGETLIGHTFVPROC)(GLenum light, GLenum pname, GLfloat *params); GLAPI PFNGLGETLIGHTFVPROC glad_glGetLightfv; #define glGetLightfv glad_glGetLightfv typedef void (APIENTRYP PFNGLGETLIGHTIVPROC)(GLenum light, GLenum pname, GLint *params); GLAPI PFNGLGETLIGHTIVPROC glad_glGetLightiv; #define glGetLightiv glad_glGetLightiv typedef void (APIENTRYP PFNGLGETMAPDVPROC)(GLenum target, GLenum query, GLdouble *v); GLAPI PFNGLGETMAPDVPROC glad_glGetMapdv; #define glGetMapdv glad_glGetMapdv typedef void (APIENTRYP PFNGLGETMAPFVPROC)(GLenum target, GLenum query, GLfloat *v); GLAPI PFNGLGETMAPFVPROC glad_glGetMapfv; #define glGetMapfv glad_glGetMapfv typedef void (APIENTRYP PFNGLGETMAPIVPROC)(GLenum target, GLenum query, GLint *v); GLAPI PFNGLGETMAPIVPROC glad_glGetMapiv; #define glGetMapiv glad_glGetMapiv typedef void (APIENTRYP PFNGLGETMATERIALFVPROC)(GLenum face, GLenum pname, GLfloat *params); GLAPI PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; #define glGetMaterialfv glad_glGetMaterialfv typedef void (APIENTRYP PFNGLGETMATERIALIVPROC)(GLenum face, GLenum pname, GLint *params); GLAPI PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; #define glGetMaterialiv glad_glGetMaterialiv typedef void (APIENTRYP PFNGLGETPIXELMAPFVPROC)(GLenum map, GLfloat *values); GLAPI PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; #define glGetPixelMapfv glad_glGetPixelMapfv typedef void (APIENTRYP PFNGLGETPIXELMAPUIVPROC)(GLenum map, GLuint *values); GLAPI PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; #define glGetPixelMapuiv glad_glGetPixelMapuiv typedef void (APIENTRYP PFNGLGETPIXELMAPUSVPROC)(GLenum map, GLushort *values); GLAPI PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; #define glGetPixelMapusv glad_glGetPixelMapusv typedef void (APIENTRYP PFNGLGETPOLYGONSTIPPLEPROC)(GLubyte *mask); GLAPI PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; #define glGetPolygonStipple glad_glGetPolygonStipple typedef void (APIENTRYP PFNGLGETTEXENVFVPROC)(GLenum target, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; #define glGetTexEnvfv glad_glGetTexEnvfv typedef void (APIENTRYP PFNGLGETTEXENVIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; #define glGetTexEnviv glad_glGetTexEnviv typedef void (APIENTRYP PFNGLGETTEXGENDVPROC)(GLenum coord, GLenum pname, GLdouble *params); GLAPI PFNGLGETTEXGENDVPROC glad_glGetTexGendv; #define glGetTexGendv glad_glGetTexGendv typedef void (APIENTRYP PFNGLGETTEXGENFVPROC)(GLenum coord, GLenum pname, GLfloat *params); GLAPI PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; #define glGetTexGenfv glad_glGetTexGenfv typedef void (APIENTRYP PFNGLGETTEXGENIVPROC)(GLenum coord, GLenum pname, GLint *params); GLAPI PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; #define glGetTexGeniv glad_glGetTexGeniv typedef GLboolean (APIENTRYP PFNGLISLISTPROC)(GLuint list); GLAPI PFNGLISLISTPROC glad_glIsList; #define glIsList glad_glIsList typedef void (APIENTRYP PFNGLFRUSTUMPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); GLAPI PFNGLFRUSTUMPROC glad_glFrustum; #define glFrustum glad_glFrustum typedef void (APIENTRYP PFNGLLOADIDENTITYPROC)(void); GLAPI PFNGLLOADIDENTITYPROC glad_glLoadIdentity; #define glLoadIdentity glad_glLoadIdentity typedef void (APIENTRYP PFNGLLOADMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; #define glLoadMatrixf glad_glLoadMatrixf typedef void (APIENTRYP PFNGLLOADMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; #define glLoadMatrixd glad_glLoadMatrixd typedef void (APIENTRYP PFNGLMATRIXMODEPROC)(GLenum mode); GLAPI PFNGLMATRIXMODEPROC glad_glMatrixMode; #define glMatrixMode glad_glMatrixMode typedef void (APIENTRYP PFNGLMULTMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLMULTMATRIXFPROC glad_glMultMatrixf; #define glMultMatrixf glad_glMultMatrixf typedef void (APIENTRYP PFNGLMULTMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLMULTMATRIXDPROC glad_glMultMatrixd; #define glMultMatrixd glad_glMultMatrixd typedef void (APIENTRYP PFNGLORTHOPROC)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); GLAPI PFNGLORTHOPROC glad_glOrtho; #define glOrtho glad_glOrtho typedef void (APIENTRYP PFNGLPOPMATRIXPROC)(void); GLAPI PFNGLPOPMATRIXPROC glad_glPopMatrix; #define glPopMatrix glad_glPopMatrix typedef void (APIENTRYP PFNGLPUSHMATRIXPROC)(void); GLAPI PFNGLPUSHMATRIXPROC glad_glPushMatrix; #define glPushMatrix glad_glPushMatrix typedef void (APIENTRYP PFNGLROTATEDPROC)(GLdouble angle, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLROTATEDPROC glad_glRotated; #define glRotated glad_glRotated typedef void (APIENTRYP PFNGLROTATEFPROC)(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLROTATEFPROC glad_glRotatef; #define glRotatef glad_glRotatef typedef void (APIENTRYP PFNGLSCALEDPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLSCALEDPROC glad_glScaled; #define glScaled glad_glScaled typedef void (APIENTRYP PFNGLSCALEFPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLSCALEFPROC glad_glScalef; #define glScalef glad_glScalef typedef void (APIENTRYP PFNGLTRANSLATEDPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLTRANSLATEDPROC glad_glTranslated; #define glTranslated glad_glTranslated typedef void (APIENTRYP PFNGLTRANSLATEFPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLTRANSLATEFPROC glad_glTranslatef; #define glTranslatef glad_glTranslatef #endif #ifndef GL_VERSION_1_1 #define GL_VERSION_1_1 1 GLAPI int GLAD_GL_VERSION_1_1; typedef void (APIENTRYP PFNGLDRAWARRAYSPROC)(GLenum mode, GLint first, GLsizei count); GLAPI PFNGLDRAWARRAYSPROC glad_glDrawArrays; #define glDrawArrays glad_glDrawArrays typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices); GLAPI PFNGLDRAWELEMENTSPROC glad_glDrawElements; #define glDrawElements glad_glDrawElements typedef void (APIENTRYP PFNGLGETPOINTERVPROC)(GLenum pname, void **params); GLAPI PFNGLGETPOINTERVPROC glad_glGetPointerv; #define glGetPointerv glad_glGetPointerv typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC)(GLfloat factor, GLfloat units); GLAPI PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; #define glPolygonOffset glad_glPolygonOffset typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); GLAPI PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; #define glCopyTexImage1D glad_glCopyTexImage1D typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); GLAPI PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; #define glCopyTexImage2D glad_glCopyTexImage2D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); GLAPI PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; #define glCopyTexSubImage1D glad_glCopyTexSubImage1D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; #define glCopyTexSubImage2D glad_glCopyTexSubImage2D typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; #define glTexSubImage1D glad_glTexSubImage1D typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; #define glTexSubImage2D glad_glTexSubImage2D typedef void (APIENTRYP PFNGLBINDTEXTUREPROC)(GLenum target, GLuint texture); GLAPI PFNGLBINDTEXTUREPROC glad_glBindTexture; #define glBindTexture glad_glBindTexture typedef void (APIENTRYP PFNGLDELETETEXTURESPROC)(GLsizei n, const GLuint *textures); GLAPI PFNGLDELETETEXTURESPROC glad_glDeleteTextures; #define glDeleteTextures glad_glDeleteTextures typedef void (APIENTRYP PFNGLGENTEXTURESPROC)(GLsizei n, GLuint *textures); GLAPI PFNGLGENTEXTURESPROC glad_glGenTextures; #define glGenTextures glad_glGenTextures typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC)(GLuint texture); GLAPI PFNGLISTEXTUREPROC glad_glIsTexture; #define glIsTexture glad_glIsTexture typedef void (APIENTRYP PFNGLARRAYELEMENTPROC)(GLint i); GLAPI PFNGLARRAYELEMENTPROC glad_glArrayElement; #define glArrayElement glad_glArrayElement typedef void (APIENTRYP PFNGLCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLCOLORPOINTERPROC glad_glColorPointer; #define glColorPointer glad_glColorPointer typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEPROC)(GLenum array); GLAPI PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; #define glDisableClientState glad_glDisableClientState typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERPROC)(GLsizei stride, const void *pointer); GLAPI PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; #define glEdgeFlagPointer glad_glEdgeFlagPointer typedef void (APIENTRYP PFNGLENABLECLIENTSTATEPROC)(GLenum array); GLAPI PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; #define glEnableClientState glad_glEnableClientState typedef void (APIENTRYP PFNGLINDEXPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLINDEXPOINTERPROC glad_glIndexPointer; #define glIndexPointer glad_glIndexPointer typedef void (APIENTRYP PFNGLINTERLEAVEDARRAYSPROC)(GLenum format, GLsizei stride, const void *pointer); GLAPI PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; #define glInterleavedArrays glad_glInterleavedArrays typedef void (APIENTRYP PFNGLNORMALPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLNORMALPOINTERPROC glad_glNormalPointer; #define glNormalPointer glad_glNormalPointer typedef void (APIENTRYP PFNGLTEXCOORDPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; #define glTexCoordPointer glad_glTexCoordPointer typedef void (APIENTRYP PFNGLVERTEXPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXPOINTERPROC glad_glVertexPointer; #define glVertexPointer glad_glVertexPointer typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTPROC)(GLsizei n, const GLuint *textures, GLboolean *residences); GLAPI PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; #define glAreTexturesResident glad_glAreTexturesResident typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESPROC)(GLsizei n, const GLuint *textures, const GLfloat *priorities); GLAPI PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; #define glPrioritizeTextures glad_glPrioritizeTextures typedef void (APIENTRYP PFNGLINDEXUBPROC)(GLubyte c); GLAPI PFNGLINDEXUBPROC glad_glIndexub; #define glIndexub glad_glIndexub typedef void (APIENTRYP PFNGLINDEXUBVPROC)(const GLubyte *c); GLAPI PFNGLINDEXUBVPROC glad_glIndexubv; #define glIndexubv glad_glIndexubv typedef void (APIENTRYP PFNGLPOPCLIENTATTRIBPROC)(void); GLAPI PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; #define glPopClientAttrib glad_glPopClientAttrib typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBPROC)(GLbitfield mask); GLAPI PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; #define glPushClientAttrib glad_glPushClientAttrib #endif #ifndef GL_VERSION_1_2 #define GL_VERSION_1_2 1 GLAPI int GLAD_GL_VERSION_1_2; typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); GLAPI PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; #define glDrawRangeElements glad_glDrawRangeElements typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXIMAGE3DPROC glad_glTexImage3D; #define glTexImage3D glad_glTexImage3D typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); GLAPI PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; #define glTexSubImage3D glad_glTexSubImage3D typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); GLAPI PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; #define glCopyTexSubImage3D glad_glCopyTexSubImage3D #endif #ifndef GL_VERSION_1_3 #define GL_VERSION_1_3 1 GLAPI int GLAD_GL_VERSION_1_3; typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC)(GLenum texture); GLAPI PFNGLACTIVETEXTUREPROC glad_glActiveTexture; #define glActiveTexture glad_glActiveTexture typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC)(GLfloat value, GLboolean invert); GLAPI PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; #define glSampleCoverage glad_glSampleCoverage typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; #define glCompressedTexImage3D glad_glCompressedTexImage3D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; #define glCompressedTexImage2D glad_glCompressedTexImage2D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; #define glCompressedTexImage1D glad_glCompressedTexImage1D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; #define glCompressedTexSubImage3D glad_glCompressedTexSubImage3D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; #define glCompressedTexSubImage2D glad_glCompressedTexSubImage2D typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); GLAPI PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; #define glCompressedTexSubImage1D glad_glCompressedTexSubImage1D typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC)(GLenum target, GLint level, void *img); GLAPI PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; #define glGetCompressedTexImage glad_glGetCompressedTexImage typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC)(GLenum texture); GLAPI PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; #define glClientActiveTexture glad_glClientActiveTexture typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC)(GLenum target, GLdouble s); GLAPI PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; #define glMultiTexCoord1d glad_glMultiTexCoord1d typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; #define glMultiTexCoord1dv glad_glMultiTexCoord1dv typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC)(GLenum target, GLfloat s); GLAPI PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; #define glMultiTexCoord1f glad_glMultiTexCoord1f typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; #define glMultiTexCoord1fv glad_glMultiTexCoord1fv typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC)(GLenum target, GLint s); GLAPI PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; #define glMultiTexCoord1i glad_glMultiTexCoord1i typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; #define glMultiTexCoord1iv glad_glMultiTexCoord1iv typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC)(GLenum target, GLshort s); GLAPI PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; #define glMultiTexCoord1s glad_glMultiTexCoord1s typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; #define glMultiTexCoord1sv glad_glMultiTexCoord1sv typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC)(GLenum target, GLdouble s, GLdouble t); GLAPI PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; #define glMultiTexCoord2d glad_glMultiTexCoord2d typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; #define glMultiTexCoord2dv glad_glMultiTexCoord2dv typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC)(GLenum target, GLfloat s, GLfloat t); GLAPI PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; #define glMultiTexCoord2f glad_glMultiTexCoord2f typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; #define glMultiTexCoord2fv glad_glMultiTexCoord2fv typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC)(GLenum target, GLint s, GLint t); GLAPI PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; #define glMultiTexCoord2i glad_glMultiTexCoord2i typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; #define glMultiTexCoord2iv glad_glMultiTexCoord2iv typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC)(GLenum target, GLshort s, GLshort t); GLAPI PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; #define glMultiTexCoord2s glad_glMultiTexCoord2s typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; #define glMultiTexCoord2sv glad_glMultiTexCoord2sv typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r); GLAPI PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; #define glMultiTexCoord3d glad_glMultiTexCoord3d typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; #define glMultiTexCoord3dv glad_glMultiTexCoord3dv typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r); GLAPI PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; #define glMultiTexCoord3f glad_glMultiTexCoord3f typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; #define glMultiTexCoord3fv glad_glMultiTexCoord3fv typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC)(GLenum target, GLint s, GLint t, GLint r); GLAPI PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; #define glMultiTexCoord3i glad_glMultiTexCoord3i typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; #define glMultiTexCoord3iv glad_glMultiTexCoord3iv typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC)(GLenum target, GLshort s, GLshort t, GLshort r); GLAPI PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; #define glMultiTexCoord3s glad_glMultiTexCoord3s typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; #define glMultiTexCoord3sv glad_glMultiTexCoord3sv typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); GLAPI PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; #define glMultiTexCoord4d glad_glMultiTexCoord4d typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC)(GLenum target, const GLdouble *v); GLAPI PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; #define glMultiTexCoord4dv glad_glMultiTexCoord4dv typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); GLAPI PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; #define glMultiTexCoord4f glad_glMultiTexCoord4f typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC)(GLenum target, const GLfloat *v); GLAPI PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; #define glMultiTexCoord4fv glad_glMultiTexCoord4fv typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC)(GLenum target, GLint s, GLint t, GLint r, GLint q); GLAPI PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; #define glMultiTexCoord4i glad_glMultiTexCoord4i typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC)(GLenum target, const GLint *v); GLAPI PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; #define glMultiTexCoord4iv glad_glMultiTexCoord4iv typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); GLAPI PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; #define glMultiTexCoord4s glad_glMultiTexCoord4s typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC)(GLenum target, const GLshort *v); GLAPI PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; #define glMultiTexCoord4sv glad_glMultiTexCoord4sv typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; #define glLoadTransposeMatrixf glad_glLoadTransposeMatrixf typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; #define glLoadTransposeMatrixd glad_glLoadTransposeMatrixd typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC)(const GLfloat *m); GLAPI PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; #define glMultTransposeMatrixf glad_glMultTransposeMatrixf typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC)(const GLdouble *m); GLAPI PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; #define glMultTransposeMatrixd glad_glMultTransposeMatrixd #endif #ifndef GL_VERSION_1_4 #define GL_VERSION_1_4 1 GLAPI int GLAD_GL_VERSION_1_4; typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); GLAPI PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; #define glBlendFuncSeparate glad_glBlendFuncSeparate typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC)(GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); GLAPI PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; #define glMultiDrawArrays glad_glMultiDrawArrays typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); GLAPI PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; #define glMultiDrawElements glad_glMultiDrawElements typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC)(GLenum pname, GLfloat param); GLAPI PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; #define glPointParameterf glad_glPointParameterf typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC)(GLenum pname, const GLfloat *params); GLAPI PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; #define glPointParameterfv glad_glPointParameterfv typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC)(GLenum pname, GLint param); GLAPI PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; #define glPointParameteri glad_glPointParameteri typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC)(GLenum pname, const GLint *params); GLAPI PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; #define glPointParameteriv glad_glPointParameteriv typedef void (APIENTRYP PFNGLFOGCOORDFPROC)(GLfloat coord); GLAPI PFNGLFOGCOORDFPROC glad_glFogCoordf; #define glFogCoordf glad_glFogCoordf typedef void (APIENTRYP PFNGLFOGCOORDFVPROC)(const GLfloat *coord); GLAPI PFNGLFOGCOORDFVPROC glad_glFogCoordfv; #define glFogCoordfv glad_glFogCoordfv typedef void (APIENTRYP PFNGLFOGCOORDDPROC)(GLdouble coord); GLAPI PFNGLFOGCOORDDPROC glad_glFogCoordd; #define glFogCoordd glad_glFogCoordd typedef void (APIENTRYP PFNGLFOGCOORDDVPROC)(const GLdouble *coord); GLAPI PFNGLFOGCOORDDVPROC glad_glFogCoorddv; #define glFogCoorddv glad_glFogCoorddv typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC)(GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; #define glFogCoordPointer glad_glFogCoordPointer typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC)(GLbyte red, GLbyte green, GLbyte blue); GLAPI PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; #define glSecondaryColor3b glad_glSecondaryColor3b typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC)(const GLbyte *v); GLAPI PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; #define glSecondaryColor3bv glad_glSecondaryColor3bv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC)(GLdouble red, GLdouble green, GLdouble blue); GLAPI PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; #define glSecondaryColor3d glad_glSecondaryColor3d typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC)(const GLdouble *v); GLAPI PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; #define glSecondaryColor3dv glad_glSecondaryColor3dv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC)(GLfloat red, GLfloat green, GLfloat blue); GLAPI PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; #define glSecondaryColor3f glad_glSecondaryColor3f typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC)(const GLfloat *v); GLAPI PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; #define glSecondaryColor3fv glad_glSecondaryColor3fv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC)(GLint red, GLint green, GLint blue); GLAPI PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; #define glSecondaryColor3i glad_glSecondaryColor3i typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC)(const GLint *v); GLAPI PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; #define glSecondaryColor3iv glad_glSecondaryColor3iv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC)(GLshort red, GLshort green, GLshort blue); GLAPI PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; #define glSecondaryColor3s glad_glSecondaryColor3s typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC)(const GLshort *v); GLAPI PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; #define glSecondaryColor3sv glad_glSecondaryColor3sv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC)(GLubyte red, GLubyte green, GLubyte blue); GLAPI PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; #define glSecondaryColor3ub glad_glSecondaryColor3ub typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC)(const GLubyte *v); GLAPI PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; #define glSecondaryColor3ubv glad_glSecondaryColor3ubv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC)(GLuint red, GLuint green, GLuint blue); GLAPI PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; #define glSecondaryColor3ui glad_glSecondaryColor3ui typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC)(const GLuint *v); GLAPI PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; #define glSecondaryColor3uiv glad_glSecondaryColor3uiv typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC)(GLushort red, GLushort green, GLushort blue); GLAPI PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; #define glSecondaryColor3us glad_glSecondaryColor3us typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC)(const GLushort *v); GLAPI PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; #define glSecondaryColor3usv glad_glSecondaryColor3usv typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC)(GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; #define glSecondaryColorPointer glad_glSecondaryColorPointer typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC)(GLdouble x, GLdouble y); GLAPI PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; #define glWindowPos2d glad_glWindowPos2d typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC)(const GLdouble *v); GLAPI PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; #define glWindowPos2dv glad_glWindowPos2dv typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC)(GLfloat x, GLfloat y); GLAPI PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; #define glWindowPos2f glad_glWindowPos2f typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC)(const GLfloat *v); GLAPI PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; #define glWindowPos2fv glad_glWindowPos2fv typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC)(GLint x, GLint y); GLAPI PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; #define glWindowPos2i glad_glWindowPos2i typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC)(const GLint *v); GLAPI PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; #define glWindowPos2iv glad_glWindowPos2iv typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC)(GLshort x, GLshort y); GLAPI PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; #define glWindowPos2s glad_glWindowPos2s typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC)(const GLshort *v); GLAPI PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; #define glWindowPos2sv glad_glWindowPos2sv typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC)(GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; #define glWindowPos3d glad_glWindowPos3d typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC)(const GLdouble *v); GLAPI PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; #define glWindowPos3dv glad_glWindowPos3dv typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC)(GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; #define glWindowPos3f glad_glWindowPos3f typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC)(const GLfloat *v); GLAPI PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; #define glWindowPos3fv glad_glWindowPos3fv typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC)(GLint x, GLint y, GLint z); GLAPI PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; #define glWindowPos3i glad_glWindowPos3i typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC)(const GLint *v); GLAPI PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; #define glWindowPos3iv glad_glWindowPos3iv typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC)(GLshort x, GLshort y, GLshort z); GLAPI PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; #define glWindowPos3s glad_glWindowPos3s typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC)(const GLshort *v); GLAPI PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; #define glWindowPos3sv glad_glWindowPos3sv typedef void (APIENTRYP PFNGLBLENDCOLORPROC)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); GLAPI PFNGLBLENDCOLORPROC glad_glBlendColor; #define glBlendColor glad_glBlendColor typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC)(GLenum mode); GLAPI PFNGLBLENDEQUATIONPROC glad_glBlendEquation; #define glBlendEquation glad_glBlendEquation #endif #ifndef GL_VERSION_1_5 #define GL_VERSION_1_5 1 GLAPI int GLAD_GL_VERSION_1_5; typedef void (APIENTRYP PFNGLGENQUERIESPROC)(GLsizei n, GLuint *ids); GLAPI PFNGLGENQUERIESPROC glad_glGenQueries; #define glGenQueries glad_glGenQueries typedef void (APIENTRYP PFNGLDELETEQUERIESPROC)(GLsizei n, const GLuint *ids); GLAPI PFNGLDELETEQUERIESPROC glad_glDeleteQueries; #define glDeleteQueries glad_glDeleteQueries typedef GLboolean (APIENTRYP PFNGLISQUERYPROC)(GLuint id); GLAPI PFNGLISQUERYPROC glad_glIsQuery; #define glIsQuery glad_glIsQuery typedef void (APIENTRYP PFNGLBEGINQUERYPROC)(GLenum target, GLuint id); GLAPI PFNGLBEGINQUERYPROC glad_glBeginQuery; #define glBeginQuery glad_glBeginQuery typedef void (APIENTRYP PFNGLENDQUERYPROC)(GLenum target); GLAPI PFNGLENDQUERYPROC glad_glEndQuery; #define glEndQuery glad_glEndQuery typedef void (APIENTRYP PFNGLGETQUERYIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYIVPROC glad_glGetQueryiv; #define glGetQueryiv glad_glGetQueryiv typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC)(GLuint id, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; #define glGetQueryObjectiv glad_glGetQueryObjectiv typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC)(GLuint id, GLenum pname, GLuint *params); GLAPI PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; #define glGetQueryObjectuiv glad_glGetQueryObjectuiv typedef void (APIENTRYP PFNGLBINDBUFFERPROC)(GLenum target, GLuint buffer); GLAPI PFNGLBINDBUFFERPROC glad_glBindBuffer; #define glBindBuffer glad_glBindBuffer typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC)(GLsizei n, const GLuint *buffers); GLAPI PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; #define glDeleteBuffers glad_glDeleteBuffers typedef void (APIENTRYP PFNGLGENBUFFERSPROC)(GLsizei n, GLuint *buffers); GLAPI PFNGLGENBUFFERSPROC glad_glGenBuffers; #define glGenBuffers glad_glGenBuffers typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC)(GLuint buffer); GLAPI PFNGLISBUFFERPROC glad_glIsBuffer; #define glIsBuffer glad_glIsBuffer typedef void (APIENTRYP PFNGLBUFFERDATAPROC)(GLenum target, GLsizeiptr size, const void *data, GLenum usage); GLAPI PFNGLBUFFERDATAPROC glad_glBufferData; #define glBufferData glad_glBufferData typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, const void *data); GLAPI PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; #define glBufferSubData glad_glBufferSubData typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC)(GLenum target, GLintptr offset, GLsizeiptr size, void *data); GLAPI PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; #define glGetBufferSubData glad_glGetBufferSubData typedef void * (APIENTRYP PFNGLMAPBUFFERPROC)(GLenum target, GLenum access); GLAPI PFNGLMAPBUFFERPROC glad_glMapBuffer; #define glMapBuffer glad_glMapBuffer typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC)(GLenum target); GLAPI PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; #define glUnmapBuffer glad_glUnmapBuffer typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; #define glGetBufferParameteriv glad_glGetBufferParameteriv typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC)(GLenum target, GLenum pname, void **params); GLAPI PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; #define glGetBufferPointerv glad_glGetBufferPointerv #endif #ifndef GL_VERSION_2_0 #define GL_VERSION_2_0 1 GLAPI int GLAD_GL_VERSION_2_0; typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC)(GLenum modeRGB, GLenum modeAlpha); GLAPI PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; #define glBlendEquationSeparate glad_glBlendEquationSeparate typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC)(GLsizei n, const GLenum *bufs); GLAPI PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; #define glDrawBuffers glad_glDrawBuffers typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC)(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); GLAPI PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; #define glStencilOpSeparate glad_glStencilOpSeparate typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC)(GLenum face, GLenum func, GLint ref, GLuint mask); GLAPI PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; #define glStencilFuncSeparate glad_glStencilFuncSeparate typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC)(GLenum face, GLuint mask); GLAPI PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; #define glStencilMaskSeparate glad_glStencilMaskSeparate typedef void (APIENTRYP PFNGLATTACHSHADERPROC)(GLuint program, GLuint shader); GLAPI PFNGLATTACHSHADERPROC glad_glAttachShader; #define glAttachShader glad_glAttachShader typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC)(GLuint program, GLuint index, const GLchar *name); GLAPI PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; #define glBindAttribLocation glad_glBindAttribLocation typedef void (APIENTRYP PFNGLCOMPILESHADERPROC)(GLuint shader); GLAPI PFNGLCOMPILESHADERPROC glad_glCompileShader; #define glCompileShader glad_glCompileShader typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC)(void); GLAPI PFNGLCREATEPROGRAMPROC glad_glCreateProgram; #define glCreateProgram glad_glCreateProgram typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC)(GLenum type); GLAPI PFNGLCREATESHADERPROC glad_glCreateShader; #define glCreateShader glad_glCreateShader typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC)(GLuint program); GLAPI PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; #define glDeleteProgram glad_glDeleteProgram typedef void (APIENTRYP PFNGLDELETESHADERPROC)(GLuint shader); GLAPI PFNGLDELETESHADERPROC glad_glDeleteShader; #define glDeleteShader glad_glDeleteShader typedef void (APIENTRYP PFNGLDETACHSHADERPROC)(GLuint program, GLuint shader); GLAPI PFNGLDETACHSHADERPROC glad_glDetachShader; #define glDetachShader glad_glDetachShader typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC)(GLuint index); GLAPI PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; #define glDisableVertexAttribArray glad_glDisableVertexAttribArray typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC)(GLuint index); GLAPI PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; #define glEnableVertexAttribArray glad_glEnableVertexAttribArray typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GLAPI PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; #define glGetActiveAttrib glad_glGetActiveAttrib typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); GLAPI PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; #define glGetActiveUniform glad_glGetActiveUniform typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC)(GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); GLAPI PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; #define glGetAttachedShaders glad_glGetAttachedShaders typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; #define glGetAttribLocation glad_glGetAttribLocation typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC)(GLuint program, GLenum pname, GLint *params); GLAPI PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; #define glGetProgramiv glad_glGetProgramiv typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC)(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; #define glGetProgramInfoLog glad_glGetProgramInfoLog typedef void (APIENTRYP PFNGLGETSHADERIVPROC)(GLuint shader, GLenum pname, GLint *params); GLAPI PFNGLGETSHADERIVPROC glad_glGetShaderiv; #define glGetShaderiv glad_glGetShaderiv typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); GLAPI PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; #define glGetShaderInfoLog glad_glGetShaderInfoLog typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC)(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); GLAPI PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; #define glGetShaderSource glad_glGetShaderSource typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; #define glGetUniformLocation glad_glGetUniformLocation typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC)(GLuint program, GLint location, GLfloat *params); GLAPI PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; #define glGetUniformfv glad_glGetUniformfv typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC)(GLuint program, GLint location, GLint *params); GLAPI PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; #define glGetUniformiv glad_glGetUniformiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC)(GLuint index, GLenum pname, GLdouble *params); GLAPI PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; #define glGetVertexAttribdv glad_glGetVertexAttribdv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC)(GLuint index, GLenum pname, GLfloat *params); GLAPI PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; #define glGetVertexAttribfv glad_glGetVertexAttribfv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC)(GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; #define glGetVertexAttribiv glad_glGetVertexAttribiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC)(GLuint index, GLenum pname, void **pointer); GLAPI PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; #define glGetVertexAttribPointerv glad_glGetVertexAttribPointerv typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC)(GLuint program); GLAPI PFNGLISPROGRAMPROC glad_glIsProgram; #define glIsProgram glad_glIsProgram typedef GLboolean (APIENTRYP PFNGLISSHADERPROC)(GLuint shader); GLAPI PFNGLISSHADERPROC glad_glIsShader; #define glIsShader glad_glIsShader typedef void (APIENTRYP PFNGLLINKPROGRAMPROC)(GLuint program); GLAPI PFNGLLINKPROGRAMPROC glad_glLinkProgram; #define glLinkProgram glad_glLinkProgram typedef void (APIENTRYP PFNGLSHADERSOURCEPROC)(GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); GLAPI PFNGLSHADERSOURCEPROC glad_glShaderSource; #define glShaderSource glad_glShaderSource typedef void (APIENTRYP PFNGLUSEPROGRAMPROC)(GLuint program); GLAPI PFNGLUSEPROGRAMPROC glad_glUseProgram; #define glUseProgram glad_glUseProgram typedef void (APIENTRYP PFNGLUNIFORM1FPROC)(GLint location, GLfloat v0); GLAPI PFNGLUNIFORM1FPROC glad_glUniform1f; #define glUniform1f glad_glUniform1f typedef void (APIENTRYP PFNGLUNIFORM2FPROC)(GLint location, GLfloat v0, GLfloat v1); GLAPI PFNGLUNIFORM2FPROC glad_glUniform2f; #define glUniform2f glad_glUniform2f typedef void (APIENTRYP PFNGLUNIFORM3FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); GLAPI PFNGLUNIFORM3FPROC glad_glUniform3f; #define glUniform3f glad_glUniform3f typedef void (APIENTRYP PFNGLUNIFORM4FPROC)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); GLAPI PFNGLUNIFORM4FPROC glad_glUniform4f; #define glUniform4f glad_glUniform4f typedef void (APIENTRYP PFNGLUNIFORM1IPROC)(GLint location, GLint v0); GLAPI PFNGLUNIFORM1IPROC glad_glUniform1i; #define glUniform1i glad_glUniform1i typedef void (APIENTRYP PFNGLUNIFORM2IPROC)(GLint location, GLint v0, GLint v1); GLAPI PFNGLUNIFORM2IPROC glad_glUniform2i; #define glUniform2i glad_glUniform2i typedef void (APIENTRYP PFNGLUNIFORM3IPROC)(GLint location, GLint v0, GLint v1, GLint v2); GLAPI PFNGLUNIFORM3IPROC glad_glUniform3i; #define glUniform3i glad_glUniform3i typedef void (APIENTRYP PFNGLUNIFORM4IPROC)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); GLAPI PFNGLUNIFORM4IPROC glad_glUniform4i; #define glUniform4i glad_glUniform4i typedef void (APIENTRYP PFNGLUNIFORM1FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM1FVPROC glad_glUniform1fv; #define glUniform1fv glad_glUniform1fv typedef void (APIENTRYP PFNGLUNIFORM2FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM2FVPROC glad_glUniform2fv; #define glUniform2fv glad_glUniform2fv typedef void (APIENTRYP PFNGLUNIFORM3FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM3FVPROC glad_glUniform3fv; #define glUniform3fv glad_glUniform3fv typedef void (APIENTRYP PFNGLUNIFORM4FVPROC)(GLint location, GLsizei count, const GLfloat *value); GLAPI PFNGLUNIFORM4FVPROC glad_glUniform4fv; #define glUniform4fv glad_glUniform4fv typedef void (APIENTRYP PFNGLUNIFORM1IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM1IVPROC glad_glUniform1iv; #define glUniform1iv glad_glUniform1iv typedef void (APIENTRYP PFNGLUNIFORM2IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM2IVPROC glad_glUniform2iv; #define glUniform2iv glad_glUniform2iv typedef void (APIENTRYP PFNGLUNIFORM3IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM3IVPROC glad_glUniform3iv; #define glUniform3iv glad_glUniform3iv typedef void (APIENTRYP PFNGLUNIFORM4IVPROC)(GLint location, GLsizei count, const GLint *value); GLAPI PFNGLUNIFORM4IVPROC glad_glUniform4iv; #define glUniform4iv glad_glUniform4iv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; #define glUniformMatrix2fv glad_glUniformMatrix2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; #define glUniformMatrix3fv glad_glUniformMatrix3fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; #define glUniformMatrix4fv glad_glUniformMatrix4fv typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC)(GLuint program); GLAPI PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; #define glValidateProgram glad_glValidateProgram typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC)(GLuint index, GLdouble x); GLAPI PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; #define glVertexAttrib1d glad_glVertexAttrib1d typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; #define glVertexAttrib1dv glad_glVertexAttrib1dv typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC)(GLuint index, GLfloat x); GLAPI PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; #define glVertexAttrib1f glad_glVertexAttrib1f typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; #define glVertexAttrib1fv glad_glVertexAttrib1fv typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC)(GLuint index, GLshort x); GLAPI PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; #define glVertexAttrib1s glad_glVertexAttrib1s typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; #define glVertexAttrib1sv glad_glVertexAttrib1sv typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC)(GLuint index, GLdouble x, GLdouble y); GLAPI PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; #define glVertexAttrib2d glad_glVertexAttrib2d typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; #define glVertexAttrib2dv glad_glVertexAttrib2dv typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC)(GLuint index, GLfloat x, GLfloat y); GLAPI PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; #define glVertexAttrib2f glad_glVertexAttrib2f typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; #define glVertexAttrib2fv glad_glVertexAttrib2fv typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC)(GLuint index, GLshort x, GLshort y); GLAPI PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; #define glVertexAttrib2s glad_glVertexAttrib2s typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; #define glVertexAttrib2sv glad_glVertexAttrib2sv typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; #define glVertexAttrib3d glad_glVertexAttrib3d typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; #define glVertexAttrib3dv glad_glVertexAttrib3dv typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z); GLAPI PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; #define glVertexAttrib3f glad_glVertexAttrib3f typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; #define glVertexAttrib3fv glad_glVertexAttrib3fv typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC)(GLuint index, GLshort x, GLshort y, GLshort z); GLAPI PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; #define glVertexAttrib3s glad_glVertexAttrib3s typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; #define glVertexAttrib3sv glad_glVertexAttrib3sv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; #define glVertexAttrib4Nbv glad_glVertexAttrib4Nbv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; #define glVertexAttrib4Niv glad_glVertexAttrib4Niv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; #define glVertexAttrib4Nsv glad_glVertexAttrib4Nsv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); GLAPI PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; #define glVertexAttrib4Nub glad_glVertexAttrib4Nub typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; #define glVertexAttrib4Nubv glad_glVertexAttrib4Nubv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; #define glVertexAttrib4Nuiv glad_glVertexAttrib4Nuiv typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; #define glVertexAttrib4Nusv glad_glVertexAttrib4Nusv typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; #define glVertexAttrib4bv glad_glVertexAttrib4bv typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; #define glVertexAttrib4d glad_glVertexAttrib4d typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC)(GLuint index, const GLdouble *v); GLAPI PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; #define glVertexAttrib4dv glad_glVertexAttrib4dv typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); GLAPI PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; #define glVertexAttrib4f glad_glVertexAttrib4f typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC)(GLuint index, const GLfloat *v); GLAPI PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; #define glVertexAttrib4fv glad_glVertexAttrib4fv typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; #define glVertexAttrib4iv glad_glVertexAttrib4iv typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); GLAPI PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; #define glVertexAttrib4s glad_glVertexAttrib4s typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; #define glVertexAttrib4sv glad_glVertexAttrib4sv typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; #define glVertexAttrib4ubv glad_glVertexAttrib4ubv typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; #define glVertexAttrib4uiv glad_glVertexAttrib4uiv typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; #define glVertexAttrib4usv glad_glVertexAttrib4usv typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; #define glVertexAttribPointer glad_glVertexAttribPointer #endif #ifndef GL_VERSION_2_1 #define GL_VERSION_2_1 1 GLAPI int GLAD_GL_VERSION_2_1; typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; #define glUniformMatrix2x3fv glad_glUniformMatrix2x3fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; #define glUniformMatrix3x2fv glad_glUniformMatrix3x2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; #define glUniformMatrix2x4fv glad_glUniformMatrix2x4fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; #define glUniformMatrix4x2fv glad_glUniformMatrix4x2fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; #define glUniformMatrix3x4fv glad_glUniformMatrix3x4fv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); GLAPI PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; #define glUniformMatrix4x3fv glad_glUniformMatrix4x3fv #endif #ifndef GL_VERSION_3_0 #define GL_VERSION_3_0 1 GLAPI int GLAD_GL_VERSION_3_0; typedef void (APIENTRYP PFNGLCOLORMASKIPROC)(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); GLAPI PFNGLCOLORMASKIPROC glad_glColorMaski; #define glColorMaski glad_glColorMaski typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC)(GLenum target, GLuint index, GLboolean *data); GLAPI PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; #define glGetBooleani_v glad_glGetBooleani_v typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC)(GLenum target, GLuint index, GLint *data); GLAPI PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; #define glGetIntegeri_v glad_glGetIntegeri_v typedef void (APIENTRYP PFNGLENABLEIPROC)(GLenum target, GLuint index); GLAPI PFNGLENABLEIPROC glad_glEnablei; #define glEnablei glad_glEnablei typedef void (APIENTRYP PFNGLDISABLEIPROC)(GLenum target, GLuint index); GLAPI PFNGLDISABLEIPROC glad_glDisablei; #define glDisablei glad_glDisablei typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC)(GLenum target, GLuint index); GLAPI PFNGLISENABLEDIPROC glad_glIsEnabledi; #define glIsEnabledi glad_glIsEnabledi typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC)(GLenum primitiveMode); GLAPI PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; #define glBeginTransformFeedback glad_glBeginTransformFeedback typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; #define glEndTransformFeedback glad_glEndTransformFeedback typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC)(GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); GLAPI PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; #define glBindBufferRange glad_glBindBufferRange typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC)(GLenum target, GLuint index, GLuint buffer); GLAPI PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; #define glBindBufferBase glad_glBindBufferBase typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC)(GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); GLAPI PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; #define glTransformFeedbackVaryings glad_glTransformFeedbackVaryings typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)(GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); GLAPI PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; #define glGetTransformFeedbackVarying glad_glGetTransformFeedbackVarying typedef void (APIENTRYP PFNGLCLAMPCOLORPROC)(GLenum target, GLenum clamp); GLAPI PFNGLCLAMPCOLORPROC glad_glClampColor; #define glClampColor glad_glClampColor typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC)(GLuint id, GLenum mode); GLAPI PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; #define glBeginConditionalRender glad_glBeginConditionalRender typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC)(void); GLAPI PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; #define glEndConditionalRender glad_glEndConditionalRender typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC)(GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); GLAPI PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; #define glVertexAttribIPointer glad_glVertexAttribIPointer typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC)(GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; #define glGetVertexAttribIiv glad_glGetVertexAttribIiv typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC)(GLuint index, GLenum pname, GLuint *params); GLAPI PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; #define glGetVertexAttribIuiv glad_glGetVertexAttribIuiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC)(GLuint index, GLint x); GLAPI PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; #define glVertexAttribI1i glad_glVertexAttribI1i typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC)(GLuint index, GLint x, GLint y); GLAPI PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; #define glVertexAttribI2i glad_glVertexAttribI2i typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC)(GLuint index, GLint x, GLint y, GLint z); GLAPI PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; #define glVertexAttribI3i glad_glVertexAttribI3i typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC)(GLuint index, GLint x, GLint y, GLint z, GLint w); GLAPI PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; #define glVertexAttribI4i glad_glVertexAttribI4i typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC)(GLuint index, GLuint x); GLAPI PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; #define glVertexAttribI1ui glad_glVertexAttribI1ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC)(GLuint index, GLuint x, GLuint y); GLAPI PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; #define glVertexAttribI2ui glad_glVertexAttribI2ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z); GLAPI PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; #define glVertexAttribI3ui glad_glVertexAttribI3ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC)(GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); GLAPI PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; #define glVertexAttribI4ui glad_glVertexAttribI4ui typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; #define glVertexAttribI1iv glad_glVertexAttribI1iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; #define glVertexAttribI2iv glad_glVertexAttribI2iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; #define glVertexAttribI3iv glad_glVertexAttribI3iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC)(GLuint index, const GLint *v); GLAPI PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; #define glVertexAttribI4iv glad_glVertexAttribI4iv typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; #define glVertexAttribI1uiv glad_glVertexAttribI1uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; #define glVertexAttribI2uiv glad_glVertexAttribI2uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; #define glVertexAttribI3uiv glad_glVertexAttribI3uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC)(GLuint index, const GLuint *v); GLAPI PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; #define glVertexAttribI4uiv glad_glVertexAttribI4uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC)(GLuint index, const GLbyte *v); GLAPI PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; #define glVertexAttribI4bv glad_glVertexAttribI4bv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC)(GLuint index, const GLshort *v); GLAPI PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; #define glVertexAttribI4sv glad_glVertexAttribI4sv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC)(GLuint index, const GLubyte *v); GLAPI PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; #define glVertexAttribI4ubv glad_glVertexAttribI4ubv typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC)(GLuint index, const GLushort *v); GLAPI PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; #define glVertexAttribI4usv glad_glVertexAttribI4usv typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC)(GLuint program, GLint location, GLuint *params); GLAPI PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; #define glGetUniformuiv glad_glGetUniformuiv typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC)(GLuint program, GLuint color, const GLchar *name); GLAPI PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; #define glBindFragDataLocation glad_glBindFragDataLocation typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; #define glGetFragDataLocation glad_glGetFragDataLocation typedef void (APIENTRYP PFNGLUNIFORM1UIPROC)(GLint location, GLuint v0); GLAPI PFNGLUNIFORM1UIPROC glad_glUniform1ui; #define glUniform1ui glad_glUniform1ui typedef void (APIENTRYP PFNGLUNIFORM2UIPROC)(GLint location, GLuint v0, GLuint v1); GLAPI PFNGLUNIFORM2UIPROC glad_glUniform2ui; #define glUniform2ui glad_glUniform2ui typedef void (APIENTRYP PFNGLUNIFORM3UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2); GLAPI PFNGLUNIFORM3UIPROC glad_glUniform3ui; #define glUniform3ui glad_glUniform3ui typedef void (APIENTRYP PFNGLUNIFORM4UIPROC)(GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); GLAPI PFNGLUNIFORM4UIPROC glad_glUniform4ui; #define glUniform4ui glad_glUniform4ui typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; #define glUniform1uiv glad_glUniform1uiv typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; #define glUniform2uiv glad_glUniform2uiv typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; #define glUniform3uiv glad_glUniform3uiv typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC)(GLint location, GLsizei count, const GLuint *value); GLAPI PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; #define glUniform4uiv glad_glUniform4uiv typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, const GLint *params); GLAPI PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; #define glTexParameterIiv glad_glTexParameterIiv typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, const GLuint *params); GLAPI PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; #define glTexParameterIuiv glad_glTexParameterIuiv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; #define glGetTexParameterIiv glad_glGetTexParameterIiv typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC)(GLenum target, GLenum pname, GLuint *params); GLAPI PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; #define glGetTexParameterIuiv glad_glGetTexParameterIuiv typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC)(GLenum buffer, GLint drawbuffer, const GLint *value); GLAPI PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; #define glClearBufferiv glad_glClearBufferiv typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC)(GLenum buffer, GLint drawbuffer, const GLuint *value); GLAPI PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; #define glClearBufferuiv glad_glClearBufferuiv typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC)(GLenum buffer, GLint drawbuffer, const GLfloat *value); GLAPI PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; #define glClearBufferfv glad_glClearBufferfv typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC)(GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); GLAPI PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; #define glClearBufferfi glad_glClearBufferfi typedef const GLubyte * (APIENTRYP PFNGLGETSTRINGIPROC)(GLenum name, GLuint index); GLAPI PFNGLGETSTRINGIPROC glad_glGetStringi; #define glGetStringi glad_glGetStringi typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC)(GLuint renderbuffer); GLAPI PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; #define glIsRenderbuffer glad_glIsRenderbuffer typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC)(GLenum target, GLuint renderbuffer); GLAPI PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; #define glBindRenderbuffer glad_glBindRenderbuffer typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC)(GLsizei n, const GLuint *renderbuffers); GLAPI PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; #define glDeleteRenderbuffers glad_glDeleteRenderbuffers typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC)(GLsizei n, GLuint *renderbuffers); GLAPI PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; #define glGenRenderbuffers glad_glGenRenderbuffers typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC)(GLenum target, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; #define glRenderbufferStorage glad_glRenderbufferStorage typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC)(GLenum target, GLenum pname, GLint *params); GLAPI PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; #define glGetRenderbufferParameteriv glad_glGetRenderbufferParameteriv typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC)(GLuint framebuffer); GLAPI PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; #define glIsFramebuffer glad_glIsFramebuffer typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); GLAPI PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; #define glBindFramebuffer glad_glBindFramebuffer typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC)(GLsizei n, const GLuint *framebuffers); GLAPI PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; #define glDeleteFramebuffers glad_glDeleteFramebuffers typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); GLAPI PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; #define glGenFramebuffers glad_glGenFramebuffers typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC)(GLenum target); GLAPI PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; #define glCheckFramebufferStatus glad_glCheckFramebufferStatus typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; #define glFramebufferTexture1D glad_glFramebufferTexture1D typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; #define glFramebufferTexture2D glad_glFramebufferTexture2D typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); GLAPI PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; #define glFramebufferTexture3D glad_glFramebufferTexture3D typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC)(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); GLAPI PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; #define glFramebufferRenderbuffer glad_glFramebufferRenderbuffer typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)(GLenum target, GLenum attachment, GLenum pname, GLint *params); GLAPI PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; #define glGetFramebufferAttachmentParameteriv glad_glGetFramebufferAttachmentParameteriv typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC)(GLenum target); GLAPI PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; #define glGenerateMipmap glad_glGenerateMipmap typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); GLAPI PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; #define glBlitFramebuffer glad_glBlitFramebuffer typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); GLAPI PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; #define glRenderbufferStorageMultisample glad_glRenderbufferStorageMultisample typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); GLAPI PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; #define glFramebufferTextureLayer glad_glFramebufferTextureLayer typedef void * (APIENTRYP PFNGLMAPBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); GLAPI PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; #define glMapBufferRange glad_glMapBufferRange typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC)(GLenum target, GLintptr offset, GLsizeiptr length); GLAPI PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; #define glFlushMappedBufferRange glad_glFlushMappedBufferRange typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC)(GLuint array); GLAPI PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; #define glBindVertexArray glad_glBindVertexArray typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC)(GLsizei n, const GLuint *arrays); GLAPI PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; #define glDeleteVertexArrays glad_glDeleteVertexArrays typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC)(GLsizei n, GLuint *arrays); GLAPI PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; #define glGenVertexArrays glad_glGenVertexArrays typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC)(GLuint array); GLAPI PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; #define glIsVertexArray glad_glIsVertexArray #endif #ifndef GL_VERSION_3_1 #define GL_VERSION_3_1 1 GLAPI int GLAD_GL_VERSION_3_1; typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC)(GLenum mode, GLint first, GLsizei count, GLsizei instancecount); GLAPI PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; #define glDrawArraysInstanced glad_glDrawArraysInstanced typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); GLAPI PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; #define glDrawElementsInstanced glad_glDrawElementsInstanced typedef void (APIENTRYP PFNGLTEXBUFFERPROC)(GLenum target, GLenum internalformat, GLuint buffer); GLAPI PFNGLTEXBUFFERPROC glad_glTexBuffer; #define glTexBuffer glad_glTexBuffer typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC)(GLuint index); GLAPI PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; #define glPrimitiveRestartIndex glad_glPrimitiveRestartIndex typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC)(GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); GLAPI PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; #define glCopyBufferSubData glad_glCopyBufferSubData typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC)(GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); GLAPI PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; #define glGetUniformIndices glad_glGetUniformIndices typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC)(GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; #define glGetActiveUniformsiv glad_glGetActiveUniformsiv typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC)(GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); GLAPI PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; #define glGetActiveUniformName glad_glGetActiveUniformName typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC)(GLuint program, const GLchar *uniformBlockName); GLAPI PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; #define glGetUniformBlockIndex glad_glGetUniformBlockIndex typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC)(GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); GLAPI PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; #define glGetActiveUniformBlockiv glad_glGetActiveUniformBlockiv typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)(GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); GLAPI PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; #define glGetActiveUniformBlockName glad_glGetActiveUniformBlockName typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC)(GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); GLAPI PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; #define glUniformBlockBinding glad_glUniformBlockBinding #endif #ifndef GL_VERSION_3_2 #define GL_VERSION_3_2 1 GLAPI int GLAD_GL_VERSION_3_2; typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; #define glDrawElementsBaseVertex glad_glDrawElementsBaseVertex typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); GLAPI PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; #define glDrawRangeElementsBaseVertex glad_glDrawRangeElementsBaseVertex typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)(GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); GLAPI PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; #define glDrawElementsInstancedBaseVertex glad_glDrawElementsInstancedBaseVertex typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)(GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); GLAPI PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; #define glMultiDrawElementsBaseVertex glad_glMultiDrawElementsBaseVertex typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC)(GLenum mode); GLAPI PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; #define glProvokingVertex glad_glProvokingVertex typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC)(GLenum condition, GLbitfield flags); GLAPI PFNGLFENCESYNCPROC glad_glFenceSync; #define glFenceSync glad_glFenceSync typedef GLboolean (APIENTRYP PFNGLISSYNCPROC)(GLsync sync); GLAPI PFNGLISSYNCPROC glad_glIsSync; #define glIsSync glad_glIsSync typedef void (APIENTRYP PFNGLDELETESYNCPROC)(GLsync sync); GLAPI PFNGLDELETESYNCPROC glad_glDeleteSync; #define glDeleteSync glad_glDeleteSync typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; #define glClientWaitSync glad_glClientWaitSync typedef void (APIENTRYP PFNGLWAITSYNCPROC)(GLsync sync, GLbitfield flags, GLuint64 timeout); GLAPI PFNGLWAITSYNCPROC glad_glWaitSync; #define glWaitSync glad_glWaitSync typedef void (APIENTRYP PFNGLGETINTEGER64VPROC)(GLenum pname, GLint64 *data); GLAPI PFNGLGETINTEGER64VPROC glad_glGetInteger64v; #define glGetInteger64v glad_glGetInteger64v typedef void (APIENTRYP PFNGLGETSYNCIVPROC)(GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); GLAPI PFNGLGETSYNCIVPROC glad_glGetSynciv; #define glGetSynciv glad_glGetSynciv typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC)(GLenum target, GLuint index, GLint64 *data); GLAPI PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; #define glGetInteger64i_v glad_glGetInteger64i_v typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC)(GLenum target, GLenum pname, GLint64 *params); GLAPI PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; #define glGetBufferParameteri64v glad_glGetBufferParameteri64v typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC)(GLenum target, GLenum attachment, GLuint texture, GLint level); GLAPI PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; #define glFramebufferTexture glad_glFramebufferTexture typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; #define glTexImage2DMultisample glad_glTexImage2DMultisample typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC)(GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); GLAPI PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; #define glTexImage3DMultisample glad_glTexImage3DMultisample typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC)(GLenum pname, GLuint index, GLfloat *val); GLAPI PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; #define glGetMultisamplefv glad_glGetMultisamplefv typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC)(GLuint maskNumber, GLbitfield mask); GLAPI PFNGLSAMPLEMASKIPROC glad_glSampleMaski; #define glSampleMaski glad_glSampleMaski #endif #ifndef GL_VERSION_3_3 #define GL_VERSION_3_3 1 GLAPI int GLAD_GL_VERSION_3_3; typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)(GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); GLAPI PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; #define glBindFragDataLocationIndexed glad_glBindFragDataLocationIndexed typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC)(GLuint program, const GLchar *name); GLAPI PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; #define glGetFragDataIndex glad_glGetFragDataIndex typedef void (APIENTRYP PFNGLGENSAMPLERSPROC)(GLsizei count, GLuint *samplers); GLAPI PFNGLGENSAMPLERSPROC glad_glGenSamplers; #define glGenSamplers glad_glGenSamplers typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC)(GLsizei count, const GLuint *samplers); GLAPI PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; #define glDeleteSamplers glad_glDeleteSamplers typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC)(GLuint sampler); GLAPI PFNGLISSAMPLERPROC glad_glIsSampler; #define glIsSampler glad_glIsSampler typedef void (APIENTRYP PFNGLBINDSAMPLERPROC)(GLuint unit, GLuint sampler); GLAPI PFNGLBINDSAMPLERPROC glad_glBindSampler; #define glBindSampler glad_glBindSampler typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC)(GLuint sampler, GLenum pname, GLint param); GLAPI PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; #define glSamplerParameteri glad_glSamplerParameteri typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, const GLint *param); GLAPI PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; #define glSamplerParameteriv glad_glSamplerParameteriv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC)(GLuint sampler, GLenum pname, GLfloat param); GLAPI PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; #define glSamplerParameterf glad_glSamplerParameterf typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, const GLfloat *param); GLAPI PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; #define glSamplerParameterfv glad_glSamplerParameterfv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, const GLint *param); GLAPI PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; #define glSamplerParameterIiv glad_glSamplerParameterIiv typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, const GLuint *param); GLAPI PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; #define glSamplerParameterIuiv glad_glSamplerParameterIuiv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC)(GLuint sampler, GLenum pname, GLint *params); GLAPI PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; #define glGetSamplerParameteriv glad_glGetSamplerParameteriv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC)(GLuint sampler, GLenum pname, GLint *params); GLAPI PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; #define glGetSamplerParameterIiv glad_glGetSamplerParameterIiv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC)(GLuint sampler, GLenum pname, GLfloat *params); GLAPI PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; #define glGetSamplerParameterfv glad_glGetSamplerParameterfv typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC)(GLuint sampler, GLenum pname, GLuint *params); GLAPI PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; #define glGetSamplerParameterIuiv glad_glGetSamplerParameterIuiv typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC)(GLuint id, GLenum target); GLAPI PFNGLQUERYCOUNTERPROC glad_glQueryCounter; #define glQueryCounter glad_glQueryCounter typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC)(GLuint id, GLenum pname, GLint64 *params); GLAPI PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; #define glGetQueryObjecti64v glad_glGetQueryObjecti64v typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC)(GLuint id, GLenum pname, GLuint64 *params); GLAPI PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; #define glGetQueryObjectui64v glad_glGetQueryObjectui64v typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC)(GLuint index, GLuint divisor); GLAPI PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; #define glVertexAttribDivisor glad_glVertexAttribDivisor typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; #define glVertexAttribP1ui glad_glVertexAttribP1ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; #define glVertexAttribP1uiv glad_glVertexAttribP1uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; #define glVertexAttribP2ui glad_glVertexAttribP2ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; #define glVertexAttribP2uiv glad_glVertexAttribP2uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; #define glVertexAttribP3ui glad_glVertexAttribP3ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; #define glVertexAttribP3uiv glad_glVertexAttribP3uiv typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC)(GLuint index, GLenum type, GLboolean normalized, GLuint value); GLAPI PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; #define glVertexAttribP4ui glad_glVertexAttribP4ui typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC)(GLuint index, GLenum type, GLboolean normalized, const GLuint *value); GLAPI PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; #define glVertexAttribP4uiv glad_glVertexAttribP4uiv typedef void (APIENTRYP PFNGLVERTEXP2UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP2UIPROC glad_glVertexP2ui; #define glVertexP2ui glad_glVertexP2ui typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; #define glVertexP2uiv glad_glVertexP2uiv typedef void (APIENTRYP PFNGLVERTEXP3UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP3UIPROC glad_glVertexP3ui; #define glVertexP3ui glad_glVertexP3ui typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; #define glVertexP3uiv glad_glVertexP3uiv typedef void (APIENTRYP PFNGLVERTEXP4UIPROC)(GLenum type, GLuint value); GLAPI PFNGLVERTEXP4UIPROC glad_glVertexP4ui; #define glVertexP4ui glad_glVertexP4ui typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC)(GLenum type, const GLuint *value); GLAPI PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; #define glVertexP4uiv glad_glVertexP4uiv typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; #define glTexCoordP1ui glad_glTexCoordP1ui typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; #define glTexCoordP1uiv glad_glTexCoordP1uiv typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; #define glTexCoordP2ui glad_glTexCoordP2ui typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; #define glTexCoordP2uiv glad_glTexCoordP2uiv typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; #define glTexCoordP3ui glad_glTexCoordP3ui typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; #define glTexCoordP3uiv glad_glTexCoordP3uiv typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; #define glTexCoordP4ui glad_glTexCoordP4ui typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; #define glTexCoordP4uiv glad_glTexCoordP4uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; #define glMultiTexCoordP1ui glad_glMultiTexCoordP1ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; #define glMultiTexCoordP1uiv glad_glMultiTexCoordP1uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; #define glMultiTexCoordP2ui glad_glMultiTexCoordP2ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; #define glMultiTexCoordP2uiv glad_glMultiTexCoordP2uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; #define glMultiTexCoordP3ui glad_glMultiTexCoordP3ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; #define glMultiTexCoordP3uiv glad_glMultiTexCoordP3uiv typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC)(GLenum texture, GLenum type, GLuint coords); GLAPI PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; #define glMultiTexCoordP4ui glad_glMultiTexCoordP4ui typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC)(GLenum texture, GLenum type, const GLuint *coords); GLAPI PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; #define glMultiTexCoordP4uiv glad_glMultiTexCoordP4uiv typedef void (APIENTRYP PFNGLNORMALP3UIPROC)(GLenum type, GLuint coords); GLAPI PFNGLNORMALP3UIPROC glad_glNormalP3ui; #define glNormalP3ui glad_glNormalP3ui typedef void (APIENTRYP PFNGLNORMALP3UIVPROC)(GLenum type, const GLuint *coords); GLAPI PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; #define glNormalP3uiv glad_glNormalP3uiv typedef void (APIENTRYP PFNGLCOLORP3UIPROC)(GLenum type, GLuint color); GLAPI PFNGLCOLORP3UIPROC glad_glColorP3ui; #define glColorP3ui glad_glColorP3ui typedef void (APIENTRYP PFNGLCOLORP3UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLCOLORP3UIVPROC glad_glColorP3uiv; #define glColorP3uiv glad_glColorP3uiv typedef void (APIENTRYP PFNGLCOLORP4UIPROC)(GLenum type, GLuint color); GLAPI PFNGLCOLORP4UIPROC glad_glColorP4ui; #define glColorP4ui glad_glColorP4ui typedef void (APIENTRYP PFNGLCOLORP4UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLCOLORP4UIVPROC glad_glColorP4uiv; #define glColorP4uiv glad_glColorP4uiv typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC)(GLenum type, GLuint color); GLAPI PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; #define glSecondaryColorP3ui glad_glSecondaryColorP3ui typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC)(GLenum type, const GLuint *color); GLAPI PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; #define glSecondaryColorP3uiv glad_glSecondaryColorP3uiv #endif #ifndef GL_VERSION_4_0 #define GL_VERSION_4_0 1 GLAPI int GLAD_GL_VERSION_4_0; typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC)(GLfloat value); GLAPI PFNGLMINSAMPLESHADINGPROC glad_glMinSampleShading; #define glMinSampleShading glad_glMinSampleShading typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC)(GLuint buf, GLenum mode); GLAPI PFNGLBLENDEQUATIONIPROC glad_glBlendEquationi; #define glBlendEquationi glad_glBlendEquationi typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC)(GLuint buf, GLenum modeRGB, GLenum modeAlpha); GLAPI PFNGLBLENDEQUATIONSEPARATEIPROC glad_glBlendEquationSeparatei; #define glBlendEquationSeparatei glad_glBlendEquationSeparatei typedef void (APIENTRYP PFNGLBLENDFUNCIPROC)(GLuint buf, GLenum src, GLenum dst); GLAPI PFNGLBLENDFUNCIPROC glad_glBlendFunci; #define glBlendFunci glad_glBlendFunci typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC)(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); GLAPI PFNGLBLENDFUNCSEPARATEIPROC glad_glBlendFuncSeparatei; #define glBlendFuncSeparatei glad_glBlendFuncSeparatei typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC)(GLenum mode, const void *indirect); GLAPI PFNGLDRAWARRAYSINDIRECTPROC glad_glDrawArraysIndirect; #define glDrawArraysIndirect glad_glDrawArraysIndirect typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC)(GLenum mode, GLenum type, const void *indirect); GLAPI PFNGLDRAWELEMENTSINDIRECTPROC glad_glDrawElementsIndirect; #define glDrawElementsIndirect glad_glDrawElementsIndirect typedef void (APIENTRYP PFNGLUNIFORM1DPROC)(GLint location, GLdouble x); GLAPI PFNGLUNIFORM1DPROC glad_glUniform1d; #define glUniform1d glad_glUniform1d typedef void (APIENTRYP PFNGLUNIFORM2DPROC)(GLint location, GLdouble x, GLdouble y); GLAPI PFNGLUNIFORM2DPROC glad_glUniform2d; #define glUniform2d glad_glUniform2d typedef void (APIENTRYP PFNGLUNIFORM3DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z); GLAPI PFNGLUNIFORM3DPROC glad_glUniform3d; #define glUniform3d glad_glUniform3d typedef void (APIENTRYP PFNGLUNIFORM4DPROC)(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); GLAPI PFNGLUNIFORM4DPROC glad_glUniform4d; #define glUniform4d glad_glUniform4d typedef void (APIENTRYP PFNGLUNIFORM1DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM1DVPROC glad_glUniform1dv; #define glUniform1dv glad_glUniform1dv typedef void (APIENTRYP PFNGLUNIFORM2DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM2DVPROC glad_glUniform2dv; #define glUniform2dv glad_glUniform2dv typedef void (APIENTRYP PFNGLUNIFORM3DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM3DVPROC glad_glUniform3dv; #define glUniform3dv glad_glUniform3dv typedef void (APIENTRYP PFNGLUNIFORM4DVPROC)(GLint location, GLsizei count, const GLdouble *value); GLAPI PFNGLUNIFORM4DVPROC glad_glUniform4dv; #define glUniform4dv glad_glUniform4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2DVPROC glad_glUniformMatrix2dv; #define glUniformMatrix2dv glad_glUniformMatrix2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3DVPROC glad_glUniformMatrix3dv; #define glUniformMatrix3dv glad_glUniformMatrix3dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4DVPROC glad_glUniformMatrix4dv; #define glUniformMatrix4dv glad_glUniformMatrix4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2X3DVPROC glad_glUniformMatrix2x3dv; #define glUniformMatrix2x3dv glad_glUniformMatrix2x3dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX2X4DVPROC glad_glUniformMatrix2x4dv; #define glUniformMatrix2x4dv glad_glUniformMatrix2x4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3X2DVPROC glad_glUniformMatrix3x2dv; #define glUniformMatrix3x2dv glad_glUniformMatrix3x2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX3X4DVPROC glad_glUniformMatrix3x4dv; #define glUniformMatrix3x4dv glad_glUniformMatrix3x4dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4X2DVPROC glad_glUniformMatrix4x2dv; #define glUniformMatrix4x2dv glad_glUniformMatrix4x2dv typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC)(GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); GLAPI PFNGLUNIFORMMATRIX4X3DVPROC glad_glUniformMatrix4x3dv; #define glUniformMatrix4x3dv glad_glUniformMatrix4x3dv typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC)(GLuint program, GLint location, GLdouble *params); GLAPI PFNGLGETUNIFORMDVPROC glad_glGetUniformdv; #define glGetUniformdv glad_glGetUniformdv typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC)(GLuint program, GLenum shadertype, const GLchar *name); GLAPI PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC glad_glGetSubroutineUniformLocation; #define glGetSubroutineUniformLocation glad_glGetSubroutineUniformLocation typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC)(GLuint program, GLenum shadertype, const GLchar *name); GLAPI PFNGLGETSUBROUTINEINDEXPROC glad_glGetSubroutineIndex; #define glGetSubroutineIndex glad_glGetSubroutineIndex typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC)(GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC glad_glGetActiveSubroutineUniformiv; #define glGetActiveSubroutineUniformiv glad_glGetActiveSubroutineUniformiv typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); GLAPI PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC glad_glGetActiveSubroutineUniformName; #define glGetActiveSubroutineUniformName glad_glGetActiveSubroutineUniformName typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC)(GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); GLAPI PFNGLGETACTIVESUBROUTINENAMEPROC glad_glGetActiveSubroutineName; #define glGetActiveSubroutineName glad_glGetActiveSubroutineName typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC)(GLenum shadertype, GLsizei count, const GLuint *indices); GLAPI PFNGLUNIFORMSUBROUTINESUIVPROC glad_glUniformSubroutinesuiv; #define glUniformSubroutinesuiv glad_glUniformSubroutinesuiv typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC)(GLenum shadertype, GLint location, GLuint *params); GLAPI PFNGLGETUNIFORMSUBROUTINEUIVPROC glad_glGetUniformSubroutineuiv; #define glGetUniformSubroutineuiv glad_glGetUniformSubroutineuiv typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC)(GLuint program, GLenum shadertype, GLenum pname, GLint *values); GLAPI PFNGLGETPROGRAMSTAGEIVPROC glad_glGetProgramStageiv; #define glGetProgramStageiv glad_glGetProgramStageiv typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC)(GLenum pname, GLint value); GLAPI PFNGLPATCHPARAMETERIPROC glad_glPatchParameteri; #define glPatchParameteri glad_glPatchParameteri typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC)(GLenum pname, const GLfloat *values); GLAPI PFNGLPATCHPARAMETERFVPROC glad_glPatchParameterfv; #define glPatchParameterfv glad_glPatchParameterfv typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC)(GLenum target, GLuint id); GLAPI PFNGLBINDTRANSFORMFEEDBACKPROC glad_glBindTransformFeedback; #define glBindTransformFeedback glad_glBindTransformFeedback typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC)(GLsizei n, const GLuint *ids); GLAPI PFNGLDELETETRANSFORMFEEDBACKSPROC glad_glDeleteTransformFeedbacks; #define glDeleteTransformFeedbacks glad_glDeleteTransformFeedbacks typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC)(GLsizei n, GLuint *ids); GLAPI PFNGLGENTRANSFORMFEEDBACKSPROC glad_glGenTransformFeedbacks; #define glGenTransformFeedbacks glad_glGenTransformFeedbacks typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC)(GLuint id); GLAPI PFNGLISTRANSFORMFEEDBACKPROC glad_glIsTransformFeedback; #define glIsTransformFeedback glad_glIsTransformFeedback typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLPAUSETRANSFORMFEEDBACKPROC glad_glPauseTransformFeedback; #define glPauseTransformFeedback glad_glPauseTransformFeedback typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC)(void); GLAPI PFNGLRESUMETRANSFORMFEEDBACKPROC glad_glResumeTransformFeedback; #define glResumeTransformFeedback glad_glResumeTransformFeedback typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC)(GLenum mode, GLuint id); GLAPI PFNGLDRAWTRANSFORMFEEDBACKPROC glad_glDrawTransformFeedback; #define glDrawTransformFeedback glad_glDrawTransformFeedback typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC)(GLenum mode, GLuint id, GLuint stream); GLAPI PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC glad_glDrawTransformFeedbackStream; #define glDrawTransformFeedbackStream glad_glDrawTransformFeedbackStream typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC)(GLenum target, GLuint index, GLuint id); GLAPI PFNGLBEGINQUERYINDEXEDPROC glad_glBeginQueryIndexed; #define glBeginQueryIndexed glad_glBeginQueryIndexed typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC)(GLenum target, GLuint index); GLAPI PFNGLENDQUERYINDEXEDPROC glad_glEndQueryIndexed; #define glEndQueryIndexed glad_glEndQueryIndexed typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC)(GLenum target, GLuint index, GLenum pname, GLint *params); GLAPI PFNGLGETQUERYINDEXEDIVPROC glad_glGetQueryIndexediv; #define glGetQueryIndexediv glad_glGetQueryIndexediv #endif #ifdef __cplusplus } #endif #endif
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/glad/khrplatform.h
C/C++ Header
#ifndef __khrplatform_h_ #define __khrplatform_h_ /* ** Copyright (c) 2008-2018 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and/or associated documentation files (the ** "Materials"), to deal in the Materials without restriction, including ** without limitation the rights to use, copy, modify, merge, publish, ** distribute, sublicense, and/or sell copies of the Materials, and to ** permit persons to whom the Materials are furnished to do so, subject to ** the following conditions: ** ** The above copyright notice and this permission notice shall be included ** in all copies or substantial portions of the Materials. ** ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE ** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. */ /* Khronos platform-specific types and definitions. * * The master copy of khrplatform.h is maintained in the Khronos EGL * Registry repository at https://github.com/KhronosGroup/EGL-Registry * The last semantic modification to khrplatform.h was at commit ID: * 67a3e0864c2d75ea5287b9f3d2eb74a745936692 * * Adopters may modify this file to suit their platform. Adopters are * encouraged to submit platform specific modifications to the Khronos * group so that they can be included in future versions of this file. * Please submit changes by filing pull requests or issues on * the EGL Registry repository linked above. * * * See the Implementer's Guidelines for information about where this file * should be located on your system and for more details of its use: * http://www.khronos.org/registry/implementers_guide.pdf * * This file should be included as * #include <KHR/khrplatform.h> * by Khronos client API header files that use its types and defines. * * The types in khrplatform.h should only be used to define API-specific types. * * Types defined in khrplatform.h: * khronos_int8_t signed 8 bit * khronos_uint8_t unsigned 8 bit * khronos_int16_t signed 16 bit * khronos_uint16_t unsigned 16 bit * khronos_int32_t signed 32 bit * khronos_uint32_t unsigned 32 bit * khronos_int64_t signed 64 bit * khronos_uint64_t unsigned 64 bit * khronos_intptr_t signed same number of bits as a pointer * khronos_uintptr_t unsigned same number of bits as a pointer * khronos_ssize_t signed size * khronos_usize_t unsigned size * khronos_float_t signed 32 bit floating point * khronos_time_ns_t unsigned 64 bit time in nanoseconds * khronos_utime_nanoseconds_t unsigned time interval or absolute time in * nanoseconds * khronos_stime_nanoseconds_t signed time interval in nanoseconds * khronos_boolean_enum_t enumerated boolean type. This should * only be used as a base type when a client API's boolean type is * an enum. Client APIs which use an integer or other type for * booleans cannot use this as the base type for their boolean. * * Tokens defined in khrplatform.h: * * KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values. * * KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0. * KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0. * * Calling convention macros defined in this file: * KHRONOS_APICALL * KHRONOS_APIENTRY * KHRONOS_APIATTRIBUTES * * These may be used in function prototypes as: * * KHRONOS_APICALL void KHRONOS_APIENTRY funcname( * int arg1, * int arg2) KHRONOS_APIATTRIBUTES; */ /*------------------------------------------------------------------------- * Definition of KHRONOS_APICALL *------------------------------------------------------------------------- * This precedes the return type of the function in the function prototype. */ #if defined(_WIN32) && !defined(__SCITECH_SNAP__) # define KHRONOS_APICALL __declspec(dllimport) #elif defined (__SYMBIAN32__) # define KHRONOS_APICALL IMPORT_C #elif defined(__ANDROID__) # define KHRONOS_APICALL __attribute__((visibility("default"))) #else # define KHRONOS_APICALL #endif /*------------------------------------------------------------------------- * Definition of KHRONOS_APIENTRY *------------------------------------------------------------------------- * This follows the return type of the function and precedes the function * name in the function prototype. */ #if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__) /* Win32 but not WinCE */ # define KHRONOS_APIENTRY __stdcall #else # define KHRONOS_APIENTRY #endif /*------------------------------------------------------------------------- * Definition of KHRONOS_APIATTRIBUTES *------------------------------------------------------------------------- * This follows the closing parenthesis of the function prototype arguments. */ #if defined (__ARMCC_2__) #define KHRONOS_APIATTRIBUTES __softfp #else #define KHRONOS_APIATTRIBUTES #endif /*------------------------------------------------------------------------- * basic type definitions *-----------------------------------------------------------------------*/ #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__) /* * Using <stdint.h> */ #include <stdint.h> typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif defined(__VMS ) || defined(__sgi) /* * Using <inttypes.h> */ #include <inttypes.h> typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif defined(_WIN32) && !defined(__SCITECH_SNAP__) /* * Win32 */ typedef __int32 khronos_int32_t; typedef unsigned __int32 khronos_uint32_t; typedef __int64 khronos_int64_t; typedef unsigned __int64 khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif defined(__sun__) || defined(__digital__) /* * Sun or Digital */ typedef int khronos_int32_t; typedef unsigned int khronos_uint32_t; #if defined(__arch64__) || defined(_LP64) typedef long int khronos_int64_t; typedef unsigned long int khronos_uint64_t; #else typedef long long int khronos_int64_t; typedef unsigned long long int khronos_uint64_t; #endif /* __arch64__ */ #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #elif 0 /* * Hypothetical platform with no float or int64 support */ typedef int khronos_int32_t; typedef unsigned int khronos_uint32_t; #define KHRONOS_SUPPORT_INT64 0 #define KHRONOS_SUPPORT_FLOAT 0 #else /* * Generic fallback */ #include <stdint.h> typedef int32_t khronos_int32_t; typedef uint32_t khronos_uint32_t; typedef int64_t khronos_int64_t; typedef uint64_t khronos_uint64_t; #define KHRONOS_SUPPORT_INT64 1 #define KHRONOS_SUPPORT_FLOAT 1 #endif /* * Types that are (so far) the same on all platforms */ typedef signed char khronos_int8_t; typedef unsigned char khronos_uint8_t; typedef signed short int khronos_int16_t; typedef unsigned short int khronos_uint16_t; /* * Types that differ between LLP64 and LP64 architectures - in LLP64, * pointers are 64 bits, but 'long' is still 32 bits. Win64 appears * to be the only LLP64 architecture in current use. */ #ifdef _WIN64 typedef signed long long int khronos_intptr_t; typedef unsigned long long int khronos_uintptr_t; typedef signed long long int khronos_ssize_t; typedef unsigned long long int khronos_usize_t; #else typedef signed long int khronos_intptr_t; typedef unsigned long int khronos_uintptr_t; typedef signed long int khronos_ssize_t; typedef unsigned long int khronos_usize_t; #endif #if KHRONOS_SUPPORT_FLOAT /* * Float type */ typedef float khronos_float_t; #endif #if KHRONOS_SUPPORT_INT64 /* Time types * * These types can be used to represent a time interval in nanoseconds or * an absolute Unadjusted System Time. Unadjusted System Time is the number * of nanoseconds since some arbitrary system event (e.g. since the last * time the system booted). The Unadjusted System Time is an unsigned * 64 bit value that wraps back to 0 every 584 years. Time intervals * may be either signed or unsigned. */ typedef khronos_uint64_t khronos_utime_nanoseconds_t; typedef khronos_int64_t khronos_stime_nanoseconds_t; #endif /* * Dummy value used to pad enum types to 32 bits. */ #ifndef KHRONOS_MAX_ENUM #define KHRONOS_MAX_ENUM 0x7FFFFFFF #endif /* * Enumerated boolean type * * Values other than zero should be considered to be true. Therefore * comparisons should not be made against KHRONOS_TRUE. */ typedef enum { KHRONOS_FALSE = 0, KHRONOS_TRUE = 1, KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM } khronos_boolean_enum_t; #endif /* __khrplatform_h_ */
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
src/main.cpp
C++
#ifdef _WIN32 #include "glad/glad.h" #endif #include <GLFW/glfw3.h> #include "World.h" #include "Configuration.h" #include "base/WorkQueue.h" #include "microprofile/microprofile.h" #include "microprofile/microprofileui.h" #include "microprofile/microprofiledraw.h" struct Vertex { Vector2f position; unsigned char r, g, b, a; }; void RenderBox(std::vector<Vertex>& vertices, Coords2f coords, Vector2f size, int r, int g, int b, int a) { Vector2f axisX = coords.xVector * size.x; Vector2f axisY = coords.yVector * size.y; Vertex v; v.r = r; v.g = g; v.b = b; v.a = a; v.position = coords.pos - axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX - axisY; vertices.push_back(v); v.position = coords.pos + axisX + axisY; vertices.push_back(v); v.position = coords.pos - axisX + axisY; vertices.push_back(v); } float random(float min, float max) { return min + (max - min) * (float(rand()) / float(RAND_MAX)); } const struct { Configuration::SolveMode mode; const char* name; } kSolveModes[] = { {Configuration::Solve_Scalar, "Scalar"}, #ifdef __SSE2__ {Configuration::Solve_SSE2, "SSE2"}, #endif #ifdef __AVX2__ {Configuration::Solve_AVX2, "AVX2"}, #endif }; const struct { Configuration::IslandMode mode; const char* name; } kIslandModes[] = { {Configuration::Island_Single, "Single"}, {Configuration::Island_Multiple, "Multiple"}, {Configuration::Island_SingleSloppy, "Single Sloppy"}, {Configuration::Island_MultipleSloppy, "Multiple Sloppy"}, }; const char* resetWorld(World& world, int scene) { MICROPROFILE_SCOPEI("Init", "resetWorld", -1); world.bodies.clear(); world.collider.manifolds.clear(); world.collider.manifoldMap.clear(); world.solver.contactJoints.clear(); RigidBody* groundBody = world.AddBody(Coords2f(Vector2f(0, 0), 0.0f), Vector2f(10000.f, 10.0f)); groundBody->invInertia = 0.0f; groundBody->invMass = 0.0f; world.AddBody(Coords2f(Vector2f(-1000, 1500), 0.0f), Vector2f(30.0f, 30.0f)); switch (scene % 8) { case 0: { for (int bodyIndex = 0; bodyIndex < 20000; bodyIndex++) { Vector2f pos = Vector2f(random(-500.0f, 500.0f), random(50.f, 1000.0f)); Vector2f size(4.f, 4.f); world.AddBody(Coords2f(pos, 0.f), size); } return "Falling"; } case 1: { for (int left = -100; left <= 100; left++) { for (int bodyIndex = 0; bodyIndex < 100; bodyIndex++) { Vector2f pos = Vector2f(left * 20, 10 + bodyIndex * 10); Vector2f size(10, 5); world.AddBody(Coords2f(pos, 0.f), size); } } return "Wall"; } case 2: { for (int step = 0; step < 100; ++step) { Vector2f pos = Vector2f(0, 1005 - step * 10); Vector2f size(10 + step * 5, 5); world.AddBody(Coords2f(pos, 0.f), size); } return "Pyramid"; } case 3: { for (int step = 0; step < 100; ++step) { Vector2f pos = Vector2f(0, 15 + step * 10); Vector2f size(10 + step * 5, 5); world.AddBody(Coords2f(pos, 0.f), size); } return "Reverse Pyramid"; } case 4: { for (int left = -100; left <= 100; left++) { for (int bodyIndex = 0; bodyIndex < 150; bodyIndex++) { Vector2f pos = Vector2f(left * 15, 15 + bodyIndex * 10); Vector2f size(5 - bodyIndex * 0.03f, 5); world.AddBody(Coords2f(pos, 0.f), size); } } return "Stacks"; } case 5: { world.AddBody(Coords2f(Vector2f(0.f, 400.f), 0.f), Vector2f(600.f, 10.f))->invMass = 0.f; world.AddBody(Coords2f(Vector2f(800.f, 200.f), 0.f), Vector2f(400.f, 10.f))->invMass = 0.f; for (int bodyIndex = 0; bodyIndex < 20000; bodyIndex++) { Vector2f pos = Vector2f(random(0.0f, 500.0f), random(500.f, 2500.0f)); Vector2f size(4.f, 4.f); world.AddBody(Coords2f(pos, 0.f), size); } return "Stacks"; } case 6: { world.AddBody(Coords2f(Vector2f(0.f, 400.f), 0.f), Vector2f(600.f, 10.f))->invMass = 0.f; world.AddBody(Coords2f(Vector2f(800.f, 200.f), 0.f), Vector2f(400.f, 10.f))->invMass = 0.f; RigidBody* body = world.AddBody(Coords2f(Vector2f(500.f, 500.f), -0.5f), Vector2f(600.f, 10.f)); body->invMass = 0.f; body->invInertia = 0.f; for (int bodyIndex = 0; bodyIndex < 10000; bodyIndex++) { Vector2f pos1 = Vector2f(random(200.0f, 500.0f), random(500.f, 2500.0f)); Vector2f pos2 = Vector2f(random(-500.0f, -200.0f), random(500.f, 2500.0f)); Vector2f size(4.f, 4.f); world.AddBody(Coords2f(pos1, 0.f), size); world.AddBody(Coords2f(pos2, 0.f), size); } return "Dual Stacks"; } case 7: { for (int group = -5; group <= 5; ++group) { RigidBody* splitter = world.AddBody(Coords2f(Vector2f(group * 300, 500.f), 0.f), Vector2f(20.f, 1000.f)); splitter->invMass = 0.f; splitter->invInertia = 0.f; for (int bodyIndex = 0; bodyIndex < 4500; bodyIndex++) { Vector2f pos = Vector2f(group * 300 + random(50.f, 250.0f), random(50.f, 1500.0f)); Vector2f size(4.f, 4.f); world.AddBody(Coords2f(pos, 0.f), size); } } return "Islands"; } } return "Empty"; } bool keyPressed[GLFW_KEY_LAST + 1]; int mouseScrollDelta = 0; static void errorCallback(int error, const char* description) { fputs(description, stderr); } static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { keyPressed[key] = (action == GLFW_PRESS); } static void scrollCallback(GLFWwindow* window, double x, double y) { mouseScrollDelta = y; } int main(int argc, char** argv) { MicroProfileOnThreadCreate("Main"); MicroProfileSetEnableAllGroups(true); MicroProfileSetForceMetaCounters(true); int windowWidth = 1280, windowHeight = 1024; std::unique_ptr<WorkQueue> queue(new WorkQueue(WorkQueue::getIdealWorkerCount() - 1)); World world; int currentSolveMode = sizeof(kSolveModes) / sizeof(kSolveModes[0]) - 1; int currentIslandMode = sizeof(kIslandModes) / sizeof(kIslandModes[0]) - 1; int currentScene = 0; const char* currentSceneName = resetWorld(world, currentScene); const float gravity = -200.0f; const float integrationTime = 1 / 60.f; world.gravity = gravity; glfwSetErrorCallback(errorCallback); if (!glfwInit()) return 1; GLFWwindow* window = glfwCreateWindow(windowWidth, windowHeight, "PhyX", NULL, NULL); if (!window) return 1; glfwMakeContextCurrent(window); glfwSwapInterval(1); glfwSetKeyCallback(window, keyCallback); glfwSetScrollCallback(window, scrollCallback); #ifdef _WIN32 if (!gladLoadGL()) return 2; #endif MicroProfileDrawInitGL(); MicroProfileGpuInitGL(); bool paused = false; double prevUpdateTime = 0.0f; std::vector<Vertex> vertices; float viewOffsetX = -500; float viewOffsetY = -40; float viewScale = 0.5f; int frameIndex = 0; while (!glfwWindowShouldClose(window)) { MicroProfileFlip(); MICROPROFILE_SCOPEI("MAIN", "Frame", 0xffee00); MICROPROFILE_LABELF("MAIN", "Index %d", frameIndex++); int width, height; glfwGetWindowSize(window, &width, &height); int frameWidth, frameHeight; glfwGetFramebufferSize(window, &frameWidth, &frameHeight); double mouseX, mouseY; glfwGetCursorPos(window, &mouseX, &mouseY); glViewport(0, 0, frameWidth, frameHeight); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(viewOffsetX / viewScale, width / viewScale + viewOffsetX / viewScale, viewOffsetY / viewScale, height / viewScale + viewOffsetY / viewScale, 1.f, -1.f); vertices.clear(); if (glfwGetTime() > prevUpdateTime + integrationTime) { prevUpdateTime += integrationTime; if (!paused) { RigidBody* draggedBody = &world.bodies[1]; Vector2f dragTarget = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) ? Vector2f(mouseX + viewOffsetX, height + viewOffsetY - mouseY) / viewScale : draggedBody->coords.pos; Vector2f dstVelocity = (dragTarget - draggedBody->coords.pos) * 5e1f; draggedBody->acceleration.y -= gravity; draggedBody->acceleration += (dstVelocity - draggedBody->velocity) * 5e0; Configuration config = { kSolveModes[currentSolveMode].mode, kIslandModes[currentIslandMode].mode, 15, 15 }; world.Update(*queue, integrationTime, config); } } char stats[256]; sprintf(stats, "Scene: %s | Bodies: %d Manifolds: %d Contacts: %d Islands: %d (biggest: %d) | Cores: %d; Solve: %s; Island: %s; Iterations: %.2f", currentSceneName, int(world.bodies.size), int(world.collider.manifolds.size), int(world.solver.contactJoints.size), int(world.solver.islandCount), int(world.solver.islandMaxSize), int(queue->getWorkerCount() + 1), kSolveModes[currentSolveMode].name, kIslandModes[currentIslandMode].name, 0.f); { MICROPROFILE_SCOPEI("Render", "Render", 0xff0000); { MICROPROFILE_SCOPEI("Render", "Prepare", -1); for (int bodyIndex = 0; bodyIndex < world.bodies.size; bodyIndex++) { RigidBody* body = &world.bodies[bodyIndex]; Coords2f bodyCoords = body->coords; Vector2f size = body->geom.size; float colorMult = float(bodyIndex) / float(world.bodies.size) * 0.5f + 0.5f; int r = 50 * colorMult; int g = 125 * colorMult; int b = 218 * colorMult; if (bodyIndex == 1) //dragged body { r = 242; g = 236; b = 164; } RenderBox(vertices, bodyCoords, size, r, g, b, 255); } if (glfwGetKey(window, GLFW_KEY_V)) { for (int manifoldIndex = 0; manifoldIndex < world.collider.manifolds.size; manifoldIndex++) { Manifold& man = world.collider.manifolds[manifoldIndex]; for (int collisionNumber = 0; collisionNumber < man.pointCount; collisionNumber++) { ContactPoint& cp = world.collider.contactPoints[man.pointIndex + collisionNumber]; Coords2f coords = Coords2f(Vector2f(0.0f, 0.0f), 3.1415f / 4.0f); coords.pos = world.bodies[man.body1Index].coords.pos + cp.delta1; float redMult = cp.isNewlyCreated ? 0.5f : 1.0f; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 100, 100 * redMult, 100 * redMult, 100); coords.pos = world.bodies[man.body2Index].coords.pos + cp.delta2; RenderBox(vertices, coords, Vector2f(3.0f, 3.0f), 150, 150 * redMult, 150 * redMult, 100); } } } } { MICROPROFILE_SCOPEI("Render", "Perform", -1); MICROPROFILE_SCOPEGPUI("Scene", -1); if (!vertices.empty()) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &vertices[0].position); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &vertices[0].r); glDrawArrays(GL_QUADS, 0, vertices.size()); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } } { MICROPROFILE_SCOPEI("Render", "Profile", -1); MICROPROFILE_SCOPEGPUI("Profile", -1); MicroProfileBeginDraw(width, height, 1.f); MicroProfileDraw(width, height); MicroProfileDrawText(2, height - 12, 0xffffffff, stats, strlen(stats)); MicroProfileEndDraw(); } } MICROPROFILE_COUNTER_ADD("frame/count", 1); { MICROPROFILE_SCOPEI("MAIN", "Flip", 0xffee00); glfwSwapBuffers(window); } { MICROPROFILE_SCOPEI("MAIN", "Input", 0xffee00); // Handle input memset(keyPressed, 0, sizeof(keyPressed)); mouseScrollDelta = 0; glfwPollEvents(); bool mouseDown0 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS; bool mouseDown1 = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; MicroProfileMouseButton(mouseDown0, mouseDown1); MicroProfileMousePosition(mouseX, mouseY, mouseScrollDelta); MicroProfileModKey(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS); if (keyPressed[GLFW_KEY_ESCAPE]) break; if (keyPressed[GLFW_KEY_O]) MicroProfileToggleDisplayMode(); if (keyPressed[GLFW_KEY_P]) { paused = !paused; MicroProfileTogglePause(); } if (keyPressed[GLFW_KEY_I]) currentIslandMode = (currentIslandMode + 1) % (sizeof(kIslandModes) / sizeof(kIslandModes[0])); if (keyPressed[GLFW_KEY_M]) currentSolveMode = (currentSolveMode + 1) % (sizeof(kSolveModes) / sizeof(kSolveModes[0])); if (keyPressed[GLFW_KEY_R]) currentSceneName = resetWorld(world, currentScene); if (keyPressed[GLFW_KEY_S]) currentSceneName = resetWorld(world, ++currentScene); if (keyPressed[GLFW_KEY_C]) { unsigned int cores = queue->getWorkerCount() + 1; unsigned int newcores = (cores == WorkQueue::getIdealWorkerCount()) ? 1 : std::min(cores * 2, WorkQueue::getIdealWorkerCount()); queue.reset(new WorkQueue(newcores - 1)); } if (glfwGetKey(window, GLFW_KEY_LEFT)) viewOffsetX -= 10; if (glfwGetKey(window, GLFW_KEY_RIGHT)) viewOffsetX += 10; if (glfwGetKey(window, GLFW_KEY_UP)) viewScale *= 1.05f; if (glfwGetKey(window, GLFW_KEY_DOWN)) viewScale /= 1.05f; } } glfwDestroyWindow(window); glfwTerminate(); MicroProfileShutdown(); }
zeux/phyx
112
2D physics engine with SoA/SIMD optimizations
C
zeux
Arseny Kapoulkine
docs/manual.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 2.0.23"> <meta name="author" content="website, repository"> <title>pugixml 1.15 manual</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"> <style> /*! Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */ /* Uncomment the following line when using as a custom stylesheet */ /* @import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"; */ html{font-family:sans-serif;-webkit-text-size-adjust:100%} a{background:none} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} b,strong{font-weight:bold} abbr{font-size:.9em} abbr[title]{cursor:help;border-bottom:1px dotted #dddddf;text-decoration:none} dfn{font-style:italic} hr{height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} audio,video{display:inline-block} audio:not([controls]){display:none;height:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type=checkbox],input[type=radio]{padding:0} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,::before,::after{box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;line-height:1;position:relative;cursor:auto;-moz-tab-size:4;-o-tab-size:4;tab-size:4;word-wrap:anywhere;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:0} p{line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ul.square{list-style-type:square} ul.circle ul:not([class]),ul.disc ul:not([class]),ul.square ul:not([class]){list-style:inherit} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:1px solid #dedede;word-wrap:normal} table thead,table tfoot{background:#f7f8f7} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt{background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .center{margin-left:auto;margin-right:auto} .stretch{width:100%} .clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table} .clearfix::after,.float-group::after{clear:both} :not(pre).nobreak{word-wrap:normal} :not(pre).nowrap{white-space:nowrap} :not(pre).pre-wrap{white-space:pre-wrap} :not(pre):not([class^=L])>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background:#f7f7f8;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed} pre{color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;line-height:1.45;text-rendering:optimizeSpeed} pre code,pre pre{color:inherit;font-size:inherit;line-height:inherit} pre>code{display:block} pre.nowrap,pre.nowrap pre{white-space:pre;word-wrap:normal} em em{font-style:normal} strong strong{font-weight:400} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background:#f7f7f7;border:1px solid #ccc;border-radius:3px;box-shadow:0 1px 0 rgba(0,0,0,.2),inset 0 0 0 .1em #fff;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menuref{color:#000} .menuseq b:not(.caret),.menuref{font-weight:inherit} .menuseq{word-spacing:-.02em} .menuseq b.caret{font-size:1.25em;line-height:.8} .menuseq i.caret{font-weight:bold;text-align:center;width:.45em} b.button::before,b.button::after{position:relative;top:-1px;font-weight:400} b.button::before{content:"[";padding:0 3px 0 2px} b.button::after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin:0 auto;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table} #header::after,#content::after,#footnotes::after,#footer::after{clear:both} #content{margin-top:1.25em} #content::before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf} #header>h1:only-child{border-bottom:1px solid #dddddf;padding-bottom:8px} #header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:flex;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span::before{content:"\00a0\2013\00a0"} #header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark::before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber::after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px} #toc.toc2{margin-top:0!important;background:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}} @media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border:1px solid #e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:none;background:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:hsla(0,0%,100%,.8);line-height:1.44} #content{margin-bottom:.625em} .sect1{padding-bottom:.625em} @media screen and (min-width:768px){#content{margin-bottom:1.25em} .sect1{padding-bottom:1.25em}} .sect1:last-child{padding-bottom:0} .sect1+.sect1{border-top:1px solid #e7e7e9} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} details,.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} details{margin-left:1.25rem} details>summary{cursor:pointer;display:block;position:relative;line-height:1.6;margin-bottom:.625rem;outline:none;-webkit-tap-highlight-color:transparent} details>summary::-webkit-details-marker{display:none} details>summary::before{content:"";border:solid transparent;border-left:solid;border-width:.3em 0 .3em .5em;position:absolute;top:.5em;left:-1.25rem;transform:translateX(15%)} details[open]>summary::before{border:solid transparent;border-top:solid;border-width:.5em .3em 0;transform:translateY(15%)} details>summary::after{content:"";width:1.25rem;height:1em;position:absolute;top:.3em;left:-1.25rem} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock.fit-content>caption.title{white-space:nowrap;width:0} .paragraph.lead>p,#preamble>.sectionbody>[class=paragraph]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6);word-wrap:anywhere} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border:1px solid #e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;border-radius:4px} .sidebarblock{border:1px solid #dbdbd6;margin-bottom:1.25em;padding:1.25em;background:#f3f3f2;border-radius:4px} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:first-child,.sidebarblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child,.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock>.content>pre{border-radius:4px;overflow-x:auto;padding:1em;font-size:.8125em} @media screen and (min-width:768px){.literalblock pre,.listingblock>.content>pre{font-size:.90625em}} @media screen and (min-width:1280px){.literalblock pre,.listingblock>.content>pre{font-size:1em}} .literalblock pre,.listingblock>.content>pre:not(.highlight),.listingblock>.content>pre[class=highlight],.listingblock>.content>pre[class^="highlight "]{background:#f7f7f8} .literalblock.output pre{color:#f7f7f8;background:rgba(0,0,0,.9)} .listingblock>.content{position:relative} .listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:inherit;opacity:.5} .listingblock:hover code[data-lang]::before{display:block} .listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:inherit;opacity:.5} .listingblock.terminal pre .command:not([data-prompt])::before{content:"$"} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .prettyprint{background:#f7f7f8} pre.prettyprint .linenums{line-height:1.45;margin-left:2em} pre.prettyprint li{background:none;list-style-type:inherit;padding-left:0} pre.prettyprint li code[data-lang]::before{opacity:1} pre.prettyprint li:not(:first-child) code[data-lang]::before{display:none} table.linenotable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.linenotable td[class]{color:inherit;vertical-align:top;padding:0;line-height:inherit;white-space:normal} table.linenotable td.code{padding-left:.75em} table.linenotable td.linenos,pre.pygments .linenos{border-right:1px solid;opacity:.35;padding-right:.5em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none} pre.pygments span.linenos{display:inline-block;margin-right:.75em} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock:not(.excerpt)>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right} .verseblock{margin:0 1em 1.25em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans-serif;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none} .quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0} .quoteblock.abstract{margin:0 1em 1.25em;display:block} .quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center} .quoteblock.excerpt>blockquote,.quoteblock .quoteblock{padding:0 0 .25em 1em;border-left:.25em solid #dddddf} .quoteblock.excerpt,.quoteblock .quoteblock{margin-left:0} .quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem} .quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;font-size:.85rem;text-align:left;margin-right:0} p.tableblock:last-child{margin-bottom:0} td.tableblock>.content{margin-bottom:1.25em;word-wrap:anywhere} td.tableblock>.content>:last-child{margin-bottom:-1.25em} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all>*>tr>*{border-width:1px} table.grid-cols>*>tr>*{border-width:0 1px} table.grid-rows>*>tr>*{border-width:1px 0} table.frame-all{border-width:1px} table.frame-ends{border-width:1px 0} table.frame-sides{border-width:0 1px} table.frame-none>colgroup+*>:first-child>*,table.frame-sides>colgroup+*>:first-child>*{border-top-width:0} table.frame-none>:last-child>:last-child>*,table.frame-sides>:last-child>:last-child>*{border-bottom-width:0} table.frame-none>*>tr>:first-child,table.frame-ends>*>tr>:first-child{border-left-width:0} table.frame-none>*>tr>:last-child,table.frame-ends>*>tr>:last-child{border-right-width:0} table.stripes-all>*>tr,table.stripes-odd>*>tr:nth-of-type(odd),table.stripes-even>*>tr:nth-of-type(even),table.stripes-hover>*>tr:hover{background:#f8f8f7} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none} ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em} ul.unstyled,ol.unstyled{margin-left:0} li>p:empty:only-child::before{content:"";display:inline-block} ul.checklist>li>p:first-child{margin-left:-1em} ul.checklist>li>p:first-child>.fa-square-o:first-child,ul.checklist>li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em} ul.checklist>li>p:first-child>input[type=checkbox]:first-child{margin-right:.25em} ul.inline{display:flex;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em} ul.inline>li{margin-left:1.25em} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} td.hdlist2{word-wrap:anywhere} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top} .colist td:not([class]):first-child img{max-width:none} .colist td:not([class]):last-child{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:4px solid #fff;box-shadow:0 0 0 1px #ddd} .imageblock.left{margin:.25em .625em 1.25em 0} .imageblock.right{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active,#footnotes .footnote a:first-of-type:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background:#00fafa} .black{color:#000} .black-background{background:#000} .blue{color:#0000bf} .blue-background{background:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background:#fa00fa} .gray{color:#606060} .gray-background{background:#7d7d7d} .green{color:#006000} .green-background{background:#007d00} .lime{color:#00bf00} .lime-background{background:#00fa00} .maroon{color:#600000} .maroon-background{background:#7d0000} .navy{color:#000060} .navy-background{background:#00007d} .olive{color:#606000} .olive-background{background:#7d7d00} .purple{color:#600060} .purple-background{background:#7d007d} .red{color:#bf0000} .red-background{background:#fa0000} .silver{color:#909090} .silver-background{background:#bcbcbc} .teal{color:#006060} .teal-background{background:#007d7d} .white{color:#bfbfbf} .white-background{background:#fafafa} .yellow{color:#bfbf00} .yellow-background{background:#fafa00} span.icon>.fa{cursor:default} a span.icon>.fa{cursor:inherit} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background:rgba(0,0,0,.8);border-radius:50%;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]::after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt,summary{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,td.hdlist1,span.alt,summary{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background:#fffef7;border-color:#e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @page{margin:1.25cm .75cm} @media print{*{box-shadow:none!important;text-shadow:none!important} html{font-size:80%} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]{border-bottom:1px dotted} abbr[title]::after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #header,#content,#footnotes,#footer{max-width:none} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span::before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]::before{display:block} #footer{padding:0 .9375em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} @media amzn-kf8,print{#header>h1:first-child{margin-top:1.25rem} .sect1{padding:0!important} .sect1+.sect1{border:0} #footer{background:none} #footer-text{color:rgba(0,0,0,.6);font-size:.9em}} @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} </style> <style> pre.pygments .hll { background-color: #ffffcc } pre.pygments { background: #f8f8f8; } pre.pygments .tok-c { color: #3D7B7B; font-style: italic } /* Comment */ pre.pygments .tok-err { border: 1px solid #FF0000 } /* Error */ pre.pygments .tok-k { color: #008000; font-weight: bold } /* Keyword */ pre.pygments .tok-o { color: #666666 } /* Operator */ pre.pygments .tok-ch { color: #3D7B7B; font-style: italic } /* Comment.Hashbang */ pre.pygments .tok-cm { color: #3D7B7B; font-style: italic } /* Comment.Multiline */ pre.pygments .tok-cp { color: #9C6500 } /* Comment.Preproc */ pre.pygments .tok-cpf { color: #3D7B7B; font-style: italic } /* Comment.PreprocFile */ pre.pygments .tok-c1 { color: #3D7B7B; font-style: italic } /* Comment.Single */ pre.pygments .tok-cs { color: #3D7B7B; font-style: italic } /* Comment.Special */ pre.pygments .tok-gd { color: #A00000 } /* Generic.Deleted */ pre.pygments .tok-ge { font-style: italic } /* Generic.Emph */ pre.pygments .tok-ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ pre.pygments .tok-gr { color: #E40000 } /* Generic.Error */ pre.pygments .tok-gh { color: #000080; font-weight: bold } /* Generic.Heading */ pre.pygments .tok-gi { color: #008400 } /* Generic.Inserted */ pre.pygments .tok-go { color: #717171 } /* Generic.Output */ pre.pygments .tok-gp { color: #000080; font-weight: bold } /* Generic.Prompt */ pre.pygments .tok-gs { font-weight: bold } /* Generic.Strong */ pre.pygments .tok-gu { color: #800080; font-weight: bold } /* Generic.Subheading */ pre.pygments .tok-gt { color: #0044DD } /* Generic.Traceback */ pre.pygments .tok-kc { color: #008000; font-weight: bold } /* Keyword.Constant */ pre.pygments .tok-kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ pre.pygments .tok-kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ pre.pygments .tok-kp { color: #008000 } /* Keyword.Pseudo */ pre.pygments .tok-kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ pre.pygments .tok-kt { color: #B00040 } /* Keyword.Type */ pre.pygments .tok-m { color: #666666 } /* Literal.Number */ pre.pygments .tok-s { color: #BA2121 } /* Literal.String */ pre.pygments .tok-na { color: #687822 } /* Name.Attribute */ pre.pygments .tok-nb { color: #008000 } /* Name.Builtin */ pre.pygments .tok-nc { color: #0000FF; font-weight: bold } /* Name.Class */ pre.pygments .tok-no { color: #880000 } /* Name.Constant */ pre.pygments .tok-nd { color: #AA22FF } /* Name.Decorator */ pre.pygments .tok-ni { color: #717171; font-weight: bold } /* Name.Entity */ pre.pygments .tok-ne { color: #CB3F38; font-weight: bold } /* Name.Exception */ pre.pygments .tok-nf { color: #0000FF } /* Name.Function */ pre.pygments .tok-nl { color: #767600 } /* Name.Label */ pre.pygments .tok-nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ pre.pygments .tok-nt { color: #008000; font-weight: bold } /* Name.Tag */ pre.pygments .tok-nv { color: #19177C } /* Name.Variable */ pre.pygments .tok-ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ pre.pygments .tok-w { color: #bbbbbb } /* Text.Whitespace */ pre.pygments .tok-mb { color: #666666 } /* Literal.Number.Bin */ pre.pygments .tok-mf { color: #666666 } /* Literal.Number.Float */ pre.pygments .tok-mh { color: #666666 } /* Literal.Number.Hex */ pre.pygments .tok-mi { color: #666666 } /* Literal.Number.Integer */ pre.pygments .tok-mo { color: #666666 } /* Literal.Number.Oct */ pre.pygments .tok-sa { color: #BA2121 } /* Literal.String.Affix */ pre.pygments .tok-sb { color: #BA2121 } /* Literal.String.Backtick */ pre.pygments .tok-sc { color: #BA2121 } /* Literal.String.Char */ pre.pygments .tok-dl { color: #BA2121 } /* Literal.String.Delimiter */ pre.pygments .tok-sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ pre.pygments .tok-s2 { color: #BA2121 } /* Literal.String.Double */ pre.pygments .tok-se { color: #AA5D1F; font-weight: bold } /* Literal.String.Escape */ pre.pygments .tok-sh { color: #BA2121 } /* Literal.String.Heredoc */ pre.pygments .tok-si { color: #A45A77; font-weight: bold } /* Literal.String.Interpol */ pre.pygments .tok-sx { color: #008000 } /* Literal.String.Other */ pre.pygments .tok-sr { color: #A45A77 } /* Literal.String.Regex */ pre.pygments .tok-s1 { color: #BA2121 } /* Literal.String.Single */ pre.pygments .tok-ss { color: #19177C } /* Literal.String.Symbol */ pre.pygments .tok-bp { color: #008000 } /* Name.Builtin.Pseudo */ pre.pygments .tok-fm { color: #0000FF } /* Name.Function.Magic */ pre.pygments .tok-vc { color: #19177C } /* Name.Variable.Class */ pre.pygments .tok-vg { color: #19177C } /* Name.Variable.Global */ pre.pygments .tok-vi { color: #19177C } /* Name.Variable.Instance */ pre.pygments .tok-vm { color: #19177C } /* Name.Variable.Magic */ pre.pygments .tok-il { color: #666666 } /* Literal.Number.Integer.Long */ </style> </head> <body class="article toc2 toc-right"> <div id="header"> <h1>pugixml 1.15 manual</h1> <div class="details"> <span id="author" class="author">website</span><br> <span id="email" class="email"><a href="https://pugixml.org" class="bare">https://pugixml.org</a></span><br> <span id="author2" class="author">repository</span><br> <span id="email2" class="email"><a href="https://github.com/zeux/pugixml" class="bare">https://github.com/zeux/pugixml</a></span><br> </div> <div id="toc" class="toc2"> <div id="toctitle">Table of Contents</div> <ul class="sectlevel1"> <li><a href="#overview">1. Overview</a> <ul class="sectlevel2"> <li><a href="#overview.introduction">1.1. Introduction</a></li> <li><a href="#overview.feedback">1.2. Feedback</a></li> <li><a href="#overview.thanks">1.3. Acknowledgments</a></li> <li><a href="#overview.license">1.4. License</a></li> </ul> </li> <li><a href="#install">2. Installation</a> <ul class="sectlevel2"> <li><a href="#install.getting">2.1. Getting pugixml</a></li> <li><a href="#install.building">2.2. Building pugixml</a></li> <li><a href="#install.portability">2.3. Portability</a></li> </ul> </li> <li><a href="#dom">3. Document object model</a> <ul class="sectlevel2"> <li><a href="#dom.tree">3.1. Tree structure</a></li> <li><a href="#dom.cpp">3.2. C&#43;&#43; interface</a></li> <li><a href="#dom.unicode">3.3. Unicode interface</a></li> <li><a href="#dom.thread">3.4. Thread-safety guarantees</a></li> <li><a href="#dom.exception">3.5. Exception guarantees</a></li> <li><a href="#dom.memory">3.6. Memory management</a></li> </ul> </li> <li><a href="#loading">4. Loading document</a> <ul class="sectlevel2"> <li><a href="#loading.file">4.1. Loading document from file</a></li> <li><a href="#loading.memory">4.2. Loading document from memory</a></li> <li><a href="#loading.stream">4.3. Loading document from C&#43;&#43; IOstreams</a></li> <li><a href="#loading.errors">4.4. Handling parsing errors</a></li> <li><a href="#loading.options">4.5. Parsing options</a></li> <li><a href="#loading.encoding">4.6. Encodings</a></li> <li><a href="#loading.w3c">4.7. Conformance to W3C specification</a></li> </ul> </li> <li><a href="#access">5. Accessing document data</a> <ul class="sectlevel2"> <li><a href="#access.basic">5.1. Basic traversal functions</a></li> <li><a href="#access.nodedata">5.2. Getting node data</a></li> <li><a href="#access.attrdata">5.3. Getting attribute data</a></li> <li><a href="#access.contents">5.4. Contents-based traversal functions</a></li> <li><a href="#access.rangefor">5.5. Range-based for-loop support</a></li> <li><a href="#access.iterators">5.6. Traversing node/attribute lists via iterators</a></li> <li><a href="#access.walker">5.7. Recursive traversal with xml_tree_walker</a></li> <li><a href="#access.predicate">5.8. Searching for nodes/attributes with predicates</a></li> <li><a href="#access.text">5.9. Working with text contents</a></li> <li><a href="#access.misc">5.10. Miscellaneous functions</a></li> </ul> </li> <li><a href="#modify">6. Modifying document data</a> <ul class="sectlevel2"> <li><a href="#modify.nodedata">6.1. Setting node data</a></li> <li><a href="#modify.attrdata">6.2. Setting attribute data</a></li> <li><a href="#modify.add">6.3. Adding nodes/attributes</a></li> <li><a href="#modify.remove">6.4. Removing nodes/attributes</a></li> <li><a href="#modify.text">6.5. Working with text contents</a></li> <li><a href="#modify.clone">6.6. Cloning nodes/attributes</a></li> <li><a href="#modify.move">6.7. Moving nodes</a></li> <li><a href="#modify.fragments">6.8. Assembling document from fragments</a></li> </ul> </li> <li><a href="#saving">7. Saving document</a> <ul class="sectlevel2"> <li><a href="#saving.file">7.1. Saving document to a file</a></li> <li><a href="#saving.stream">7.2. Saving document to C&#43;&#43; IOstreams</a></li> <li><a href="#saving.writer">7.3. Saving document via writer interface</a></li> <li><a href="#saving.subtree">7.4. Saving a single subtree</a></li> <li><a href="#saving.options">7.5. Output options</a></li> <li><a href="#saving.encoding">7.6. Encodings</a></li> <li><a href="#saving.declaration">7.7. Customizing document declaration</a></li> </ul> </li> <li><a href="#xpath">8. XPath</a> <ul class="sectlevel2"> <li><a href="#xpath.types">8.1. XPath types</a></li> <li><a href="#xpath.select">8.2. Selecting nodes via XPath expression</a></li> <li><a href="#xpath.query">8.3. Using query objects</a></li> <li><a href="#xpath.variables">8.4. Using variables</a></li> <li><a href="#xpath.errors">8.5. Error handling</a></li> <li><a href="#xpath.w3c">8.6. Conformance to W3C specification</a></li> </ul> </li> <li><a href="#changes">9. Changelog</a> <ul class="sectlevel2"> <li><a href="#v1.15">v1.15 <sup>2024-01-10</sup></a></li> <li><a href="#v1.14">v1.14 <sup>2023-10-01</sup></a></li> <li><a href="#v1.13">v1.13 <sup>2022-11-01</sup></a></li> <li><a href="#v1.12">v1.12 <sup>2022-02-09</sup></a></li> <li><a href="#v1.11">v1.11 <sup>2020-11-26</sup></a></li> <li><a href="#v1.10">v1.10 <sup>2019-09-15</sup></a></li> <li><a href="#v1.9">v1.9 <sup>2018-04-04</sup></a></li> <li><a href="#v1.8">v1.8 <sup>2016-11-24</sup></a></li> <li><a href="#v1.7">v1.7 <sup>2015-10-19</sup></a></li> <li><a href="#v1.6">v1.6 <sup>2015-04-10</sup></a></li> <li><a href="#v1.5">v1.5 <sup>2014-11-27</sup></a></li> <li><a href="#v1.4">v1.4 <sup>2014-02-27</sup></a></li> <li><a href="#v1.2">v1.2 <sup>2012-05-01</sup></a></li> <li><a href="#v1.0">v1.0 <sup>2010-11-01</sup></a></li> <li><a href="#v0.9">v0.9 <sup>2010-07-01</sup></a></li> <li><a href="#v0.5">v0.5 <sup>2009-11-08</sup></a></li> <li><a href="#v0.42">v0.42 <sup>2009-09-17</sup></a></li> <li><a href="#v0.41">v0.41 <sup>2009-02-08</sup></a></li> <li><a href="#v0.4">v0.4 <sup>2009-01-18</sup></a></li> <li><a href="#v0.34">v0.34 <sup>2007-10-31</sup></a></li> <li><a href="#v0.3">v0.3 <sup>2007-02-21</sup></a></li> <li><a href="#v0.2">v0.2 <sup>2006-11-06</sup></a></li> <li><a href="#v0.1">v0.1 <sup>2006-07-15</sup></a></li> </ul> </li> <li><a href="#apiref">10. API Reference</a> <ul class="sectlevel2"> <li><a href="#apiref.macros">10.1. Macros</a></li> <li><a href="#apiref.types">10.2. Types</a></li> <li><a href="#apiref.enums">10.3. Enumerations</a></li> <li><a href="#apiref.constants">10.4. Constants</a></li> <li><a href="#apiref.classes">10.5. Classes</a></li> <li><a href="#apiref.functions">10.6. Functions</a></li> </ul> </li> </ul> </div> </div> <div id="content"> <div class="sect1"> <h2 id="overview"><a class="anchor" href="#overview"></a><a class="link" href="#overview">1. Overview</a></h2> <div class="sectionbody"> <div class="sect2"> <h3 id="overview.introduction"><a class="anchor" href="#overview.introduction"></a><a class="link" href="#overview.introduction">1.1. Introduction</a></h3> <div class="paragraph"> <p><a href="https://pugixml.org/">pugixml</a> is a light-weight C&#43;&#43; XML processing library. It consists of a DOM-like interface with rich traversal/modification capabilities, an extremely fast XML parser which constructs the DOM tree from an XML file/buffer, and an <a href="#xpath">XPath 1.0 implementation</a> for complex data-driven tree queries. Full Unicode support is also available, with <a href="#dom.unicode">two Unicode interface variants</a> and conversions between different Unicode encodings (which happen automatically during parsing/saving). The library is <a href="#install.portability">extremely portable</a> and easy to integrate and use. pugixml is developed and maintained since 2006 and has many users. All code is distributed under the <a href="#overview.license">MIT license</a>, making it completely free to use in both open-source and proprietary applications.</p> </div> <div class="paragraph"> <p>pugixml enables very fast, convenient and memory-efficient XML document processing. However, since pugixml has a DOM parser, it can&#8217;t process XML documents that do not fit in memory; also the parser is a non-validating one, so if you need DTD or XML Schema validation, the library is not for you.</p> </div> <div class="paragraph"> <p>This is the complete manual for pugixml, which describes all features of the library in detail. If you want to start writing code as quickly as possible, you are advised to <a href="quickstart.html">read the quick start guide first</a>.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> No documentation is perfect; neither is this one. If you find errors or omissions, please don’t hesitate to <a href="https://github.com/zeux/pugixml/issues/new">submit an issue or open a pull request</a> with a fix. </td> </tr> </table> </div> </div> <div class="sect2"> <h3 id="overview.feedback"><a class="anchor" href="#overview.feedback"></a><a class="link" href="#overview.feedback">1.2. Feedback</a></h3> <div class="paragraph"> <p>If you believe you&#8217;ve found a bug in pugixml (bugs include compilation problems (errors/warnings), crashes, performance degradation and incorrect behavior), please file an issue via <a href="https://github.com/zeux/pugixml/issues/new">issue submission form</a>. Be sure to include the relevant information so that the bug can be reproduced: the version of pugixml, compiler version and target architecture, the code that uses pugixml and exhibits the bug, etc.</p> </div> <div class="paragraph"> <p>Feature requests can be reported the same way as bugs, so if you&#8217;re missing some functionality in pugixml or if the API is rough in some places and you can suggest an improvement, <a href="https://github.com/zeux/pugixml/issues/new">file an issue</a>. However please note that there are many factors when considering API changes (compatibility with previous versions, API redundancy, etc.), so generally features that can be implemented via a small function without pugixml modification are not accepted. However, all rules have exceptions.</p> </div> <div class="paragraph"> <p>If you have a contribution to pugixml, such as build script for some build system/IDE, or a well-designed set of helper functions, or a binding to some language other than C&#43;&#43;, please <a href="https://github.com/zeux/pugixml/issues/new">file an issue or open a pull request</a>. Your contribution has to be distributed under the terms of a license that&#8217;s compatible with pugixml license; i.e. GPL/LGPL licensed code is not accepted.</p> </div> <div class="paragraph"> <p>If filing an issue is not possible due to privacy or other concerns, you can contact pugixml author by e-mail directly: <a href="mailto:arseny.kapoulkine@gmail.com">arseny.kapoulkine@gmail.com</a>.</p> </div> </div> <div class="sect2"> <h3 id="overview.thanks"><a class="anchor" href="#overview.thanks"></a><a class="link" href="#overview.thanks">1.3. Acknowledgments</a></h3> <div class="paragraph"> <p>pugixml could not be developed without the help from many people; some of them are listed in this section. If you&#8217;ve played a part in pugixml development and you can not find yourself on this list, I&#8217;m truly sorry; please <a href="#email">send me an e-mail</a> so I can fix this.</p> </div> <div class="paragraph"> <p>Thanks to <strong>Kristen Wegner</strong> for pugxml parser, which was used as a basis for pugixml.</p> </div> <div class="paragraph"> <p>Thanks to <strong>Neville Franks</strong> for contributions to pugxml parser.</p> </div> <div class="paragraph"> <p>Thanks to <strong>Artyom Palvelev</strong> for suggesting a lazy gap contraction approach.</p> </div> <div class="paragraph"> <p>Thanks to <strong>Vyacheslav Egorov</strong> for documentation proofreading and fuzz testing.</p> </div> </div> <div class="sect2"> <h3 id="overview.license"><a class="anchor" href="#overview.license"></a><a class="link" href="#overview.license">1.4. License</a></h3> <div class="paragraph"> <p>The pugixml library is distributed under the MIT license:</p> </div> <div class="literalblock"> <div class="content"> <pre>Copyright (c) 2006-2026 Arseny Kapoulkine Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</pre> </div> </div> <div class="paragraph"> <p>This means that you can freely use pugixml in your applications, both open-source and proprietary. If you use pugixml in a product, it is sufficient to add an acknowledgment like this to the product distribution:</p> </div> <div class="literalblock"> <div class="content"> <pre>This software is based on pugixml library (https://pugixml.org). pugixml is Copyright (C) 2006-2026 Arseny Kapoulkine.</pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="install"><a class="anchor" href="#install"></a><a class="link" href="#install">2. Installation</a></h2> <div class="sectionbody"> <div class="sect2"> <h3 id="install.getting"><a class="anchor" href="#install.getting"></a><a class="link" href="#install.getting">2.1. Getting pugixml</a></h3> <div class="paragraph"> <p>pugixml is distributed in source form. You can either download a source distribution or clone the Git repository.</p> </div> <div class="sect3"> <h4 id="install.getting.source"><a class="anchor" href="#install.getting.source"></a><a class="link" href="#install.getting.source">2.1.1. Source distributions</a></h4> <div class="paragraph"> <p>You can download the latest source distribution as an archive:</p> </div> <div class="paragraph"> <p><a href="https://github.com/zeux/pugixml/releases/download/v1.15/pugixml-1.15.zip">pugixml-1.15.zip</a> (Windows line endings) / <a href="https://github.com/zeux/pugixml/releases/download/v1.15/pugixml-1.15.tar.gz">pugixml-1.15.tar.gz</a> (Unix line endings)</p> </div> <div class="paragraph"> <p>The distribution contains library source, documentation (the manual you&#8217;re reading now and the quick start guide) and some code examples. After downloading the distribution, install pugixml by extracting all files from the compressed archive.</p> </div> <div class="paragraph"> <p>If you need an older version, you can download it from the <a href="https://github.com/zeux/pugixml/releases">version archive</a>.</p> </div> </div> <div class="sect3"> <h4 id="install.getting.git"><a class="anchor" href="#install.getting.git"></a><a class="link" href="#install.getting.git">2.1.2. Git repository</a></h4> <div class="paragraph"> <p>The Git repository is located at <a href="https://github.com/zeux/pugixml/" class="bare">https://github.com/zeux/pugixml/</a>. There is a Git tag "v{version}" for each version; also there is the "latest" tag, which always points to the latest stable release.</p> </div> <div class="paragraph"> <p>For example, to checkout the current version, you can use this command:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="bash">git clone https://github.com/zeux/pugixml cd pugixml git checkout v1.15</code></pre> </div> </div> <div class="paragraph"> <p>The repository contains library source, documentation, code examples and full unit test suite.</p> </div> <div class="paragraph"> <p>Use <code>latest</code> tag if you want to automatically get new versions. Use other tags if you want to switch to new versions only explicitly. Also please note that the master branch contains the work-in-progress version of the code; while this means that you can get new features and bug fixes from master without waiting for a new release, this also means that occasionally the code can be broken in some configurations.</p> </div> </div> <div class="sect3"> <h4 id="install.getting.subversion"><a class="anchor" href="#install.getting.subversion"></a><a class="link" href="#install.getting.subversion">2.1.3. Subversion repository</a></h4> <div class="paragraph"> <p>You can access the Git repository via Subversion using <a href="https://github.com/zeux/pugixml" class="bare">https://github.com/zeux/pugixml</a> URL. For example, to checkout the current version, you can use this command:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="bash">svn checkout https://github.com/zeux/pugixml/tags/v1.15 pugixml</code></pre> </div> </div> </div> <div class="sect3"> <h4 id="install.getting.packages"><a class="anchor" href="#install.getting.packages"></a><a class="link" href="#install.getting.packages">2.1.4. Packages</a></h4> <div class="paragraph"> <p>pugixml is available as a package via various package managers. Note that most packages are maintained separately from the main repository so they do not necessarily contain the latest version.</p> </div> <div class="paragraph"> <p>Here&#8217;s an incomplete list of pugixml packages in various systems:</p> </div> <div class="ulist"> <ul> <li> <p>Linux (<a href="http://packages.ubuntu.com/search?keywords=pugixml">Ubuntu</a>, <a href="https://tracker.debian.org/pkg/pugixml">Debian</a>, <a href="https://apps.fedoraproject.org/packages/pugixml">Fedora</a>, <a href="https://aur.archlinux.org/packages/pugixml/">Arch Linux</a>, other <a href="http://pkgs.org/search/pugixml">distributions</a>)</p> </li> <li> <p><a href="http://fbsdmon.org/ports/textproc/pugixml">FreeBSD</a></p> </li> <li> <p>OSX, via <a href="http://brewformulas.org/Pugixml">Homebrew</a></p> </li> <li> <p>Windows, via <a href="https://www.nuget.org/packages/pugixml/">NuGet</a></p> </li> </ul> </div> </div> </div> <div class="sect2"> <h3 id="install.building"><a class="anchor" href="#install.building"></a><a class="link" href="#install.building">2.2. Building pugixml</a></h3> <div class="paragraph"> <p>pugixml is distributed in source form without any pre-built binaries; you have to build them yourself.</p> </div> <div class="paragraph"> <p>The complete pugixml source consists of three files - one source file, <code>pugixml.cpp</code>, and two header files, <code>pugixml.hpp</code> and <code>pugiconfig.hpp</code>. <code>pugixml.hpp</code> is the primary header which you need to include in order to use pugixml classes/functions; <code>pugiconfig.hpp</code> is a supplementary configuration file (see <a href="#install.building.config">Additional configuration options</a>). The rest of this guide assumes that <code>pugixml.hpp</code> is either in the current directory or in one of include directories of your projects, so that <code>#include "pugixml.hpp"</code> can find the header; however you can also use relative path (i.e. <code>#include "../libs/pugixml/src/pugixml.hpp"</code>) or include directory-relative path (i.e. <code>#include &lt;xml/thirdparty/pugixml/src/pugixml.hpp&gt;</code>).</p> </div> <div class="sect3"> <h4 id="install.building.embed"><a class="anchor" href="#install.building.embed"></a><a class="link" href="#install.building.embed">2.2.1. Building pugixml as a part of another static library/executable</a></h4> <div class="paragraph"> <p>The easiest way to build pugixml is to compile the source file, <code>pugixml.cpp</code>, along with the existing library/executable. This process depends on the method of building your application; for example, if you&#8217;re using Microsoft Visual Studio <sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>, Apple Xcode, Code::Blocks or any other IDE, just <strong>add <code>pugixml.cpp</code> to one of your projects</strong>.</p> </div> <div class="paragraph"> <p>If you&#8217;re using Microsoft Visual Studio and the project has precompiled headers turned on, you&#8217;ll see the following error messages:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugixml</span><span class="tok-p">.</span><span class="tok-n">cpp</span><span class="tok-p">(</span><span class="tok-mi">3477</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">fatal</span><span class="tok-w"> </span><span class="tok-n">error</span><span class="tok-w"> </span><span class="tok-n">C1010</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">unexpected</span><span class="tok-w"> </span><span class="tok-n">end</span><span class="tok-w"> </span><span class="tok-n">of</span><span class="tok-w"> </span><span class="tok-n">file</span><span class="tok-w"> </span><span class="tok-k">while</span><span class="tok-w"> </span><span class="tok-n">looking</span><span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-n">precompiled</span><span class="tok-w"> </span><span class="tok-n">header</span><span class="tok-p">.</span><span class="tok-w"> </span><span class="tok-n">Did</span><span class="tok-w"> </span><span class="tok-n">you</span><span class="tok-w"> </span><span class="tok-n">forget</span><span class="tok-w"> </span><span class="tok-n">to</span><span class="tok-w"> </span><span class="tok-n">add</span><span class="tok-w"> </span><span class="tok-err">&#39;#</span><span class="tok-n">include</span><span class="tok-w"> </span><span class="tok-s">&quot;stdafx.h&quot;</span><span class="tok-err">&#39;</span><span class="tok-w"> </span><span class="tok-n">to</span><span class="tok-w"> </span><span class="tok-n">your</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-o">?</span></code></pre> </div> </div> <div class="paragraph"> <p>The correct way to resolve this is to disable precompiled headers for <code>pugixml.cpp</code>; you have to set "Create/Use Precompiled Header" option (Properties dialog &#8594; C/C&#43;&#43; &#8594; Precompiled Headers &#8594; Create/Use Precompiled Header) to "Not Using Precompiled Headers". You&#8217;ll have to do it for all project configurations/platforms (you can select Configuration "All Configurations" and Platform "All Platforms" before editing the option):</p> </div> <table class="tableblock frame-none grid-all stretch"> <colgroup> <col style="width: 25%;"> <col style="width: 25%;"> <col style="width: 25%;"> <col style="width: 25%;"> </colgroup> <tbody> <tr> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_pch1.png"><img src="images/vs2005_pch1.png" alt="vs2005 pch1"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_pch2.png"><img src="images/vs2005_pch2.png" alt="vs2005 pch2"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_pch3.png"><img src="images/vs2005_pch3.png" alt="vs2005 pch3"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_pch4.png"><img src="images/vs2005_pch4.png" alt="vs2005 pch4"></a> </div> </div></div></td> </tr> </tbody> </table> </div> <div class="sect3"> <h4 id="install.building.static"><a class="anchor" href="#install.building.static"></a><a class="link" href="#install.building.static">2.2.2. Building pugixml as a standalone static library</a></h4> <div class="paragraph"> <p>It&#8217;s possible to compile pugixml as a standalone static library. This process depends on the method of building your application; pugixml distribution comes with project files for several popular IDEs/build systems. There are project files for Apple XCode, Code::Blocks, Codelite, Microsoft Visual Studio 2005, 2008, 2010+, and configuration scripts for CMake and premake4. You&#8217;re welcome to submit project files/build scripts for other software; see <a href="#overview.feedback">Feedback</a>.</p> </div> <div class="paragraph"> <p>There are two projects for each version of Microsoft Visual Studio: one for dynamically linked CRT, which has a name like <code>pugixml_vs2008.vcproj</code>, and another one for statically linked CRT, which has a name like <code>pugixml_vs2008_static.vcproj</code>. You should select the version that matches the CRT used in your application; the default option for new projects created by Microsoft Visual Studio is dynamically linked CRT, so unless you changed the defaults, you should use the version with dynamic CRT (i.e. <code>pugixml_vs2008.vcproj</code> for Microsoft Visual Studio 2008).</p> </div> <div class="paragraph"> <p>In addition to adding pugixml project to your workspace, you&#8217;ll have to make sure that your application links with pugixml library. If you&#8217;re using Microsoft Visual Studio 2005/2008, you can add a dependency from your application project to pugixml one. If you&#8217;re using Microsoft Visual Studio 2010+, you&#8217;ll have to add a reference to your application project instead. For other IDEs/systems, consult the relevant documentation.</p> </div> <table class="tableblock frame-none grid-all stretch"> <colgroup> <col style="width: 25%;"> <col style="width: 25%;"> <col style="width: 25%;"> <col style="width: 25%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top" colspan="2">Microsoft Visual Studio 2005/2008</th> <th class="tableblock halign-left valign-top" colspan="2">Microsoft Visual Studio 2010+</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_link1.png"><img src="images/vs2005_link1.png" alt="vs2005 link1"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2005_link2.png"><img src="images/vs2005_link2.png" alt="vs2005 link2"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2010_link1.png"><img src="images/vs2010_link1.png" alt="vs2010 link1"></a> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/vs2010_link2.png"><img src="images/vs2010_link2.png" alt="vs2010 link2"></a> </div> </div></div></td> </tr> </tbody> </table> </div> <div class="sect3"> <h4 id="install.building.shared"><a class="anchor" href="#install.building.shared"></a><a class="link" href="#install.building.shared">2.2.3. Building pugixml as a standalone shared library</a></h4> <div class="paragraph"> <p>It&#8217;s possible to compile pugixml as a standalone shared library. The process is usually similar to the static library approach; however, no preconfigured projects/scripts are included into pugixml distribution, so you&#8217;ll have to do it yourself. Generally, if you&#8217;re using GCC-based toolchain, the process does not differ from building any other library as DLL (adding -shared to compilation flags should suffice); if you&#8217;re using MSVC-based toolchain, you&#8217;ll have to explicitly mark exported symbols with a declspec attribute. You can do it by defining <a href="#PUGIXML_API">PUGIXML_API</a> macro, i.e. via <code>pugiconfig.hpp</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-cp">#ifdef _DLL</span> <span class="tok-w"> </span><span class="tok-cp">#define PUGIXML_API __declspec(dllexport)</span> <span class="tok-cp">#else</span> <span class="tok-w"> </span><span class="tok-cp">#define PUGIXML_API __declspec(dllimport)</span> <span class="tok-cp">#endif</span></code></pre> </div> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> If you&#8217;re using STL-related functions, you should use the shared runtime library to ensure that a single heap is used for STL allocations in your application and in pugixml; in MSVC, this means selecting the 'Multithreaded DLL' or 'Multithreaded Debug DLL' to 'Runtime library' property (<code>/MD</code> or <code>/MDd</code> linker switch). You should also make sure that your runtime library choice is consistent between different projects. </td> </tr> </table> </div> </div> <div class="sect3"> <h4 id="install.building.header"><a class="anchor" href="#install.building.header"></a><a class="link" href="#install.building.header">2.2.4. Using pugixml in header-only mode</a></h4> <div id="PUGIXML_HEADER_ONLY" class="paragraph"> <p>It&#8217;s possible to use pugixml in header-only mode. This means that all source code for pugixml will be included in every translation unit that includes <code>pugixml.hpp</code>. This is how most of Boost and STL libraries work.</p> </div> <div class="paragraph"> <p>Note that there are advantages and drawbacks of this approach. Header mode may improve tree traversal/modification performance (because many simple functions will be inlined), if your compiler toolchain does not support link-time optimization, or if you have it turned off (with link-time optimization the performance should be similar to non-header mode). However, since compiler now has to compile pugixml source once for each translation unit that includes it, compilation times may increase noticeably. If you want to use pugixml in header mode but do not need XPath support, you can consider disabling it by using <a href="#PUGIXML_NO_XPATH">PUGIXML_NO_XPATH</a> define to improve compilation time.</p> </div> <div class="paragraph"> <p>To enable header-only mode, you have to define <code>PUGIXML_HEADER_ONLY</code>. You can either do it in <code>pugiconfig.hpp</code>, or provide them via compiler command-line.</p> </div> <div class="paragraph"> <p>Note that it is safe to compile <code>pugixml.cpp</code> if <code>PUGIXML_HEADER_ONLY</code> is defined - so if you want to i.e. use header-only mode only in Release configuration, you can include pugixml.cpp in your project (see <a href="#install.building.embed">Building pugixml as a part of another static library/executable</a>), and conditionally enable header-only mode in <code>pugiconfig.hpp</code> like this:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-cp">#ifndef _DEBUG</span> <span class="tok-w"> </span><span class="tok-cp">#define PUGIXML_HEADER_ONLY</span> <span class="tok-cp">#endif</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="install.building.config"><a class="anchor" href="#install.building.config"></a><a class="link" href="#install.building.config">2.2.5. Additional configuration options</a></h4> <div class="paragraph"> <p>pugixml uses several defines to control the compilation process. There are two ways to define them: either put the needed definitions to <code>pugiconfig.hpp</code> (it has some examples that are commented out) or provide them via compiler command-line. Consistency is important: the definitions should match in all source files that include <code>pugixml.hpp</code> (including pugixml sources) throughout the application. Adding defines to <code>pugiconfig.hpp</code> lets you guarantee this, unless your macro definition is wrapped in preprocessor <code>#if</code>/<code>#ifdef</code> directive and this directive is not consistent. <code>pugiconfig.hpp</code> will never contain anything but comments, which means that when upgrading to a new version, you can safely leave your modified version intact.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_WCHAR_MODE"></a><code>PUGIXML_WCHAR_MODE</code> define toggles between UTF-8 style interface (the in-memory text encoding is assumed to be UTF-8, most functions use <code>char</code> as character type) and UTF-16/32 style interface (the in-memory text encoding is assumed to be UTF-16/32, depending on <code>wchar_t</code> size, most functions use <code>wchar_t</code> as character type). See <a href="#dom.unicode">Unicode interface</a> for more details.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_COMPACT"></a><code>PUGIXML_COMPACT</code> define activates a different internal representation of document storage that is much more memory efficient for documents with a lot of markup (i.e. nodes and attributes), but is slightly slower to parse and access. For details see <a href="#dom.memory.compact">Compact mode</a>.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_NO_XPATH"></a><code>PUGIXML_NO_XPATH</code> define disables XPath. Both XPath interfaces and XPath implementation are excluded from compilation. This option is provided in case you do not need XPath functionality and need to save code space.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_NO_STL"></a><code>PUGIXML_NO_STL</code> define disables use of STL in pugixml. The functions that operate on STL types are no longer present (i.e. load/save via iostream) if this macro is defined. This option is provided in case your target platform does not have a standard-compliant STL implementation.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_NO_EXCEPTIONS"></a><code>PUGIXML_NO_EXCEPTIONS</code> define disables use of exceptions in pugixml. This option is provided in case your target platform does not have exception handling capabilities.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_API"></a><code>PUGIXML_API</code>, <a id="PUGIXML_CLASS"></a><code>PUGIXML_CLASS</code> and <a id="PUGIXML_FUNCTION"></a><code>PUGIXML_FUNCTION</code> defines let you specify custom attributes (i.e. declspec or calling conventions) for pugixml classes and non-member functions. In absence of <code>PUGIXML_CLASS</code> or <code>PUGIXML_FUNCTION</code> definitions, <code>PUGIXML_API</code> definition is used instead. For example, to specify fixed calling convention, you can define <code>PUGIXML_FUNCTION</code> to i.e. <code>__fastcall</code>. Another example is DLL import/export attributes in MSVC (see <a href="#install.building.shared">Building pugixml as a standalone shared library</a>).</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> In that example <code>PUGIXML_API</code> is inconsistent between several source files; this is an exception to the consistency rule. </td> </tr> </table> </div> <div class="paragraph"> <p><a id="PUGIXML_MEMORY_PAGE_SIZE"></a><code>PUGIXML_MEMORY_PAGE_SIZE</code>, <a id="PUGIXML_MEMORY_OUTPUT_STACK"></a><code>PUGIXML_MEMORY_OUTPUT_STACK</code> and <a id="PUGIXML_MEMORY_XPATH_PAGE_SIZE"></a><code>PUGIXML_MEMORY_XPATH_PAGE_SIZE</code> can be used to customize certain important sizes to optimize memory usage for the application-specific patterns. For details see <a href="#dom.memory.tuning">Memory consumption tuning</a>.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_HAS_LONG_LONG"></a><code>PUGIXML_HAS_LONG_LONG</code> define enables support for <code>long long</code> type in pugixml. This define is automatically enabled if your platform is known to have <code>long long</code> support (i.e. has C&#43;&#43;11 support or uses a reasonably modern version of a known compiler); if pugixml does not recognize that your platform supports <code>long long</code> but in fact it does, you can enable the define manually.</p> </div> <div class="paragraph"> <p><a id="PUGIXML_HAS_STRING_VIEW"></a><code>PUGIXML_HAS_STRING_VIEW</code> define enables function overloads that accept <code>std::string_view</code> arguments. This define is automatically enabled if built targeting C&#43;&#43;17 or later; if pugixml does not recognize that your platform supports <code>std::string_view</code> but in fact it does, you can enable the define manually.</p> </div> </div> </div> <div class="sect2"> <h3 id="install.portability"><a class="anchor" href="#install.portability"></a><a class="link" href="#install.portability">2.3. Portability</a></h3> <div class="paragraph"> <p>pugixml is written in standard-compliant C&#43;&#43; with some compiler-specific workarounds where appropriate. pugixml is compatible with the C&#43;&#43;11 standard, but does not require C&#43;&#43;11 support. Each version is tested with a unit test suite with code coverage exceeding 99%.</p> </div> <div class="paragraph"> <p>pugixml runs on a variety of desktop platforms (including Microsoft Windows, Linux, FreeBSD, Apple MacOSX and Sun Solaris), game consoles (including Microsoft Xbox 360, Microsoft Xbox One, Nintendo Wii, Sony Playstation Portable and Sony Playstation 3) and mobile platforms (including Android, iOS, BlackBerry, Samsung bada and Microsoft Windows CE).</p> </div> <div class="paragraph"> <p>pugixml supports various architectures, such as x86/x86-64, PowerPC, ARM, MIPS and SPARC. In general it should run on any architecture since it does not use architecture-specific code and does not rely on features such as unaligned memory access.</p> </div> <div class="paragraph"> <p>pugixml can be compiled using any C++ compiler; it was tested with all versions of Microsoft Visual C&#43;&#43; from 6.0 up to 2015, GCC from 3.4 up to 5.2, Clang from 3.2 up to 3.7, as well as a variety of other compilers (e.g. Borland C&#43;&#43;, Digital Mars C&#43;&#43;, Intel C&#43;&#43;, Metrowerks CodeWarrior and PathScale). The code is written to avoid compilation warnings even on reasonably high warning levels.</p> </div> <div class="paragraph"> <p>Note that some platforms may have very bare-bones support of C++; in some cases you&#8217;ll have to use <code>PUGIXML_NO_STL</code> and/or <code>PUGIXML_NO_EXCEPTIONS</code> to compile without issues. This mostly applies to old game consoles and embedded systems.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="dom"><a class="anchor" href="#dom"></a><a class="link" href="#dom">3. Document object model</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml stores XML data in DOM-like way: the entire XML document (both document structure and element data) is stored in memory as a tree. The tree can be loaded from a character stream (file, string, C&#43;&#43; I/O stream), then traversed with the special API or XPath expressions. The whole tree is mutable: both node structure and node/attribute data can be changed at any time. Finally, the result of document transformations can be saved to a character stream (file, C&#43;&#43; I/O stream or custom transport).</p> </div> <div class="sect2"> <h3 id="dom.tree"><a class="anchor" href="#dom.tree"></a><a class="link" href="#dom.tree">3.1. Tree structure</a></h3> <div class="paragraph"> <p>The XML document is represented with a tree data structure. The root of the tree is the document itself, which corresponds to C&#43;&#43; type <a href="#xml_document">xml_document</a>. Document has one or more child nodes, which correspond to C&#43;&#43; type <a href="#xml_node">xml_node</a>. Nodes have different types; depending on a type, a node can have a collection of child nodes, a collection of attributes, which correspond to C&#43;&#43; type <a href="#xml_attribute">xml_attribute</a>, and some additional data (i.e. name).</p> </div> <div id="xml_node_type" class="paragraph"> <p>The tree nodes can be of one of the following types (which together form the enumeration <code>xml_node_type</code>):</p> </div> <div class="ulist"> <ul> <li> <p>Document node (<a id="node_document"></a><code>node_document</code>) - this is the root of the tree, which consists of several child nodes. This node corresponds to <a href="#xml_document">xml_document</a> class; note that <a href="#xml_document">xml_document</a> is a sub-class of <a href="#xml_node">xml_node</a>, so the entire node interface is also available. However, document node is special in several ways, which are covered below. There can be only one document node in the tree; document node does not have any XML representation. Document generally has one child element node (see <a id="xml_document::document_element"></a><code>document_element()</code>), although documents parsed from XML fragments (see <a id="parse_fragment"></a><code>parse_fragment</code>) can have more than one.</p> </li> <li> <p>Element/tag node (<a id="node_element"></a><code>node_element</code>) - this is the most common type of node, which represents XML elements. Element nodes have a name, a collection of attributes and a collection of child nodes (both of which may be empty). The attribute is a simple name/value pair. The example XML representation of element nodes is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;</span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-o">=</span><span class="tok-s">&quot;value&quot;</span><span class="tok-o">&gt;&lt;</span><span class="tok-n">child</span><span class="tok-o">/&gt;&lt;/</span><span class="tok-n">node</span><span class="tok-o">&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>There are two element nodes here: one has name <code>"node"</code>, single attribute <code>"attr"</code> and single child <code>"child"</code>, another has name <code>"child"</code> and does not have any attributes or child nodes.</p> </div> </li> <li> <p>Plain character data nodes (<a id="node_pcdata"></a><code>node_pcdata</code>) represent plain text in XML. PCDATA nodes have a value, but do not have a name or children/attributes. Note that <strong>plain character data is not a part of the element node but instead has its own node</strong>; an element node can have several child PCDATA nodes. The example XML representation of text nodes is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;</span><span class="tok-n">node</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">text1</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-n">child</span><span class="tok-o">/&gt;</span><span class="tok-w"> </span><span class="tok-n">text2</span><span class="tok-w"> </span><span class="tok-o">&lt;/</span><span class="tok-n">node</span><span class="tok-o">&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>Here <code>"node"</code> element has three children, two of which are PCDATA nodes with values <code>" text1 "</code> and <code>" text2 "</code>.</p> </div> </li> <li> <p>Character data nodes (<a id="node_cdata"></a><code>node_cdata</code>) represent text in XML that is quoted in a special way. CDATA nodes do not differ from PCDATA nodes except in XML representation - the above text example looks like this with CDATA:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;</span><span class="tok-n">node</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-o">&lt;!</span><span class="tok-p">[</span><span class="tok-n">CDATA</span><span class="tok-p">[</span><span class="tok-n">text1</span><span class="tok-p">]]</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-n">child</span><span class="tok-o">/&gt;</span><span class="tok-w"> </span><span class="tok-o">&lt;!</span><span class="tok-p">[</span><span class="tok-n">CDATA</span><span class="tok-p">[</span><span class="tok-n">text2</span><span class="tok-p">]]</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-o">&lt;/</span><span class="tok-n">node</span><span class="tok-o">&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>CDATA nodes make it easy to include non-escaped <code>&lt;</code>, <code>&amp;</code> and <code>&gt;</code> characters in plain text. CDATA value can not contain the character sequence <code>]]&gt;</code>, since it is used to determine the end of node contents.</p> </div> </li> <li> <p>Comment nodes (<a id="node_comment"></a><code>node_comment</code>) represent comments in XML. Comment nodes have a value, but do not have a name or children/attributes. The example XML representation of a comment node is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;!--</span><span class="tok-w"> </span><span class="tok-n">comment</span><span class="tok-w"> </span><span class="tok-n">text</span><span class="tok-w"> </span><span class="tok-o">--&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>Here the comment node has value <code>"comment text"</code>. By default comment nodes are treated as non-essential part of XML markup and are not loaded during XML parsing. You can override this behavior with <a href="#parse_comments">parse_comments</a> flag.</p> </div> </li> <li> <p>Processing instruction node (<a id="node_pi"></a><code>node_pi</code>) represent processing instructions (PI) in XML. PI nodes have a name and an optional value, but do not have children/attributes. The example XML representation of a PI node is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;?</span><span class="tok-n">name</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-o">?&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>Here the name (also called PI target) is <code>"name"</code>, and the value is <code>"value"</code>. By default PI nodes are treated as non-essential part of XML markup and are not loaded during XML parsing. You can override this behavior with <a href="#parse_pi">parse_pi</a> flag.</p> </div> </li> <li> <p>Declaration node (<a id="node_declaration"></a><code>node_declaration</code>) represents document declarations in XML. Declaration nodes have a name (<code>"xml"</code>) and an optional collection of attributes, but do not have value or children. There can be only one declaration node in a document; moreover, it should be the topmost node (its parent should be the document). The example XML representation of a declaration node is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;?</span><span class="tok-n">xml</span><span class="tok-w"> </span><span class="tok-n">version</span><span class="tok-o">=</span><span class="tok-s">&quot;1.0&quot;</span><span class="tok-o">?&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>Here the node has name <code>"xml"</code> and a single attribute with name <code>"version"</code> and value <code>"1.0"</code>. By default declaration nodes are treated as non-essential part of XML markup and are not loaded during XML parsing. You can override this behavior with <a href="#parse_declaration">parse_declaration</a> flag. Also, by default a dummy declaration is output when XML document is saved unless there is already a declaration in the document; you can disable this with <a href="#format_no_declaration">format_no_declaration</a> flag.</p> </div> </li> <li> <p>Document type declaration node (<a id="node_doctype"></a><code>node_doctype</code>) represents document type declarations in XML. Document type declaration nodes have a value, which corresponds to the entire document type contents; no additional nodes are created for inner elements like <code>&lt;!ENTITY&gt;</code>. There can be only one document type declaration node in a document; moreover, it should be the topmost node (its parent should be the document). The example XML representation of a document type declaration node is as follows:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-o">&lt;!</span><span class="tok-n">DOCTYPE</span><span class="tok-w"> </span><span class="tok-n">greeting</span><span class="tok-w"> </span><span class="tok-p">[</span><span class="tok-w"> </span><span class="tok-o">&lt;!</span><span class="tok-n">ELEMENT</span><span class="tok-w"> </span><span class="tok-n">greeting</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-err">#</span><span class="tok-n">PCDATA</span><span class="tok-p">)</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-p">]</span><span class="tok-o">&gt;</span></code></pre> </div> </div> <div class="paragraph"> <p>Here the node has value <code>"greeting [ &lt;!ELEMENT greeting (#PCDATA)&gt; ]"</code>. By default document type declaration nodes are treated as non-essential part of XML markup and are not loaded during XML parsing. You can override this behavior with <a href="#parse_doctype">parse_doctype</a> flag.</p> </div> </li> </ul> </div> <div class="paragraph"> <p>Finally, here is a complete example of XML document and the corresponding tree representation (<a href="samples/tree.xml" class="bare">samples/tree.xml</a>):</p> </div> <table class="tableblock frame-none grid-all stretch"> <colgroup> <col style="width: 50%;"> <col style="width: 50%;"> </colgroup> <tbody> <tr> <td class="tableblock halign-left valign-top"><div class="content"><div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span> <span class="tok-nt">&lt;mesh</span><span class="tok-w"> </span><span class="tok-na">name=</span><span class="tok-s">&quot;mesh_root&quot;</span><span class="tok-nt">&gt;</span> <span class="tok-w"> </span><span class="tok-cm">&lt;!-- here is a mesh node --&gt;</span> <span class="tok-w"> </span>some<span class="tok-w"> </span>text <span class="tok-w"> </span><span class="tok-cp">&lt;![CDATA[someothertext]]&gt;</span> <span class="tok-w"> </span>some<span class="tok-w"> </span>more<span class="tok-w"> </span>text <span class="tok-w"> </span><span class="tok-nt">&lt;node</span><span class="tok-w"> </span><span class="tok-na">attr1=</span><span class="tok-s">&quot;value1&quot;</span><span class="tok-w"> </span><span class="tok-na">attr2=</span><span class="tok-s">&quot;value2&quot;</span><span class="tok-w"> </span><span class="tok-nt">/&gt;</span> <span class="tok-w"> </span><span class="tok-nt">&lt;node</span><span class="tok-w"> </span><span class="tok-na">attr1=</span><span class="tok-s">&quot;value2&quot;</span><span class="tok-nt">&gt;</span> <span class="tok-w"> </span><span class="tok-nt">&lt;innernode/&gt;</span> <span class="tok-w"> </span><span class="tok-nt">&lt;/node&gt;</span> <span class="tok-nt">&lt;/mesh&gt;</span> <span class="tok-cp">&lt;?include somedata?&gt;</span></code></pre> </div> </div></div></td> <td class="tableblock halign-left valign-top"><div class="content"><div class="imageblock"> <div class="content"> <a class="image" href="images/dom_tree.png"><img src="images/dom_tree.png" alt="dom tree"></a> </div> </div></div></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="dom.cpp"><a class="anchor" href="#dom.cpp"></a><a class="link" href="#dom.cpp">3.2. C&#43;&#43; interface</a></h3> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> All pugixml classes and functions are located in the <code>pugi</code> namespace; you have to either use explicit name qualification (i.e. <code>pugi::xml_node</code>), or to gain access to relevant symbols via <code>using</code> directive (i.e. <code>using pugi::xml_node;</code> or <code>using namespace pugi;</code>). The namespace will be omitted from all declarations in this documentation hereafter; all code examples will use fully qualified names. </td> </tr> </table> </div> <div class="paragraph"> <p>Despite the fact that there are several node types, there are only three C&#43;&#43; classes representing the tree (<code>xml_document</code>, <code>xml_node</code>, <code>xml_attribute</code>); some operations on <code>xml_node</code> are only valid for certain node types. The classes are described below.</p> </div> <div class="paragraph"> <p><a id="xml_document"></a><a id="xml_document::document_element"></a> <code>xml_document</code> is the owner of the entire document structure; it is a non-copyable class. The interface of <code>xml_document</code> consists of loading functions (see <a href="#loading">Loading document</a>), saving functions (see <a href="#saving">Saving document</a>) and the entire interface of <code>xml_node</code>, which allows for document inspection and/or modification. Note that while <code>xml_document</code> is a sub-class of <code>xml_node</code>, <code>xml_node</code> is not a polymorphic type; the inheritance is present only to simplify usage. Alternatively you can use the <code>document_element</code> function to get the element node that&#8217;s the immediate child of the document.</p> </div> <div class="paragraph"> <p><a id="xml_document::ctor"></a><a id="xml_document::dtor"></a><a id="xml_document::reset"></a> Default constructor of <code>xml_document</code> initializes the document to the tree with only a root node (document node). You can then populate it with data using either tree modification functions or loading functions; all loading functions destroy the previous tree with all occupied memory, which puts existing node/attribute handles for this document to invalid state. If you want to destroy the previous tree, you can use the <code>xml_document::reset</code> function; it destroys the tree and replaces it with either an empty one or a copy of the specified document. Destructor of <code>xml_document</code> also destroys the tree, thus the lifetime of the document object should exceed the lifetimes of any node/attribute handles that point to the tree.</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> While technically node/attribute handles can be alive when the tree they&#8217;re referring to is destroyed, calling any member function for these handles results in undefined behavior. Thus it is recommended to make sure that the document is destroyed only after all references to its nodes/attributes are destroyed. </td> </tr> </table> </div> <div class="paragraph"> <p><a id="xml_node"></a><a id="xml_node::type"></a> <code>xml_node</code> is the handle to document node; it can point to any node in the document, including the document node itself. There is a common interface for nodes of all types; the actual <a href="#xml_node_type">node type</a> can be queried via the <code>xml_node::type()</code> method. Note that <code>xml_node</code> is only a handle to the actual node, not the node itself - you can have several <code>xml_node</code> handles pointing to the same underlying object. Destroying <code>xml_node</code> handle does not destroy the node and does not remove it from the tree. The size of <code>xml_node</code> is equal to that of a pointer, so it is nothing more than a lightweight wrapper around a pointer; you can safely pass or return <code>xml_node</code> objects by value without additional overhead.</p> </div> <div id="node_null" class="paragraph"> <p>There is a special value of <code>xml_node</code> type, known as null node or empty node (such nodes have type <code>node_null</code>). It does not correspond to any node in any document, and thus resembles null pointer. However, all operations are defined on empty nodes; generally the operations don&#8217;t do anything and return empty nodes/attributes or empty strings as their result (see documentation for specific functions for more detailed information). This is useful for chaining calls; i.e. you can get the grandparent of a node like so: <code>node.parent().parent()</code>; if a node is a null node or it does not have a parent, the first <code>parent()</code> call returns null node; the second <code>parent()</code> call then also returns null node, which makes error handling easier.</p> </div> <div id="xml_attribute" class="paragraph"> <p><code>xml_attribute</code> is the handle to an XML attribute; it has the same semantics as <code>xml_node</code>, i.e. there can be several <code>xml_attribute</code> handles pointing to the same underlying object and there is a special null attribute value, which propagates to function results.</p> </div> <div class="paragraph"> <p><a id="xml_attribute::ctor"></a><a id="xml_node::ctor"></a> Both <code>xml_node</code> and <code>xml_attribute</code> have the default constructor which initializes them to null objects.</p> </div> <div class="paragraph"> <p><a id="xml_attribute::comparison"></a><a id="xml_node::comparison"></a> <code>xml_node</code> and <code>xml_attribute</code> try to behave like pointers, that is, they can be compared with other objects of the same type, making it possible to use them as keys in associative containers. All handles to the same underlying object are equal, and any two handles to different underlying objects are not equal. Null handles only compare as equal to null handles. The result of relational comparison can not be reliably determined from the order of nodes in file or in any other way. Do not use relational comparison operators except for search optimization (i.e. associative container keys).</p> </div> <div class="paragraph"> <p><a id="xml_attribute::hash_value"></a><a id="xml_node::hash_value"></a> If you want to use <code>xml_node</code> or <code>xml_attribute</code> objects as keys in hash-based associative containers, you can use the <code>hash_value</code> member functions. They return the hash values that are guaranteed to be the same for all handles to the same underlying object. The hash value for null handles is 0. Note that hash value does not depend on the content of the node, only on the location of the underlying structure in memory - this means that loading the same document twice will likely produce different hash values, and copying the node will not preserve the hash.</p> </div> <div class="paragraph"> <p><a id="xml_attribute::unspecified_bool_type"></a><a id="xml_node::unspecified_bool_type"></a><a id="xml_attribute::empty"></a><a id="xml_node::empty"></a> Finally handles can be implicitly cast to boolean-like objects, so that you can test if the node/attribute is empty with the following code: <code>if (node) { &#8230;&#8203; }</code> or <code>if (!node) { &#8230;&#8203; } else { &#8230;&#8203; }</code>. Alternatively you can check if a given <code>xml_node</code>/<code>xml_attribute</code> handle is null by calling the following methods:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::empty</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::empty</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Nodes and attributes do not exist without a document tree, so you can&#8217;t create them without adding them to some document. Once underlying node/attribute objects are destroyed, the handles to those objects become invalid. While this means that destruction of the entire tree invalidates all node/attribute handles, it also means that destroying a subtree (by calling <a href="#xml_node::remove_child">xml_node::remove_child</a>) or removing an attribute invalidates the corresponding handles. There is no way to check handle validity; you have to ensure correctness through external mechanisms.</p> </div> </div> <div class="sect2"> <h3 id="dom.unicode"><a class="anchor" href="#dom.unicode"></a><a class="link" href="#dom.unicode">3.3. Unicode interface</a></h3> <div class="paragraph"> <p>There are two choices of interface and internal representation when configuring pugixml: you can either choose the UTF-8 (also called char) interface or UTF-16/32 (also called wchar_t) one. The choice is controlled via <a href="#PUGIXML_WCHAR_MODE">PUGIXML_WCHAR_MODE</a> define; you can set it via <code>pugiconfig.hpp</code> or via preprocessor options, as discussed in <a href="#install.building.config">Additional configuration options</a>. If this define is set, the wchar_t interface is used; otherwise (by default) the char interface is used. The exact wide character encoding is assumed to be either UTF-16 or UTF-32 and is determined based on the size of <code>wchar_t</code> type.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> If the size of <code>wchar_t</code> is 2, pugixml assumes UTF-16 encoding instead of UCS-2, which means that some characters are represented as two code points. </td> </tr> </table> </div> <div class="paragraph"> <p>All tree functions that work with strings work with either C-style null terminated strings or STL strings of the selected character type. For example, node name accessors look like this in char mode:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>and like this in wchar_t mode:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="char_t"></a><a id="string_t"></a><a id="string_view_t"></a> There is a special type, <code>pugi::char_t</code>, that is defined as the character type and depends on the library configuration; it will be also used in the documentation hereafter. There is also a type <code>pugi::string_t</code>, which is defined as the STL string of the character type; it corresponds to <code>std::string</code> in char mode and to <code>std::wstring</code> in wchar_t mode. Similarly, <code>string_view_t</code> is defined to be <code>std::basic_string_view&lt;char_t&gt;</code>. Overloads for <code>string_view_t</code> are only available when building for C++17 or later (see <code>PUGIXML_HAS_STRING_VIEW</code>).</p> </div> <div class="paragraph"> <p>In addition to the interface, the internal implementation changes to store XML data as <code>pugi::char_t</code>; this means that these two modes have different memory usage characteristics - generally UTF-8 mode is more memory and performance efficient, especially if <code>sizeof(wchar_t)</code> is 4. The conversion to <code>pugi::char_t</code> upon document loading and from <code>pugi::char_t</code> upon document saving happen automatically, which also carries minor performance penalty. The general advice however is to select the character mode based on usage scenario, i.e. if UTF-8 is inconvenient to process and most of your XML data is non-ASCII, wchar_t mode is probably a better choice.</p> </div> <div class="paragraph"> <p><a id="as_utf8"></a><a id="as_wide"></a> There are cases when you&#8217;ll have to convert string data between UTF-8 and wchar_t encodings; the following helper functions are provided for such purposes:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><span class="tok-nf">as_utf8</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-w"> </span><span class="tok-nf">as_wide</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Both functions accept a null-terminated string as an argument <code>str</code>, and return the converted string. <code>as_utf8</code> performs conversion from UTF-16/32 to UTF-8; <code>as_wide</code> performs conversion from UTF-8 to UTF-16/32. Invalid UTF sequences are silently discarded upon conversion. <code>str</code> has to be a valid string; passing null pointer results in undefined behavior. There are also two overloads with the same semantics which accept a string as an argument:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><span class="tok-nf">as_utf8</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-w"> </span><span class="tok-nf">as_wide</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> <div class="paragraph"> <p>Most examples in this documentation assume char interface and therefore will not compile with <a href="#PUGIXML_WCHAR_MODE">PUGIXML_WCHAR_MODE</a>. This is done to simplify the documentation; usually the only changes you&#8217;ll have to make is to pass <code>wchar_t</code> string literals, i.e. instead of</p> </div> <div class="paragraph"> <p><code>xml_node node = doc.child("bookstore").find_child_by_attribute("book", "id", "12345");</code></p> </div> <div class="paragraph"> <p>you&#8217;ll have to use</p> </div> <div class="paragraph"> <p><code>xml_node node = doc.child(L"bookstore").find_child_by_attribute(L"book", L"id", L"12345");</code></p> </div> </td> </tr> </table> </div> </div> <div class="sect2"> <h3 id="dom.thread"><a class="anchor" href="#dom.thread"></a><a class="link" href="#dom.thread">3.4. Thread-safety guarantees</a></h3> <div class="paragraph"> <p>Almost all functions in pugixml have the following thread-safety guarantees:</p> </div> <div class="ulist"> <ul> <li> <p>it is safe to call free (non-member) functions from multiple threads</p> </li> <li> <p>it is safe to perform concurrent read-only accesses to the same tree (all constant member functions do not modify the tree)</p> </li> <li> <p>it is safe to perform concurrent read/write accesses on multiple trees, as long as each tree is only accessed from a single thread at a time</p> </li> </ul> </div> <div class="paragraph"> <p>Concurrent read/write access to a single tree requires synchronization, for example via a reader-writer lock. Modification includes altering document structure and altering individual node/attribute data, i.e. changing names/values.</p> </div> <div class="paragraph"> <p>The only exception is <a href="#set_memory_management_functions">set_memory_management_functions</a>; it modifies global variables and as such is not thread-safe. Its usage policy has more restrictions, see <a href="#dom.memory.custom">Custom memory allocation/deallocation functions</a>.</p> </div> </div> <div class="sect2"> <h3 id="dom.exception"><a class="anchor" href="#dom.exception"></a><a class="link" href="#dom.exception">3.5. Exception guarantees</a></h3> <div class="paragraph"> <p>With the exception of XPath, pugixml itself does not throw any exceptions. Additionally, most pugixml functions have a no-throw exception guarantee.</p> </div> <div class="paragraph"> <p>This is not applicable to functions that operate on STL strings or IOstreams; such functions have either strong guarantee (functions that operate on strings) or basic guarantee (functions that operate on streams). Also functions that call user-defined callbacks (i.e. <a href="#xml_node::traverse">xml_node::traverse</a> or <a href="#xml_node::find_node">xml_node::find_node</a>) do not provide any exception guarantees beyond the ones provided by the callback.</p> </div> <div class="paragraph"> <p>If exception handling is not disabled with <a href="#PUGIXML_NO_EXCEPTIONS">PUGIXML_NO_EXCEPTIONS</a> define, XPath functions may throw <a href="#xpath_exception">xpath_exception</a> on parsing errors; also, XPath functions may throw <code>std::bad_alloc</code> in low memory conditions. Still, XPath functions provide strong exception guarantee.</p> </div> </div> <div class="sect2"> <h3 id="dom.memory"><a class="anchor" href="#dom.memory"></a><a class="link" href="#dom.memory">3.6. Memory management</a></h3> <div class="paragraph"> <p>pugixml requests the memory needed for document storage in big chunks, and allocates document data inside those chunks. This section discusses replacing functions used for chunk allocation and internal memory management implementation.</p> </div> <div class="sect3"> <h4 id="dom.memory.custom"><a class="anchor" href="#dom.memory.custom"></a><a class="link" href="#dom.memory.custom">3.6.1. Custom memory allocation/deallocation functions</a></h4> <div class="paragraph"> <p><a id="allocation_function"></a><a id="deallocation_function"></a> All memory for tree structure, tree data and XPath objects is allocated via globally specified functions, which default to malloc/free. You can set your own allocation functions with set_memory_management function. The function interfaces are the same as that of malloc/free:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">*</span><span class="tok-n">allocation_function</span><span class="tok-p">)(</span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">*</span><span class="tok-n">deallocation_function</span><span class="tok-p">)(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">ptr</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="set_memory_management_functions"></a><a id="get_memory_allocation_function"></a><a id="get_memory_deallocation_function"></a> You can use the following accessor functions to change or get current memory management functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-nf">set_memory_management_functions</span><span class="tok-p">(</span><span class="tok-n">allocation_function</span><span class="tok-w"> </span><span class="tok-n">allocate</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">deallocation_function</span><span class="tok-w"> </span><span class="tok-n">deallocate</span><span class="tok-p">);</span> <span class="tok-n">allocation_function</span><span class="tok-w"> </span><span class="tok-nf">get_memory_allocation_function</span><span class="tok-p">();</span> <span class="tok-n">deallocation_function</span><span class="tok-w"> </span><span class="tok-nf">get_memory_deallocation_function</span><span class="tok-p">();</span></code></pre> </div> </div> <div class="paragraph"> <p>Allocation function is called with the size (in bytes) as an argument and should return a pointer to a memory block with alignment that is suitable for storage of primitive types (usually a maximum of <code>void*</code> and <code>double</code> types alignment is sufficient) and size that is greater than or equal to the requested one. If the allocation fails, the function has to either return null pointer or to throw an exception.</p> </div> <div class="paragraph"> <p>Deallocation function is called with the pointer that was returned by some call to allocation function; it is never called with a null pointer. If memory management functions are not thread-safe, library thread safety is not guaranteed.</p> </div> <div class="paragraph"> <p>This is a simple example of custom memory management (<a href="samples/custom_memory_management.cpp" class="bare">samples/custom_memory_management.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">custom_allocate</span><span class="tok-p">(</span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-k">new</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">nothrow</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-p">[</span><span class="tok-n">size</span><span class="tok-p">];</span> <span class="tok-p">}</span> <span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-nf">custom_deallocate</span><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">ptr</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">delete</span><span class="tok-p">[]</span><span class="tok-w"> </span><span class="tok-k">static_cast</span><span class="tok-o">&lt;</span><span class="tok-kt">char</span><span class="tok-o">*&gt;</span><span class="tok-p">(</span><span class="tok-n">ptr</span><span class="tok-p">);</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">set_memory_management_functions</span><span class="tok-p">(</span><span class="tok-n">custom_allocate</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">custom_deallocate</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>When setting new memory management functions, care must be taken to make sure that there are no live pugixml objects. Otherwise when the objects are destroyed, the new deallocation function will be called with the memory obtained by the old allocation function, resulting in undefined behavior.</p> </div> </div> <div class="sect3"> <h4 id="dom.memory.tuning"><a class="anchor" href="#dom.memory.tuning"></a><a class="link" href="#dom.memory.tuning">3.6.2. Memory consumption tuning</a></h4> <div class="paragraph"> <p>There are several important buffering optimizations in pugixml that rely on predefined constants. These constants have default values that were tuned for common usage patterns; for some applications, changing these constants might improve memory consumption or increase performance. Changing these constants is not recommended unless their default values result in visible problems.</p> </div> <div class="paragraph"> <p>These constants can be tuned via configuration defines, as discussed in <a href="#install.building.config">Additional configuration options</a>; it is recommended to set them in <code>pugiconfig.hpp</code>.</p> </div> <div class="ulist"> <ul> <li> <p><code>PUGIXML_MEMORY_PAGE_SIZE</code> controls the page size for document memory allocation. Memory for node/attribute objects is allocated in pages of the specified size. The default size is 32 Kb; for some applications the size is too large (i.e. embedded systems with little heap space or applications that keep lots of XML documents in memory). A minimum size of 1 Kb is recommended.</p> </li> <li> <p><code>PUGIXML_MEMORY_OUTPUT_STACK</code> controls the cumulative stack space required to output the node. Any output operation (i.e. saving a subtree to file) uses an internal buffering scheme for performance reasons. The default size is 10 Kb; if you&#8217;re using node output from threads with little stack space, decreasing this value can prevent stack overflows. A minimum size of 1 Kb is recommended.</p> </li> <li> <p><code>PUGIXML_MEMORY_XPATH_PAGE_SIZE</code> controls the page size for XPath memory allocation. Memory for XPath query objects as well as internal memory for XPath evaluation is allocated in pages of the specified size. The default size is 4 Kb; if you have a lot of resident XPath query objects, you might need to decrease the size to improve memory consumption. A minimum size of 256 bytes is recommended.</p> </li> </ul> </div> </div> <div class="sect3"> <h4 id="dom.memory.internals"><a class="anchor" href="#dom.memory.internals"></a><a class="link" href="#dom.memory.internals">3.6.3. Document memory management internals</a></h4> <div class="paragraph"> <p>Constructing a document object using the default constructor does not result in any allocations; document node is stored inside the <a href="#xml_document">xml_document</a> object.</p> </div> <div class="paragraph"> <p>When the document is loaded from file/buffer, unless an inplace loading function is used (see <a href="#loading.memory">Loading document from memory</a>), a complete copy of character stream is made; all names/values of nodes and attributes are allocated in this buffer. This buffer is allocated via a single large allocation and is only freed when document memory is reclaimed (i.e. if the <a href="#xml_document">xml_document</a> object is destroyed or if another document is loaded in the same object). Also when loading from file or stream, an additional large allocation may be performed if encoding conversion is required; a temporary buffer is allocated, and it is freed before load function returns.</p> </div> <div class="paragraph"> <p>All additional memory, such as memory for document structure (node/attribute objects) and memory for node/attribute names/values is allocated in pages on the order of 32 Kb; actual objects are allocated inside the pages using a memory management scheme optimized for fast allocation/deallocation of many small objects. Because of the scheme specifics, the pages are only destroyed if all objects inside them are destroyed; also, generally destroying an object does not mean that subsequent object creation will reuse the same memory. This means that it is possible to devise a usage scheme which will lead to higher memory usage than expected; one example is adding a lot of nodes, and them removing all even numbered ones; not a single page is reclaimed in the process. However this is an example specifically crafted to produce unsatisfying behavior; in all practical usage scenarios the memory consumption is less than that of a general-purpose allocator because allocation meta-data is very small in size.</p> </div> </div> <div class="sect3"> <h4 id="dom.memory.compact"><a class="anchor" href="#dom.memory.compact"></a><a class="link" href="#dom.memory.compact">3.6.4. Compact mode</a></h4> <div class="paragraph"> <p>By default nodes and attributes are optimized for efficiency of access. This can cause them to take a significant amount of memory - for documents with a lot of nodes and not a lot of contents (short attribute values/node text), and depending on the pointer size, the document structure can take noticeably more memory than the document itself (e.g. on a 64-bit platform in UTF-8 mode a markup-heavy document with the file size of 2.1 Mb can use 2.1 Mb for document buffer and 8.3 Mb for document structure).</p> </div> <div class="paragraph"> <p>If you are processing big documents or your platform is memory constrained and you&#8217;re willing to sacrifice a bit of performance for memory, you can compile pugixml with <code>PUGIXML_COMPACT</code> define which will activate compact mode. Compact mode uses a different representation of the document structure that assumes locality of reference between nodes and attributes to optimize memory usage. As a result you get significantly smaller node/attribute objects; usually most objects in most documents don&#8217;t require additional storage, but in the worst case - if assumptions about locality of reference don&#8217;t hold - additional memory will be allocated to store the extra data required.</p> </div> <div class="paragraph"> <p>The compact storage supports all existing operations - including tree modification - with the same amortized complexity (that is, all basic document manipulations are still O(1) on average). The operations are slightly slower; you can usually expect 10-50% slowdown in terms of processing time unless your processing was memory-bound.</p> </div> <div class="paragraph"> <p>On 32-bit architectures document structure in compact mode is typically reduced by around 2.5x; on 64-bit architectures the ratio is around 5x. Thus for big markup-heavy documents compact mode can make the difference between the processing of a multi-gigabyte document running completely from RAM vs requiring swapping to disk. Even if the document fits into memory, compact storage can use CPU caches more efficiently by taking less space and causing less cache/TLB misses.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="loading"><a class="anchor" href="#loading"></a><a class="link" href="#loading">4. Loading document</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml provides several functions for loading XML data from various places - files, C&#43;&#43; iostreams, memory buffers. All functions use an extremely fast non-validating parser. This parser is not fully W3C conformant - it can load any valid XML document, but does not perform some well-formedness checks. While considerable effort is made to reject invalid XML documents, some validation is not performed for performance reasons. Also some XML transformations (i.e. EOL handling or attribute value normalization) can impact parsing speed and thus can be disabled. However for vast majority of XML documents there is no performance difference between different parsing options. Parsing options also control whether certain XML nodes are parsed; see <a href="#loading.options">Parsing options</a> for more information.</p> </div> <div class="paragraph"> <p>XML data is always converted to internal character format (see <a href="#dom.unicode">Unicode interface</a>) before parsing. pugixml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it&#8217;s a strict subset of UTF-16) as well as some non-Unicode encodings (Latin-1) and handles all encoding conversions automatically. Unless explicit encoding is specified, loading functions perform automatic encoding detection based on source XML data, so in most cases you do not have to specify document encoding. Encoding conversion is described in more detail in <a href="#loading.encoding">Encodings</a>.</p> </div> <div class="sect2"> <h3 id="loading.file"><a class="anchor" href="#loading.file"></a><a class="link" href="#loading.file">4.1. Loading document from file</a></h3> <div class="paragraph"> <p><a id="xml_document::load_file"></a><a id="xml_document::load_file_wide"></a> The most common source of XML data is files; pugixml provides dedicated functions for loading an XML document from file:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_file</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_file</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions accept the file path as its first argument, and also two optional arguments, which specify parsing options (see <a href="#loading.options">Parsing options</a>) and input data encoding (see <a href="#loading.encoding">Encodings</a>). The path has the target operating system format, so it can be a relative or absolute one, it should have the delimiters of the target system, it should have the exact case if the target file system is case-sensitive, etc.</p> </div> <div class="paragraph"> <p>File path is passed to the system file opening function as is in case of the first function (which accepts <code>const char* path</code>); the second function either uses a special file opening function if it is provided by the runtime library or converts the path to UTF-8 and uses the system file opening function.</p> </div> <div class="paragraph"> <p><code>load_file</code> destroys the existing document tree and then tries to load the new tree from the specified file. The result of the operation is returned in an <a href="#xml_parse_result">xml_parse_result</a> object; this object contains the operation status and the related information (i.e. last successfully parsed position in the input file, if parsing fails). See <a href="#loading.errors">Handling parsing errors</a> for error handling details.</p> </div> <div class="paragraph"> <p>This is an example of loading XML document from file (<a href="samples/load_file.cpp" class="bare">samples/load_file.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_file</span><span class="tok-p">(</span><span class="tok-s">&quot;tree.xml&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Load result: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, mesh name: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;mesh&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="loading.memory"><a class="anchor" href="#loading.memory"></a><a class="link" href="#loading.memory">4.2. Loading document from memory</a></h3> <div class="paragraph"> <p><a id="xml_document::load_buffer"></a><a id="xml_document::load_buffer_inplace"></a><a id="xml_document::load_buffer_inplace_own"></a> Sometimes XML data should be loaded from some other source than a file, i.e. HTTP URL; also you may want to load XML data from file using non-standard functions, i.e. to use your virtual file system facilities or to load XML from GZip-compressed files. All these scenarios require loading document from memory. First you should prepare a contiguous memory block with all XML data; then you have to invoke one of buffer loading functions. These functions will handle the necessary encoding conversions, if any, and then will parse the data into the corresponding XML tree. There are several buffer loading functions, which differ in the behavior and thus in performance/memory usage:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_buffer</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_buffer_inplace</span><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_buffer_inplace_own</span><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>All functions accept the buffer which is represented by a pointer to XML data, <code>contents</code>, and data size in bytes. Also there are two optional arguments, which specify parsing options (see <a href="#loading.options">Parsing options</a>) and input data encoding (see <a href="#loading.encoding">Encodings</a>). The buffer does not have to be zero-terminated.</p> </div> <div class="paragraph"> <p><code>load_buffer</code> function works with immutable buffer - it does not ever modify the buffer. Because of this restriction it has to create a private buffer and copy XML data to it before parsing (applying encoding conversions if necessary). This copy operation carries a performance penalty, so inplace functions are provided - <code>load_buffer_inplace</code> and <code>load_buffer_inplace_own</code> store the document data in the buffer, modifying it in the process. In order for the document to stay valid, you have to make sure that the buffer&#8217;s lifetime exceeds that of the tree if you&#8217;re using inplace functions. In addition to that, <code>load_buffer_inplace</code> does not assume ownership of the buffer, so you&#8217;ll have to destroy it yourself; <code>load_buffer_inplace_own</code> assumes ownership of the buffer and destroys it once it is not needed. This means that if you&#8217;re using <code>load_buffer_inplace_own</code>, you have to allocate memory with pugixml allocation function (you can get it via <a href="#get_memory_allocation_function">get_memory_allocation_function</a>).</p> </div> <div class="paragraph"> <p>The best way from the performance/memory point of view is to load document using <code>load_buffer_inplace_own</code>; this function has maximum control of the buffer with XML data so it is able to avoid redundant copies and reduce peak memory usage while parsing. This is the recommended function if you have to load the document from memory and performance is critical.</p> </div> <div id="xml_document::load_string" class="paragraph"> <p>There is also a simple helper function for cases when you want to load the XML document from null-terminated character string:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load_string</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>It is equivalent to calling <code>load_buffer</code> with <code>size</code> being either <code>strlen(contents)</code> or <code>wcslen(contents) * sizeof(wchar_t)</code>, depending on the character type. This function assumes native encoding for input data, so it does not do any encoding conversion. In general, this function is fine for loading small documents from string literals, but has more overhead and less functionality than the buffer loading functions.</p> </div> <div class="paragraph"> <p>This is an example of loading XML document from memory using different functions (<a href="samples/load_memory.cpp" class="bare">samples/load_memory.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-p">[]</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&lt;mesh name=&#39;sphere&#39;&gt;&lt;bounds&gt;0 0 1 1&lt;/bounds&gt;&lt;/mesh&gt;&quot;</span><span class="tok-p">;</span> <span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-k">sizeof</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// You can use load_buffer to load document from immutable memory block:</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_buffer</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// You can use load_buffer_inplace to load document from mutable memory block; the block&#39;s lifetime must exceed that of document</span> <span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-k">new</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-p">[</span><span class="tok-n">size</span><span class="tok-p">];</span> <span class="tok-n">memcpy</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-c1">// The block can be allocated by any method; the block is modified during parsing</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_buffer_inplace</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-c1">// You have to destroy the block yourself after the document is no longer used</span> <span class="tok-k">delete</span><span class="tok-p">[]</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// You can use load_buffer_inplace_own to load document from mutable memory block and to pass the ownership of this block</span> <span class="tok-c1">// The block has to be allocated via pugixml allocation function - using i.e. operator new here is incorrect</span> <span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-k">static_cast</span><span class="tok-o">&lt;</span><span class="tok-kt">char</span><span class="tok-o">*&gt;</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">get_memory_allocation_function</span><span class="tok-p">()(</span><span class="tok-n">size</span><span class="tok-p">));</span> <span class="tok-n">memcpy</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-c1">// The block will be deleted by the document</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_buffer_inplace_own</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// You can use load to load document from null-terminated strings, for example literals:</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-s">&quot;&lt;mesh name=&#39;sphere&#39;&gt;&lt;bounds&gt;0 0 1 1&lt;/bounds&gt;&lt;/mesh&gt;&quot;</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="loading.stream"><a class="anchor" href="#loading.stream"></a><a class="link" href="#loading.stream">4.3. Loading document from C&#43;&#43; IOstreams</a></h3> <div id="xml_document::load_stream" class="paragraph"> <p>To enhance interoperability, pugixml provides functions for loading document from any object which implements C&#43;&#43; <code>std::istream</code> interface. This allows you to load documents from any standard C&#43;&#43; stream (i.e. file stream) or any third-party compliant implementation (i.e. Boost Iostreams). There are two functions, one works with narrow character streams, another handles wide character ones:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">istream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_document::load</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wistream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p><code>load</code> with <code>std::istream</code> argument loads the document from stream from the current read position to the end, treating the stream contents as a byte stream of the specified encoding (with encoding autodetection as necessary). Thus calling <code>xml_document::load</code> on an opened <code>std::ifstream</code> object is equivalent to calling <code>xml_document::load_file</code>.</p> </div> <div class="paragraph"> <p><code>load</code> with <code>std::wstream</code> argument treats the stream contents as a wide character stream (encoding is always <a href="#encoding_wchar">encoding_wchar</a>). Because of this, using <code>load</code> with wide character streams requires careful (usually platform-specific) stream setup (i.e. using the <code>imbue</code> function). Generally use of wide streams is discouraged, however it provides you the ability to load documents from non-Unicode encodings, i.e. you can load Shift-JIS encoded data if you set the correct locale.</p> </div> <div class="paragraph"> <p>This is a simple example of loading XML document from file using streams (<a href="samples/load_stream.cpp" class="bare">samples/load_stream.cpp</a>); read the sample code for more complex examples involving wide streams and locales:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ifstream</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">(</span><span class="tok-s">&quot;weekly-utf-8.xml&quot;</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load</span><span class="tok-p">(</span><span class="tok-n">stream</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="loading.errors"><a class="anchor" href="#loading.errors"></a><a class="link" href="#loading.errors">4.4. Handling parsing errors</a></h3> <div id="xml_parse_result" class="paragraph"> <p>All document loading functions return the parsing result via <code>xml_parse_result</code> object. It contains parsing status, the offset of last successfully parsed character from the beginning of the source stream, and the encoding of the source stream:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">xml_parse_result</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_status</span><span class="tok-w"> </span><span class="tok-n">status</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><span class="tok-n">offset</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-p">};</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="xml_parse_status"></a><a id="xml_parse_result::status"></a> Parsing status is represented as the <code>xml_parse_status</code> enumeration and can be one of the following:</p> </div> <div class="ulist"> <ul> <li> <p><a id="status_ok"></a><code>status_ok</code> means that no error was encountered during parsing; the source stream represents the valid XML document which was fully parsed and converted to a tree.</p> </li> <li> <p><a id="status_file_not_found"></a><code>status_file_not_found</code> is only returned by <code>load_file</code> function and means that file could not be opened.</p> </li> <li> <p><a id="status_io_error"></a><code>status_io_error</code> is returned by <code>load_file</code> function and by <code>load</code> functions with <code>std::istream</code>/<code>std::wstream</code> arguments; it means that some I/O error has occurred during reading the file/stream.</p> </li> <li> <p><a id="status_out_of_memory"></a><code>status_out_of_memory</code> means that there was not enough memory during some allocation; any allocation failure during parsing results in this error.</p> </li> <li> <p><a id="status_internal_error"></a><code>status_internal_error</code> means that something went horribly wrong; currently this error does not occur</p> </li> <li> <p><a id="status_unrecognized_tag"></a><code>status_unrecognized_tag</code> means that parsing stopped due to a tag with either an empty name or a name which starts with incorrect character, such as <code>#</code>.</p> </li> <li> <p><a id="status_bad_pi"></a><code>status_bad_pi</code> means that parsing stopped due to incorrect document declaration/processing instruction</p> </li> <li> <p><a id="status_bad_comment"></a><code>status_bad_comment</code>, <a id="status_bad_cdata"></a><code>status_bad_cdata</code>, <a id="status_bad_doctype"></a><code>status_bad_doctype</code> and <a id="status_bad_pcdata"></a><code>status_bad_pcdata</code> mean that parsing stopped due to the invalid construct of the respective type</p> </li> <li> <p><a id="status_bad_start_element"></a><code>status_bad_start_element</code> means that parsing stopped because starting tag either had no closing <code>&gt;</code> symbol or contained some incorrect symbol</p> </li> <li> <p><a id="status_bad_attribute"></a><code>status_bad_attribute</code> means that parsing stopped because there was an incorrect attribute, such as an attribute without value or with value that is not quoted (note that <code>&lt;node attr=1&gt;</code> is incorrect in XML)</p> </li> <li> <p><a id="status_bad_end_element"></a><code>status_bad_end_element</code> means that parsing stopped because ending tag had incorrect syntax (i.e. extra non-whitespace symbols between tag name and <code>&gt;</code>)</p> </li> <li> <p><a id="status_end_element_mismatch"></a><code>status_end_element_mismatch</code> means that parsing stopped because the closing tag did not match the opening one (i.e. <code>&lt;node&gt;&lt;/nedo&gt;</code>) or because some tag was not closed at all</p> </li> <li> <p><a id="status_no_document_element"></a><code>status_no_document_element</code> means that no element nodes were discovered during parsing; this usually indicates an empty or invalid document</p> </li> </ul> </div> <div id="xml_parse_result::description" class="paragraph"> <p><code>description()</code> member function can be used to convert parsing status to a string; the returned message is always in English, so you&#8217;ll have to write your own function if you need a localized string. However please note that the exact messages returned by <code>description()</code> function may change from version to version, so any complex status handling should be based on <code>status</code> value. Note that <code>description()</code> returns a <code>char</code> string even in <code>PUGIXML_WCHAR_MODE</code>; you&#8217;ll have to call <a href="#as_wide">as_wide</a> to get the <code>wchar_t</code> string.</p> </div> <div class="paragraph"> <p>If parsing failed because the source data was not a valid XML, the resulting tree is not destroyed - despite the fact that load function returns error, you can use the part of the tree that was successfully parsed. Obviously, the last element may have an unexpected name/value; for example, if the attribute value does not end with the necessary quotation mark, like in <code>&lt;node attr="value&gt;some data&lt;/node&gt;</code> example, the value of attribute <code>attr</code> will contain the string <code>value&gt;some data&lt;/node&gt;</code>.</p> </div> <div id="xml_parse_result::offset" class="paragraph"> <p>In addition to the status code, parsing result has an <code>offset</code> member, which contains the offset of last successfully parsed character if parsing failed because of an error in source data; otherwise <code>offset</code> is 0. For parsing efficiency reasons, pugixml does not track the current line during parsing; this offset is in units of <a href="#char_t">pugi::char_t</a> (bytes for character mode, wide characters for wide character mode). Many text editors support 'Go To Position' feature - you can use it to locate the exact error position. Alternatively, if you&#8217;re loading the document from memory, you can display the error chunk along with the error description (see the example code below).</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> Offset is calculated in the XML buffer in native encoding; if encoding conversion is performed during parsing, offset can not be used to reliably track the error position. </td> </tr> </table> </div> <div id="xml_parse_result::encoding" class="paragraph"> <p>Parsing result also has an <code>encoding</code> member, which can be used to check that the source data encoding was correctly guessed. It is equal to the exact encoding used during parsing (i.e. with the exact endianness); see <a href="#loading.encoding">Encodings</a> for more information.</p> </div> <div id="xml_parse_result::bool" class="paragraph"> <p>Parsing result object can be implicitly converted to <code>bool</code>; if you do not want to handle parsing errors thoroughly, you can just check the return value of load functions as if it was a <code>bool</code>: <code>if (doc.load_file("file.xml")) { &#8230;&#8203; } else { &#8230;&#8203; }</code>.</p> </div> <div class="paragraph"> <p>This is an example of handling loading errors (<a href="samples/load_error_handling.cpp" class="bare">samples/load_error_handling.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">);</span> <span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">result</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;XML [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;] parsed without errors, attr value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;attr&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-k">else</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;XML [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;] parsed with errors, attr value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;attr&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Error description: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Error offset: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">offset</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; (error at [...&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">+</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">offset</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="loading.options"><a class="anchor" href="#loading.options"></a><a class="link" href="#loading.options">4.5. Parsing options</a></h3> <div class="paragraph"> <p>All document loading functions accept the optional parameter <code>options</code>. This is a bitmask that customizes the parsing process: you can select the node types that are parsed and various transformations that are performed with the XML text. Disabling certain transformations can improve parsing performance for some documents; however, the code for all transformations is very well optimized, and thus the majority of documents won&#8217;t get any performance benefit. As a rule of thumb, only modify parsing flags if you want to get some nodes in the document that are excluded by default (i.e. declaration or comment nodes).</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> You should use the usual bitwise arithmetics to manipulate the bitmask: to enable a flag, use <code>mask | flag</code>; to disable a flag, use <code>mask &amp; ~flag</code>. </td> </tr> </table> </div> <div class="paragraph"> <p>These flags control the resulting tree contents:</p> </div> <div class="ulist"> <ul> <li> <p><a id="parse_declaration"></a><code>parse_declaration</code> determines if XML document declaration (node with type <a href="#node_declaration">node_declaration</a>) is to be put in DOM tree. If this flag is off, it is not put in the tree, but is still parsed and checked for correctness. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_doctype"></a><code>parse_doctype</code> determines if XML document type declaration (node with type <a href="#node_doctype">node_doctype</a>) is to be put in DOM tree. If this flag is off, it is not put in the tree, but is still parsed and checked for correctness. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_pi"></a><code>parse_pi</code> determines if processing instructions (nodes with type <a href="#node_pi">node_pi</a>) are to be put in DOM tree. If this flag is off, they are not put in the tree, but are still parsed and checked for correctness. Note that <code>&lt;?xml &#8230;&#8203;?&gt;</code> (document declaration) is not considered to be a PI. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_comments"></a><code>parse_comments</code> determines if comments (nodes with type <a href="#node_comment">node_comment</a>) are to be put in DOM tree. If this flag is off, they are not put in the tree, but are still parsed and checked for correctness. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_cdata"></a><code>parse_cdata</code> determines if CDATA sections (nodes with type <a href="#node_cdata">node_cdata</a>) are to be put in DOM tree. If this flag is off, they are not put in the tree, but are still parsed and checked for correctness. This flag is <strong>on</strong> by default.</p> </li> <li> <p><a id="parse_trim_pcdata"></a><code>parse_trim_pcdata</code> determines if leading and trailing whitespace characters are to be removed from PCDATA nodes. While for some applications leading/trailing whitespace is significant, often the application only cares about the non-whitespace contents so it&#8217;s easier to trim whitespace from text during parsing. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_ws_pcdata"></a><code>parse_ws_pcdata</code> determines if PCDATA nodes (nodes with type <a href="#node_pcdata">node_pcdata</a>) that consist only of whitespace characters are to be put in DOM tree. Often whitespace-only data is not significant for the application, and the cost of allocating and storing such nodes (both memory and speed-wise) can be significant. For example, after parsing XML string <code>&lt;node&gt; &lt;a/&gt; &lt;/node&gt;</code>, <code>&lt;node&gt;</code> element will have three children when <code>parse_ws_pcdata</code> is set (child with type <a href="#node_pcdata">node_pcdata</a> and value <code>" "</code>, child with type <a href="#node_element">node_element</a> and name <code>"a"</code>, and another child with type <a href="#node_pcdata">node_pcdata</a> and value <code>" "</code>), and only one child when <code>parse_ws_pcdata</code> is not set. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_ws_pcdata_single"></a><code>parse_ws_pcdata_single</code> determines if whitespace-only PCDATA nodes that have no sibling nodes are to be put in DOM tree. In some cases application needs to parse the whitespace-only contents of nodes, i.e. <code>&lt;node&gt; &lt;/node&gt;</code>, but is not interested in whitespace markup elsewhere. It is possible to use <a href="#parse_ws_pcdata">parse_ws_pcdata</a> flag in this case, but it results in excessive allocations and complicates document processing; this flag can be used to avoid that. As an example, after parsing XML string <code>&lt;node&gt; &lt;a&gt; &lt;/a&gt; &lt;/node&gt;</code> with <code>parse_ws_pcdata_single</code> flag set, <code>&lt;node&gt;</code> element will have one child <code>&lt;a&gt;</code>, and <code>&lt;a&gt;</code> element will have one child with type <a href="#node_pcdata">node_pcdata</a> and value <code>" "</code>. This flag has no effect if <a href="#parse_ws_pcdata">parse_ws_pcdata</a> is enabled. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_embed_pcdata"></a><code>parse_embed_pcdata</code> determines if PCDATA contents is to be saved as element values. Normally element nodes have names but not values; this flag forces the parser to store the contents as a value if PCDATA is the first child of the element node (otherwise PCDATA node is created as usual). This can significantly reduce the memory required for documents with many PCDATA nodes. To retrieve the data you can use <code>xml_node::value()</code> on the element nodes or any of the higher-level functions like <code>child_value</code> or <code>text</code>. This flag is <strong>off</strong> by default. Since this flag significantly changes the DOM structure it is only recommended for parsing documents with many PCDATA nodes in memory-constrained environments. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="parse_merge_pcdata"></a><code>parse_merge_pcdata</code> determines if PCDATA contents is to be merged with the previous PCDATA node when no intermediary nodes are present between them. If the PCDATA contains CDATA sections, PI nodes, or comments in between, and either of the flags <a href="#parse_cdata">parse_cdata</a> ,<a href="#parse_pi">parse_pi</a> ,<a href="#parse_comments">parse_comments</a> is not set, the contents of the PCDATA node will be merged with the previous one. This flag is <strong>off</strong> by default. Note that this flag is not compatible with <code>parse_embed_pcdata</code>.</p> </li> <li> <p><a id="parse_fragment"></a><code>parse_fragment</code> determines if document should be treated as a fragment of a valid XML. Parsing document as a fragment leads to top-level PCDATA content (i.e. text that is not located inside a node) to be added to a tree, and additionally treats documents without element nodes as valid and permits multiple top-level element nodes (currently multiple top-level element nodes are also permitted when the flag is off, but that behavior should not be relied on). This flag is <strong>off</strong> by default.</p> </li> </ul> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> Using in-place parsing (<a href="#xml_document::load_buffer_inplace">load_buffer_inplace</a>) with <code>parse_fragment</code> flag may result in the loss of the last character of the buffer if it is a part of PCDATA. Since PCDATA values are null-terminated strings, the only way to resolve this is to provide a null-terminated buffer as an input to <code>load_buffer_inplace</code> - i.e. <code>doc.load_buffer_inplace("test\0", 5, pugi::parse_default | pugi::parse_fragment)</code>. </td> </tr> </table> </div> <div class="paragraph"> <p>These flags control the transformation of tree element contents:</p> </div> <div class="ulist"> <ul> <li> <p><a id="parse_escapes"></a><code>parse_escapes</code> determines if character and entity references are to be expanded during the parsing process. Character references have the form <code>&amp;#&#8230;&#8203;;</code> or <code>&amp;#x&#8230;&#8203;;</code> (<code>&#8230;&#8203;</code> is Unicode numeric representation of character in either decimal (<code>&amp;#&#8230;&#8203;;</code>) or hexadecimal (<code>&amp;#x&#8230;&#8203;;</code>) form), entity references are <code>&amp;lt;</code>, <code>&amp;gt;</code>, <code>&amp;amp;</code>, <code>&amp;apos;</code> and <code>&amp;quot;</code> (note that as pugixml does not handle DTD, the only allowed entities are predefined ones). If character/entity reference can not be expanded, it is left as is, so you can do additional processing later. Reference expansion is performed on attribute values and PCDATA content. This flag is <strong>on</strong> by default.</p> </li> <li> <p><a id="parse_eol"></a><code>parse_eol</code> determines if EOL handling (that is, replacing sequences <code>\r\n</code> by a single <code>\n</code> character, and replacing all standalone <code>\r</code> characters by <code>\n</code>) is to be performed on input data (that is, comment contents, PCDATA/CDATA contents and attribute values). This flag is <strong>on</strong> by default.</p> </li> <li> <p><a id="parse_wconv_attribute"></a><code>parse_wconv_attribute</code> determines if attribute value normalization should be performed for all attributes. This means, that whitespace characters (new line, tab and space) are replaced with space (<code>' '</code>). New line characters are always treated as if <a href="#parse_eol">parse_eol</a> is set, i.e. <code>\r\n</code> is converted to a single space. This flag is <strong>on</strong> by default.</p> </li> <li> <p><a id="parse_wnorm_attribute"></a><code>parse_wnorm_attribute</code> determines if extended attribute value normalization should be performed for all attributes. This means, that after attribute values are normalized as if <a href="#parse_wconv_attribute">parse_wconv_attribute</a> was set, leading and trailing space characters are removed, and all sequences of space characters are replaced by a single space character. <a href="#parse_wconv_attribute">parse_wconv_attribute</a> has no effect if this flag is on. This flag is <strong>off</strong> by default.</p> </li> </ul> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> <code>parse_wconv_attribute</code> option performs transformations that are required by W3C specification for attributes that are declared as CDATA; <a href="#parse_wnorm_attribute">parse_wnorm_attribute</a> performs transformations required for NMTOKENS attributes. In the absence of document type declaration all attributes should behave as if they are declared as CDATA, thus <a href="#parse_wconv_attribute">parse_wconv_attribute</a> is the default option. </td> </tr> </table> </div> <div class="paragraph"> <p>Additionally there are three predefined option masks:</p> </div> <div class="ulist"> <ul> <li> <p><a id="parse_minimal"></a><code>parse_minimal</code> has all options turned off. This option mask means that pugixml does not add declaration nodes, document type declaration nodes, PI nodes, CDATA sections and comments to the resulting tree and does not perform any conversion for input data, so theoretically it is the fastest mode. However, as mentioned above, in practice <a href="#parse_default">parse_default</a> is usually equally fast.</p> </li> <li> <p><a id="parse_default"></a><code>parse_default</code> is the default set of flags, i.e. it has all options set to their default values. It includes parsing CDATA sections (comments/PIs are not parsed), performing character and entity reference expansion, replacing whitespace characters with spaces in attribute values and performing EOL handling. Note, that PCDATA sections consisting only of whitespace characters are not parsed (by default) for performance reasons.</p> </li> <li> <p><a id="parse_full"></a><code>parse_full</code> is the set of flags which adds nodes of all types to the resulting tree and performs default conversions for input data. It includes parsing CDATA sections, comments, PI nodes, document declaration node and document type declaration node, performing character and entity reference expansion, replacing whitespace characters with spaces in attribute values and performing EOL handling. Note, that PCDATA sections consisting only of whitespace characters are not parsed in this mode.</p> </li> </ul> </div> <div class="paragraph"> <p>This is an example of using different parsing options (<a href="samples/load_options.cpp" class="bare">samples/load_options.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&lt;!--comment--&gt;&lt;node&gt;&amp;lt;&lt;/node&gt;&quot;</span><span class="tok-p">;</span> <span class="tok-c1">// Parsing with default options; note that comment node is not added to the tree, and entity reference &amp;lt; is expanded</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;First node value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;], node child value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-c1">// Parsing with additional parse_comments option; comment node is now added to the tree</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_default</span><span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_comments</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;First node value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;], node child value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-c1">// Parsing with additional parse_comments option and without the (default) parse_escapes option; &amp;lt; is not expanded</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_default</span><span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_comments</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-o">~</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_escapes</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;First node value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;], node child value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-c1">// Parsing with minimal option mask; comment node is not added to the tree, and &amp;lt; is not expanded</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_minimal</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;First node value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;], node child value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="loading.encoding"><a class="anchor" href="#loading.encoding"></a><a class="link" href="#loading.encoding">4.6. Encodings</a></h3> <div id="xml_encoding" class="paragraph"> <p>pugixml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it&#8217;s a strict subset of UTF-16) as well as some non-Unicode encodings (Latin-1) and handles all encoding conversions. Most loading functions accept the optional parameter <code>encoding</code>. This is a value of enumeration type <code>xml_encoding</code>, that can have the following values:</p> </div> <div class="ulist"> <ul> <li> <p><a id="encoding_auto"></a><code>encoding_auto</code> means that pugixml will try to guess the encoding based on source XML data. The algorithm is a modified version of the one presented in <a href="http://www.w3.org/TR/REC-xml/#sec-guessing">Appendix F of XML recommendation</a>. It tries to find a Byte Order Mark of one of the supported encodings first; if that fails, it checks if the first few bytes of the input data look like a representation of <code>&lt;</code> or <code>&lt;?</code> in one of UTF-16 or UTF-32 variants; if that fails as well, encoding is assumed to be either UTF-8 or one of the non-Unicode encodings - to make the final decision the algorithm tries to parse the <code>encoding</code> attribute of the XML document declaration, ultimately falling back to UTF-8 if document declaration is not present or does not specify a supported encoding.</p> </li> <li> <p><a id="encoding_utf8"></a><code>encoding_utf8</code> corresponds to UTF-8 encoding as defined in the Unicode standard; UTF-8 sequences with length equal to 5 or 6 are not standard and are rejected.</p> </li> <li> <p><a id="encoding_utf16_le"></a><code>encoding_utf16_le</code> corresponds to little-endian UTF-16 encoding as defined in the Unicode standard; surrogate pairs are supported.</p> </li> <li> <p><a id="encoding_utf16_be"></a><code>encoding_utf16_be</code> corresponds to big-endian UTF-16 encoding as defined in the Unicode standard; surrogate pairs are supported.</p> </li> <li> <p><a id="encoding_utf16"></a><code>encoding_utf16</code> corresponds to UTF-16 encoding as defined in the Unicode standard; the endianness is assumed to be that of the target platform.</p> </li> <li> <p><a id="encoding_utf32_le"></a><code>encoding_utf32_le</code> corresponds to little-endian UTF-32 encoding as defined in the Unicode standard.</p> </li> <li> <p><a id="encoding_utf32_be"></a><code>encoding_utf32_be</code> corresponds to big-endian UTF-32 encoding as defined in the Unicode standard.</p> </li> <li> <p><a id="encoding_utf32"></a><code>encoding_utf32</code> corresponds to UTF-32 encoding as defined in the Unicode standard; the endianness is assumed to be that of the target platform.</p> </li> <li> <p><a id="encoding_wchar"></a><code>encoding_wchar</code> corresponds to the encoding of <code>wchar_t</code> type; it has the same meaning as either <code>encoding_utf16</code> or <code>encoding_utf32</code>, depending on <code>wchar_t</code> size.</p> </li> <li> <p><a id="encoding_latin1"></a><code>encoding_latin1</code> corresponds to ISO-8859-1 encoding (also known as Latin-1).</p> </li> </ul> </div> <div class="paragraph"> <p>The algorithm used for <code>encoding_auto</code> correctly detects any supported Unicode encoding for all well-formed XML documents (since they start with document declaration) and for all other XML documents that start with <code>&lt;</code>; if your XML document does not start with <code>&lt;</code> and has encoding that is different from UTF-8, use the specific encoding.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> The current behavior for Unicode conversion is to skip all invalid UTF sequences during conversion. This behavior should not be relied upon; moreover, in case no encoding conversion is performed, the invalid sequences are not removed, so you&#8217;ll get them as is in node/attribute contents. </td> </tr> </table> </div> </div> <div class="sect2"> <h3 id="loading.w3c"><a class="anchor" href="#loading.w3c"></a><a class="link" href="#loading.w3c">4.7. Conformance to W3C specification</a></h3> <div class="paragraph"> <p>pugixml is not fully W3C conformant - it can load any valid XML document, but does not perform some well-formedness checks. While considerable effort is made to reject invalid XML documents, some validation is not performed because of performance reasons.</p> </div> <div class="paragraph"> <p>There is only one non-conformant behavior when dealing with valid XML documents: pugixml does not use information supplied in document type declaration for parsing. This means that entities declared in DOCTYPE are not expanded, and all attribute/PCDATA values are always processed in a uniform way that depends only on parsing options.</p> </div> <div class="paragraph"> <p>As for rejecting invalid XML documents, there are a number of incompatibilities with W3C specification, including:</p> </div> <div class="ulist"> <ul> <li> <p>Multiple attributes of the same node can have equal names.</p> </li> <li> <p>Tag and attribute names are not fully validated for consisting of allowed characters, so some invalid tags are not rejected</p> </li> <li> <p>Attribute values which contain <code>&lt;</code> are not rejected.</p> </li> <li> <p>Invalid entity/character references are not rejected and are instead left as is.</p> </li> <li> <p>Comment values can contain <code>--</code>.</p> </li> <li> <p>XML data is not required to begin with document declaration; additionally, document declaration can appear after comments and other nodes.</p> </li> <li> <p>Invalid document type declarations are silently ignored in some cases.</p> </li> <li> <p>Unicode validation is not performed so invalid UTF sequences are not rejected.</p> </li> <li> <p>Document can contain multiple top-level element nodes.</p> </li> </ul> </div> </div> </div> </div> <div class="sect1"> <h2 id="access"><a class="anchor" href="#access"></a><a class="link" href="#access">5. Accessing document data</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml features an extensive interface for getting various types of data from the document and for traversing the document. This section provides documentation for all such functions that do not modify the tree except for XPath-related functions; see <a href="#xpath">XPath</a> for XPath reference. As discussed in <a href="#dom.cpp">C&#43;&#43; interface</a>, there are two types of handles to tree data - <a href="#xml_node">xml_node</a> and <a href="#xml_attribute">xml_attribute</a>. The handles have special null (empty) values which propagate through various functions and thus are useful for writing more concise code; see <a href="#node_null">this description</a> for details. The documentation in this section will explicitly state the results of all function in case of null inputs.</p> </div> <div class="sect2"> <h3 id="access.basic"><a class="anchor" href="#access.basic"></a><a class="link" href="#access.basic">5.1. Basic traversal functions</a></h3> <div class="paragraph"> <p><a id="xml_node::parent"></a><a id="xml_node::first_child"></a><a id="xml_node::last_child"></a><a id="xml_node::next_sibling"></a><a id="xml_node::previous_sibling"></a><a id="xml_node::first_attribute"></a><a id="xml_node::last_attribute"></a><a id="xml_attribute::next_attribute"></a><a id="xml_attribute::previous_attribute"></a> The internal representation of the document is a tree, where each node has a list of child nodes (the order of children corresponds to their order in the XML representation), and additionally element nodes have a list of attributes, which is also ordered. Several functions are provided in order to let you get from one node in the tree to the other. These functions roughly correspond to the internal representation, and thus are usually building blocks for other methods of traversing (i.e. XPath traversals are based on these functions).</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::parent</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::first_child</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::last_child</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::next_sibling</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::previous_sibling</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::first_attribute</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::last_attribute</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::next_attribute</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::previous_attribute</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>parent</code> function returns the node&#8217;s parent; all non-null nodes except the document have non-null parent. <code>first_child</code> and <code>last_child</code> return the first and last child of the node, respectively; note that only document nodes and element nodes can have non-empty child node list. If node has no children, both functions return null nodes. <code>next_sibling</code> and <code>previous_sibling</code> return the node that&#8217;s immediately to the right/left of this node in the children list, respectively - for example, in <code>&lt;a/&gt;&lt;b/&gt;&lt;c/&gt;</code>, calling <code>next_sibling</code> for a handle that points to <code>&lt;b/&gt;</code> results in a handle pointing to <code>&lt;c/&gt;</code>, and calling <code>previous_sibling</code> results in handle pointing to <code>&lt;a/&gt;</code>. If node does not have next/previous sibling (this happens if it is the last/first node in the list, respectively), the functions return null nodes. <code>first_attribute</code>, <code>last_attribute</code>, <code>next_attribute</code> and <code>previous_attribute</code> functions behave similarly to the corresponding child node functions and allow to iterate through attribute list in the same way.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> Because of memory consumption reasons, attributes do not have a link to their parent nodes. Thus there is no <code>xml_attribute::parent()</code> function. </td> </tr> </table> </div> <div class="paragraph"> <p>Calling any of the functions above on the null handle results in a null handle - i.e. <code>node.first_child().next_sibling()</code> returns the second child of <code>node</code>, and null handle if <code>node</code> is null, has no children at all or if it has only one child node.</p> </div> <div class="paragraph"> <p>With these functions, you can iterate through all child nodes and display all attributes like this (<a href="samples/traverse_base.cpp" class="bare">samples/traverse_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">())</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool:&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">first_attribute</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">next_attribute</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.nodedata"><a class="anchor" href="#access.nodedata"></a><a class="link" href="#access.nodedata">5.2. Getting node data</a></h3> <div class="paragraph"> <p><a id="xml_node::name"></a><a id="xml_node::value"></a> Apart from structural information (parent, child nodes, attributes), nodes can have name and value, both of which are strings. Depending on node type, name or value may be absent. <a href="#node_document">node_document</a> nodes do not have a name or value, <a href="#node_element">node_element</a> and <a href="#node_declaration">node_declaration</a> nodes always have a name but never have a value, <a href="#node_pcdata">node_pcdata</a>, <a href="#node_cdata">node_cdata</a>, <a href="#node_comment">node_comment</a> and <a href="#node_doctype">node_doctype</a> nodes never have a name but always have a value (it may be empty though), <a href="#node_pi">node_pi</a> nodes always have a name and a value (again, value may be empty). In order to get node&#8217;s name or value, you can use the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>In case node does not have a name or value or if the node handle is null, both functions return empty strings - they never return null pointers.</p> </div> <div id="xml_node::child_value" class="paragraph"> <p>It is common to store data as text contents of some node - i.e. <code>&lt;node&gt;&lt;description&gt;This is a node&lt;/description&gt;&lt;/node&gt;</code>. In this case, <code>&lt;description&gt;</code> node does not have a value, but instead has a child of type <a href="#node_pcdata">node_pcdata</a> with value <code>"This is a node"</code>. pugixml provides several helper functions to parse such data:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::child_value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_node::child_value</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_text</span><span class="tok-w"> </span><span class="tok-nf">xml_node::text</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>child_value()</code> returns the value of the first child with type <a href="#node_pcdata">node_pcdata</a> or <a href="#node_cdata">node_cdata</a>; <code>child_value(name)</code> is a simple wrapper for <code>child(name).child_value()</code>. For the above example, calling <code>node.child_value("description")</code> and <code>description.child_value()</code> will both produce string <code>"This is a node"</code>. If there is no child with relevant type, or if the handle is null, <code>child_value</code> functions return empty string.</p> </div> <div class="paragraph"> <p><code>text()</code> returns a special object that can be used for working with PCDATA contents in more complex cases than just retrieving the value; it is described in <a href="#access.text">Working with text contents</a> sections.</p> </div> <div class="paragraph"> <p>There is an example of using some of these functions <a href="#code_traverse_base_data">at the end of the next section</a>.</p> </div> </div> <div class="sect2"> <h3 id="access.attrdata"><a class="anchor" href="#access.attrdata"></a><a class="link" href="#access.attrdata">5.3. Getting attribute data</a></h3> <div class="paragraph"> <p><a id="xml_attribute::name"></a><a id="xml_attribute::value"></a> All attributes have name and value, both of which are strings (value may be empty). There are two corresponding accessors, like for <code>xml_node</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>In case the attribute handle is null, both functions return empty strings - they never return null pointers.</p> </div> <div id="xml_attribute::as_string" class="paragraph"> <p>If you need a non-empty string if the attribute handle is null (for example, you need to get the option value from XML attribute, but if it is not specified, you need it to default to <code>"sorted"</code> instead of <code>""</code>), you can use <code>as_string</code> accessor:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-n">as_string</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>It returns <code>def</code> argument if the attribute handle is null. If you do not specify the argument, the function is equivalent to <code>value()</code>.</p> </div> <div class="paragraph"> <p><a id="xml_attribute::as_int"></a><a id="xml_attribute::as_uint"></a><a id="xml_attribute::as_double"></a><a id="xml_attribute::as_float"></a><a id="xml_attribute::as_bool"></a><a id="xml_attribute::as_llong"></a><a id="xml_attribute::as_ullong"></a> In many cases attribute values have types that are not strings - i.e. an attribute may always contain values that should be treated as integers, despite the fact that they are represented as strings in XML. pugixml provides several accessors that convert attribute value to some other type:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_int</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_uint</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_double</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_float</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_bool</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_llong</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::as_ullong</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>as_int</code>, <code>as_uint</code>, <code>as_llong</code>, <code>as_ullong</code>, <code>as_double</code> and <code>as_float</code> convert attribute values to numbers. If attribute handle is null <code>def</code> argument is returned (which is 0 by default). Otherwise, all leading whitespace characters are truncated, and the remaining string is parsed as an integer number in either decimal or hexadecimal form (applicable to <code>as_int</code>, <code>as_uint</code>, <code>as_llong</code> and <code>as_ullong</code>; hexadecimal format is used if the number has <code>0x</code> or <code>0X</code> prefix) or as a floating point number in either decimal or scientific form (<code>as_double</code> or <code>as_float</code>).</p> </div> <div class="paragraph"> <p>In case the input string contains a non-numeric character sequence or a number that is out of the target numeric range, the result is undefined.</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> Number conversion functions depend on current C locale as set with <code>setlocale</code>, so may return unexpected results if the locale is different from <code>"C"</code>. </td> </tr> </table> </div> <div class="paragraph"> <p><code>as_bool</code> converts attribute value to boolean as follows: if attribute handle is null, <code>def</code> argument is returned (which is <code>false</code> by default). If attribute value is empty, <code>false</code> is returned. Otherwise, <code>true</code> is returned if the first character is one of <code>'1', 't', 'T', 'y', 'Y'</code>. This means that strings like <code>"true"</code> and <code>"yes"</code> are recognized as <code>true</code>, while strings like <code>"false"</code> and <code>"no"</code> are recognized as <code>false</code>. For more complex matching you&#8217;ll have to write your own function.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> <code>as_llong</code> and <code>as_ullong</code> are only available if your platform has reliable support for the <code>long long</code> type, including string conversions. </td> </tr> </table> </div> <div id="code_traverse_base_data" class="paragraph"> <p>This is an example of using these functions, along with node data retrieval ones (<a href="samples/traverse_base.cpp" class="bare">samples/traverse_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;: AllowRemote &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;AllowRemote&quot;</span><span class="tok-p">).</span><span class="tok-n">as_bool</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, Timeout &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Timeout&quot;</span><span class="tok-p">).</span><span class="tok-n">as_int</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, Description &#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;Description&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.contents"><a class="anchor" href="#access.contents"></a><a class="link" href="#access.contents">5.4. Contents-based traversal functions</a></h3> <div class="paragraph"> <p><a id="xml_node::child"></a><a id="xml_node::attribute"></a><a id="xml_node::next_sibling_name"></a><a id="xml_node::previous_sibling_name"></a> Since a lot of document traversal consists of finding the node/attribute with the correct name, there are special functions for that purpose:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::child</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::child</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attribute</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::next_sibling</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::next_sibling</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::previous_sibling</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::previous_sibling</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>child</code> and <code>attribute</code> return the first child/attribute with the specified name; <code>next_sibling</code> and <code>previous_sibling</code> return the first sibling in the corresponding direction with the specified name. All string comparisons are case-sensitive. In case the node handle is null or there is no node/attribute with the specified name, null handle is returned.</p> </div> <div class="paragraph"> <p><code>child</code> and <code>next_sibling</code> functions can be used together to loop through all child nodes with the desired name like this:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span></code></pre> </div> </div> <div id="xml_node::attribute_hinted" class="paragraph"> <p><code>attribute</code> function needs to look for the target attribute by name. If a node has many attributes, finding each by name can be time consuming. If you have an idea of how attributes are ordered in the node, you can use a faster function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attribute</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>The extra <code>hint</code> argument is used to guess where the attribute might be, and is updated to the location of the next attribute so that if you search for multiple attributes in the right order, the performance is maximized. Note that <code>hint</code> has to be either null or has to belong to the node, otherwise the behavior is undefined.</p> </div> <div class="paragraph"> <p>You can use this function as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">id</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;id&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">version</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>This code is correct regardless of the order of the attributes, but it&#8217;s faster if <code>"id"</code>, <code>"name"</code> and <code>"version"</code> occur in that order.</p> </div> <div id="xml_node::find_child_by_attribute" class="paragraph"> <p>Occasionally the needed node is specified not by the unique name but instead by the value of some attribute; for example, it is common to have node collections with each node having a unique id: <code>&lt;group&gt;&lt;item id="1"/&gt; &lt;item id="2"/&gt;&lt;/group&gt;</code>. There are two functions for finding child nodes based on the attribute values:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::find_child_by_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_value</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::find_child_by_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_value</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>The three-argument function returns the first child node with the specified name which has an attribute with the specified name/value; the two-argument function skips the name test for the node, which can be useful for searching in heterogeneous collections. If the node handle is null or if no node is found, null handle is returned. All string comparisons are case-sensitive.</p> </div> <div class="paragraph"> <p>In all of the above functions, all arguments have to be valid strings; passing null pointers results in undefined behavior.</p> </div> <div class="paragraph"> <p>This is an example of using these functions (<a href="samples/traverse_base.cpp" class="bare">samples/traverse_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool for *.dae generation: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">find_child_by_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;OutputFileMasks&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;*.dae&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.rangefor"><a class="anchor" href="#access.rangefor"></a><a class="link" href="#access.rangefor">5.5. Range-based for-loop support</a></h3> <div class="paragraph"> <p><a id="xml_node::children"></a><a id="xml_node::attributes"></a> If your C&#43;&#43; compiler supports range-based for-loop (this is a C&#43;&#43;11 feature, at the time of writing it&#8217;s supported by Microsoft Visual Studio 2012+, GCC 4.6+ and Clang 3.0+), you can use it to enumerate nodes/attributes. Additional helpers are provided to support this; note that they are also compatible with <a href="http://www.boost.org/libs/foreach/">Boost Foreach</a>, and possibly other pre-C&#43;&#43;11 foreach facilities.</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n"><em>implementation</em></span><span class="tok-o">-</span><span class="tok-n"><em>defined</em></span><span class="tok-o">-</span><span class="tok-n"><em>type</em></span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">children</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n"><em>implementation</em></span><span class="tok-o">-</span><span class="tok-n"><em>defined</em></span><span class="tok-o">-</span><span class="tok-n"><em>type</em></span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">children</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n"><em>implementation</em></span><span class="tok-o">-</span><span class="tok-n"><em>defined</em></span><span class="tok-o">-</span><span class="tok-n"><em>type</em></span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">attributes</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>children</code> function allows you to enumerate all child nodes; <code>children</code> function with <code>name</code> argument allows you to enumerate all child nodes with a specific name; <code>attributes</code> function allows you to enumerate all attributes of the node. Note that you can also use node object itself in a range-based for construct, which is equivalent to using <code>children()</code>.</p> </div> <div class="paragraph"> <p>This is an example of using these functions (<a href="samples/traverse_rangefor.cpp" class="bare">samples/traverse_rangefor.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">children</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool:&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attributes</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">children</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, child &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>While using <code>children()</code> makes the intent of the code clear, note that each node can be treated as a container of child nodes, since it provides <code>begin()</code>/<code>end()</code> member functions described in the next section. Because of this, you can iterate through node&#8217;s children simply by using the node itself:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-p">...</span></code></pre> </div> </div> <div class="paragraph"> <p>When using C&#43;&#43;20, you can also use nodes as well as objects returned by <code>children()</code> and <code>attributes()</code> functions as ranges:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">auto</span><span class="tok-w"> </span><span class="tok-n">tf</span><span class="tok-w"> </span><span class="tok-o">=</span> <span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">children</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">views</span><span class="tok-o">::</span><span class="tok-n">filter</span><span class="tok-p">([](</span><span class="tok-k">auto</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-p">{</span><span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;AllowRemote&quot;</span><span class="tok-p">).</span><span class="tok-n">as_bool</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-p">})</span> <span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">views</span><span class="tok-o">::</span><span class="tok-n">reverse</span><span class="tok-p">;</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tf</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-p">...</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.iterators"><a class="anchor" href="#access.iterators"></a><a class="link" href="#access.iterators">5.6. Traversing node/attribute lists via iterators</a></h3> <div class="paragraph"> <p><a id="xml_node_iterator"></a><a id="xml_attribute_iterator"></a><a id="xml_node::begin"></a><a id="xml_node::end"></a><a id="xml_node::attributes_begin"></a><a id="xml_node::attributes_end"></a> Child node lists and attribute lists are simply double-linked lists; while you can use <code>previous_sibling</code>/<code>next_sibling</code> and other such functions for iteration, pugixml additionally provides node and attribute iterators, so that you can treat nodes as containers of other nodes or attributes:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">class</span><span class="tok-w"> </span><span class="tok-nc">xml_node_iterator</span><span class="tok-p">;</span> <span class="tok-k">class</span><span class="tok-w"> </span><span class="tok-nc">xml_attribute_iterator</span><span class="tok-p">;</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">xml_node_iterator</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">iterator</span><span class="tok-p">;</span> <span class="tok-n">iterator</span><span class="tok-w"> </span><span class="tok-nf">xml_node::begin</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">iterator</span><span class="tok-w"> </span><span class="tok-nf">xml_node::end</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">xml_attribute_iterator</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">attribute_iterator</span><span class="tok-p">;</span> <span class="tok-n">attribute_iterator</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attributes_begin</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">attribute_iterator</span><span class="tok-w"> </span><span class="tok-nf">xml_node::attributes_end</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>begin</code> and <code>attributes_begin</code> return iterators that point to the first node/attribute, respectively; <code>end</code> and <code>attributes_end</code> return past-the-end iterator for node/attribute list, respectively - this iterator can&#8217;t be dereferenced, but decrementing it results in an iterator pointing to the last element in the list (except for empty lists, where decrementing past-the-end iterator results in undefined behavior). Past-the-end iterator is commonly used as a termination value for iteration loops (see sample below). If you want to get an iterator that points to an existing handle, you can construct the iterator with the handle as a single constructor argument, like so: <code>xml_node_iterator(node)</code>. For <code>xml_attribute_iterator</code>, you&#8217;ll have to provide both an attribute and its parent node.</p> </div> <div class="paragraph"> <p><code>begin</code> and <code>end</code> return equal iterators if called on null node; such iterators can&#8217;t be dereferenced. <code>attributes_begin</code> and <code>attributes_end</code> behave the same way. For correct iterator usage this means that child node/attribute collections of null nodes appear to be empty.</p> </div> <div class="paragraph"> <p>Both types of iterators have bidirectional iterator semantics (i.e. they can be incremented and decremented, but efficient random access is not supported) and support all usual iterator operations - comparison, dereference, etc. The iterators are invalidated if the node/attribute objects they&#8217;re pointing to are removed from the tree; adding nodes/attributes does not invalidate any iterators.</p> </div> <div class="paragraph"> <p>Here is an example of using iterators for document traversal (<a href="samples/traverse_iter.cpp" class="bare">samples/traverse_iter.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node_iterator</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">it</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool:&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute_iterator</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-o">-&gt;</span><span class="tok-n">attributes_begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-o">-&gt;</span><span class="tok-n">attributes_end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">ait</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-o">-&gt;</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-o">-&gt;</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> Node and attribute iterators are somewhere in the middle between const and non-const iterators. While dereference operation yields a non-constant reference to the object, so that you can use it for tree modification operations, modifying this reference using assignment - i.e. passing iterators to a function like <code>std::sort</code> - will not give expected results, as assignment modifies local handle that&#8217;s stored in the iterator. </td> </tr> </table> </div> </div> <div class="sect2"> <h3 id="access.walker"><a class="anchor" href="#access.walker"></a><a class="link" href="#access.walker">5.7. Recursive traversal with xml_tree_walker</a></h3> <div id="xml_tree_walker" class="paragraph"> <p>The methods described above allow traversal of immediate children of some node; if you want to do a deep tree traversal, you&#8217;ll have to do it via a recursive function or some equivalent method. However, pugixml provides a helper for depth-first traversal of a subtree. In order to use it, you have to implement <code>xml_tree_walker</code> interface and to call <code>traverse</code> function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">class</span><span class="tok-w"> </span><span class="tok-nc">xml_tree_walker</span> <span class="tok-p">{</span> <span class="tok-k">public</span><span class="tok-o">:</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">begin</span><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">for_each</span><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">end</span><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-nf">depth</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-p">};</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::traverse</span><span class="tok-p">(</span><span class="tok-n">xml_tree_walker</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">walker</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="xml_tree_walker::begin"></a><a id="xml_tree_walker::for_each"></a><a id="xml_tree_walker::end"></a><a id="xml_node::traverse"></a> The traversal is launched by calling <code>traverse</code> function on traversal root and proceeds as follows:</p> </div> <div class="ulist"> <ul> <li> <p>First, <code>begin</code> function is called with traversal root as its argument.</p> </li> <li> <p>Then, <code>for_each</code> function is called for all nodes in the traversal subtree in depth first order, excluding the traversal root. Node is passed as an argument.</p> </li> <li> <p>Finally, <code>end</code> function is called with traversal root as its argument.</p> </li> </ul> </div> <div class="paragraph"> <p>If <code>begin</code>, <code>end</code> or any of the <code>for_each</code> calls return <code>false</code>, the traversal is terminated and <code>false</code> is returned as the traversal result; otherwise, the traversal results in <code>true</code>. Note that you don&#8217;t have to override <code>begin</code> or <code>end</code> functions; their default implementations return <code>true</code>.</p> </div> <div id="xml_tree_walker::depth" class="paragraph"> <p>You can get the node&#8217;s depth relative to the traversal root at any point by calling <code>depth</code> function. It returns <code>-1</code> if called from <code>begin</code>/<code>end</code>, and returns 0-based depth if called from <code>for_each</code> - depth is 0 for all children of the traversal root, 1 for all grandchildren and so on.</p> </div> <div class="paragraph"> <p>This is an example of traversing tree hierarchy with xml_tree_walker (<a href="samples/traverse_walker.cpp" class="bare">samples/traverse_walker.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">simple_walker</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_tree_walker</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">for_each</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">i</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">i</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">i</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-c1">// indentation</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node_types</span><span class="tok-p">[</span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">type</span><span class="tok-p">()]</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;: name=&#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;, value=&#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-c1">// continue traversal</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-p">};</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">simple_walker</span><span class="tok-w"> </span><span class="tok-n">walker</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">traverse</span><span class="tok-p">(</span><span class="tok-n">walker</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.predicate"><a class="anchor" href="#access.predicate"></a><a class="link" href="#access.predicate">5.8. Searching for nodes/attributes with predicates</a></h3> <div class="paragraph"> <p><a id="xml_node::find_attribute"></a><a id="xml_node::find_child"></a><a id="xml_node::find_node"></a> While there are existing functions for getting a node/attribute with known contents, they are often not sufficient for simple queries. As an alternative for manual iteration through nodes/attributes until the needed one is found, you can make a predicate and call one of <code>find_</code> functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">find_attribute</span><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">find_child</span><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">find_node</span><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>The predicate should be either a plain function or a function object which accepts one argument of type <code>xml_attribute</code> (for <code>find_attribute</code>) or <code>xml_node</code> (for <code>find_child</code> and <code>find_node</code>), and returns <code>bool</code>. The predicate is never called with null handle as an argument.</p> </div> <div class="paragraph"> <p><code>find_attribute</code> function iterates through all attributes of the specified node, and returns the first attribute for which the predicate returned <code>true</code>. If the predicate returned <code>false</code> for all attributes or if there were no attributes (including the case where the node is null), null attribute is returned.</p> </div> <div class="paragraph"> <p><code>find_child</code> function iterates through all child nodes of the specified node, and returns the first node for which the predicate returned <code>true</code>. If the predicate returned <code>false</code> for all nodes or if there were no child nodes (including the case where the node is null), null node is returned.</p> </div> <div class="paragraph"> <p><code>find_node</code> function performs a depth-first traversal through the subtree of the specified node (excluding the node itself), and returns the first node for which the predicate returned <code>true</code>. If the predicate returned <code>false</code> for all nodes or if subtree was empty, null node is returned.</p> </div> <div class="paragraph"> <p>This is an example of using predicate-based functions (<a href="samples/traverse_predicate.cpp" class="bare">samples/traverse_predicate.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">small_timeout</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Timeout&quot;</span><span class="tok-p">).</span><span class="tok-n">as_int</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-w"> </span><span class="tok-mi">20</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">allow_remote_predicate</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">operator</span><span class="tok-p">()(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-n">strcmp</span><span class="tok-p">(</span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">(),</span><span class="tok-w"> </span><span class="tok-s">&quot;AllowRemote&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">==</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">operator</span><span class="tok-p">()(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;AllowRemote&quot;</span><span class="tok-p">).</span><span class="tok-n">as_bool</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-p">};</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// Find child via predicate (looks for direct children only)</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">find_child</span><span class="tok-p">(</span><span class="tok-n">allow_remote_predicate</span><span class="tok-p">()).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// Find node via predicate (looks for all descendants in depth-first order)</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">find_node</span><span class="tok-p">(</span><span class="tok-n">allow_remote_predicate</span><span class="tok-p">()).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// Find attribute via predicate</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">find_attribute</span><span class="tok-p">(</span><span class="tok-n">allow_remote_predicate</span><span class="tok-p">()).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// We can use simple functions instead of function objects</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">find_child</span><span class="tok-p">(</span><span class="tok-n">small_timeout</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.text"><a class="anchor" href="#access.text"></a><a class="link" href="#access.text">5.9. Working with text contents</a></h3> <div id="xml_text" class="paragraph"> <p>It is common to store data as text contents of some node - i.e. <code>&lt;node&gt;&lt;description&gt;This is a node&lt;/description&gt;&lt;/node&gt;</code>. In this case, <code>&lt;description&gt;</code> node does not have a value, but instead has a child of type <a href="#node_pcdata">node_pcdata</a> with value <code>"This is a node"</code>. pugixml provides a special class, <code>xml_text</code>, to work with such data. Working with text objects to modify data is described in <a href="#modify.text">the documentation for modifying document data</a>; this section describes the access interface of <code>xml_text</code>.</p> </div> <div id="xml_node::text" class="paragraph"> <p>You can get the text object from a node by using <code>text()</code> method:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_text</span><span class="tok-w"> </span><span class="tok-nf">xml_node::text</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>If the node has a type <code>node_pcdata</code> or <code>node_cdata</code>, then the node itself is used to return data; otherwise, a first child node of type <code>node_pcdata</code> or <code>node_cdata</code> is used.</p> </div> <div class="paragraph"> <p><a id="xml_text::empty"></a><a id="xml_text::unspecified_bool_type"></a> You can check if the text object is bound to a valid PCDATA/CDATA node by using it as a boolean value, i.e. <code>if (text) { &#8230;&#8203; }</code> or <code>if (!text) { &#8230;&#8203; }</code>. Alternatively you can check it by using the <code>empty()</code> method:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::empty</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div id="xml_text::get" class="paragraph"> <p>Given a text object, you can get the contents (i.e. the value of PCDATA/CDATA node) by using the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xml_text::get</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>In case text object is empty, the function returns an empty string - it never returns a null pointer.</p> </div> <div class="paragraph"> <p><a id="xml_text::as_string"></a><a id="xml_text::as_int"></a><a id="xml_text::as_uint"></a><a id="xml_text::as_double"></a><a id="xml_text::as_float"></a><a id="xml_text::as_bool"></a><a id="xml_text::as_llong"></a><a id="xml_text::as_ullong"></a> If you need a non-empty string if the text object is empty, or if the text contents is actually a number or a boolean that is stored as a string, you can use the following accessors:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-n">as_string</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_int</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_uint</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_double</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_float</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_bool</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_llong</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-nf">xml_text::as_ullong</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>All of the above functions have the same semantics as similar <code>xml_attribute</code> members: they return the default argument if the text object is empty, they convert the text contents to a target type using the same rules and restrictions. You can <a href="#xml_attribute::as_int">refer to documentation for the attribute functions</a> for details.</p> </div> <div id="xml_text::data" class="paragraph"> <p><code>xml_text</code> is essentially a helper class that operates on <code>xml_node</code> values. It is bound to a node of type <a href="#node_pcdata">node_pcdata</a> or <a href="#node_cdata">node_cdata</a>. You can use the following function to retrieve this node:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_text::data</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Essentially, assuming <code>text</code> is an <code>xml_text</code> object, calling <code>text.get()</code> is equivalent to calling <code>text.data().value()</code>.</p> </div> <div class="paragraph"> <p>This is an example of using <code>xml_text</code> object (<a href="samples/text.cpp" class="bare">samples/text.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Project name: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">().</span><span class="tok-n">get</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Project version: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">().</span><span class="tok-n">as_double</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Project visibility: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;public&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">().</span><span class="tok-n">as_bool</span><span class="tok-p">(</span><span class="tok-cm">/* def= */</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">?</span><span class="tok-w"> </span><span class="tok-s">&quot;public&quot;</span><span class="tok-w"> </span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-s">&quot;private&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Project description: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">().</span><span class="tok-n">get</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="access.misc"><a class="anchor" href="#access.misc"></a><a class="link" href="#access.misc">5.10. Miscellaneous functions</a></h3> <div id="xml_node::root" class="paragraph"> <p>If you need to get the document root of some node, you can use the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::root</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>This function returns the node with type <a href="#node_document">node_document</a>, which is the root node of the document the node belongs to (unless the node is null, in which case null node is returned).</p> </div> <div class="paragraph"> <p><a id="xml_node::path"></a><a id="xml_node::first_element_by_path"></a> While pugixml supports complex XPath expressions, sometimes a simple path handling facility is needed. There are two functions, for getting node path and for converting path to a node:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">string_t</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">path</span><span class="tok-p">(</span><span class="tok-n">char_t</span><span class="tok-w"> </span><span class="tok-n">delimiter</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-sc">&#39;/&#39;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">first_element_by_path</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-w"> </span><span class="tok-n">delimiter</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-sc">&#39;/&#39;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Node paths consist of node names, separated with a delimiter (which is <code>/</code> by default); also paths can contain self (<code>.</code>) and parent (<code>..</code>) pseudo-names, so that this is a valid path: <code>"../../foo/./bar"</code>. <code>path</code> returns the path to the node from the document root, <code>first_element_by_path</code> looks for a node represented by a given path; a path can be an absolute one (absolute paths start with the delimiter), in which case the rest of the path is treated as document root relative, and relative to the given node. For example, in the following document: <code>&lt;a&gt;&lt;b&gt;&lt;c/&gt;&lt;/b&gt;&lt;/a&gt;</code>, node <code>&lt;c/&gt;</code> has path <code>"a/b/c"</code>; calling <code>first_element_by_path</code> for document with path <code>"a/b"</code> results in node <code>&lt;b/&gt;</code>; calling <code>first_element_by_path</code> for node <code>&lt;a/&gt;</code> with path <code>"../a/./b/../."</code> results in node <code>&lt;a/&gt;</code>; calling <code>first_element_by_path</code> with path <code>"/a"</code> results in node <code>&lt;a/&gt;</code> for any node.</p> </div> <div class="paragraph"> <p>In case path component is ambiguous (if there are two nodes with given name), the first one is selected; paths are not guaranteed to uniquely identify nodes in a document. If any component of a path is not found, the result of <code>first_element_by_path</code> is null node; also <code>first_element_by_path</code> returns null node for null nodes, in which case the path does not matter. <code>path</code> returns an empty string for null nodes.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> <code>path</code> function returns the result as STL string, and thus is not available if <a href="#PUGIXML_NO_STL">PUGIXML_NO_STL</a> is defined. </td> </tr> </table> </div> <div id="xml_node::offset_debug" class="paragraph"> <p>pugixml does not record row/column information for nodes upon parsing for efficiency reasons. However, if the node has not changed in a significant way since parsing (the name/value are not changed, and the node itself is the original one, i.e. it was not deleted from the tree and re-added later), it is possible to get the offset from the beginning of XML buffer:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><span class="tok-nf">xml_node::offset_debug</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>If the offset is not available (this happens if the node is null, was not originally parsed from a stream, or has changed in a significant way), the function returns -1. Otherwise it returns the offset to node&#8217;s data from the beginning of XML buffer in <a href="#char_t">pugi::char_t</a> units. For more information on parsing offsets, see <a href="#xml_parse_result::offset">parsing error handling documentation</a>.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="modify"><a class="anchor" href="#modify"></a><a class="link" href="#modify">6. Modifying document data</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>The document in pugixml is fully mutable: you can completely change the document structure and modify the data of nodes/attributes. This section provides documentation for the relevant functions. All functions take care of memory management and structural integrity themselves, so they always result in structurally valid tree - however, it is possible to create an invalid XML tree (for example, by adding two attributes with the same name or by setting attribute/node name to empty/invalid string). Tree modification is optimized for performance and for memory consumption, so if you have enough memory you can create documents from scratch with pugixml and later save them to file/stream instead of relying on error-prone manual text writing and without too much overhead.</p> </div> <div class="paragraph"> <p>All member functions that change node/attribute data or structure are non-constant and thus can not be called on constant handles. However, you can easily convert constant handle to non-constant one by simple assignment: <code>void foo(const pugi::xml_node&amp; n) { pugi::xml_node nc = n; }</code>, so const-correctness here mainly provides additional documentation.</p> </div> <div class="sect2"> <h3 id="modify.nodedata"><a class="anchor" href="#modify.nodedata"></a><a class="link" href="#modify.nodedata">6.1. Setting node data</a></h3> <div class="paragraph"> <p><a id="xml_node::set_name"></a><a id="xml_node::set_value"></a> As discussed before, nodes can have name and value, both of which are strings. Depending on node type, name or value may be absent. <a href="#node_document">node_document</a> nodes do not have a name or value, <a href="#node_element">node_element</a> and <a href="#node_declaration">node_declaration</a> nodes always have a name but never have a value, <a href="#node_pcdata">node_pcdata</a>, <a href="#node_cdata">node_cdata</a>, <a href="#node_comment">node_comment</a> and <a href="#node_doctype">node_doctype</a> nodes never have a name but always have a value (it may be empty though), <a href="#node_pi">node_pi</a> nodes always have a name and a value (again, value may be empty). In order to set node&#8217;s name or value, you can use the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">sz</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_name</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_value</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_value</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::set_value</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Both functions try to set the name/value to the specified string, and return the operation result. The operation fails if the node can not have name or value (for instance, when trying to call <code>set_name</code> on a <a href="#node_pcdata">node_pcdata</a> node), if the node handle is null, or if there is insufficient memory to handle the request. The provided string is copied into document managed memory and can be destroyed after the function returns (for example, you can safely pass stack-allocated buffers to these functions). The name/value content is not verified, so take care to use only valid XML names, or the document may become malformed.</p> </div> <div class="paragraph"> <p>This is an example of setting node name and value (<a href="samples/modify_base.cpp" class="bare">samples/modify_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// change node name</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;notnode&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new node name: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// change comment text</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;useless comment&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new comment text: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can&#39;t change value of the element or name of the comment</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.attrdata"><a class="anchor" href="#modify.attrdata"></a><a class="link" href="#modify.attrdata">6.2. Setting attribute data</a></h3> <div class="paragraph"> <p><a id="xml_attribute::set_name"></a><a id="xml_attribute::set_value"></a> All attributes have name and value, both of which are strings (value may be empty). You can set them with the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_name</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">sz</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_name</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Both functions try to set the name/value to the specified string, and return the operation result. The operation fails if the attribute handle is null, or if there is insufficient memory to handle the request. The provided string is copied into document managed memory and can be destroyed after the function returns (for example, you can safely pass stack-allocated buffers to these functions). The name/value content is not verified, so take care to use only valid XML names, or the document may become malformed.</p> </div> <div class="paragraph"> <p>In addition to string functions, several functions are provided for handling attributes with numbers and booleans as values:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">precision</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">precision</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_attribute::set_value</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The above functions convert the argument to string and then call the base <code>set_value</code> function. Integers are converted to a decimal form, floating-point numbers are converted to either decimal or scientific form, depending on the number magnitude, boolean values are converted to either <code>"true"</code> or <code>"false"</code>.</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> Number conversion functions depend on current C locale as set with <code>setlocale</code>, so may generate unexpected results if the locale is different from <code>"C"</code>. </td> </tr> </table> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> <code>set_value</code> overloads with <code>long long</code> type are only available if your platform has reliable support for the type, including string conversions. </td> </tr> </table> </div> <div id="xml_attribute::assign" class="paragraph"> <p>For convenience, all <code>set_value</code> functions have the corresponding assignment operators:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These operators simply call the right <code>set_value</code> function and return the attribute they&#8217;re called on; the return value of <code>set_value</code> is ignored, so errors are ignored.</p> </div> <div class="paragraph"> <p>This is an example of setting attribute name and value (<a href="samples/modify_base.cpp" class="bare">samples/modify_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;id&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// change attribute name/value</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;key&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;345&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new attribute: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can use numbers or booleans</span> <span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-mf">1.234</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;new attribute value: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can also use assignment operators for more concise code</span> <span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">;</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;final attribute value: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.add"><a class="anchor" href="#modify.add"></a><a class="link" href="#modify.add">6.3. Adding nodes/attributes</a></h3> <div class="paragraph"> <p><a id="xml_node::prepend_attribute"></a><a id="xml_node::append_attribute"></a><a id="xml_node::insert_attribute_after"></a><a id="xml_node::insert_attribute_before"></a><a id="xml_node::prepend_child"></a><a id="xml_node::append_child"></a><a id="xml_node::insert_child_after"></a><a id="xml_node::insert_child_before"></a> Nodes and attributes do not exist without a document tree, so you can&#8217;t create them without adding them to some document. A node or attribute can be created at the end of node/attribute list or before/after some other node:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_attribute</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_attribute</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_attribute_after</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_attribute_after</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_attribute_before</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_attribute_before</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_child</span><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node_element</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_child</span><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node_element</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_after</span><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_before</span><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_child</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_child</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_child</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_child</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_after</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_after</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_before</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_child_before</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p><code>append_attribute</code> and <code>append_child</code> create a new node/attribute at the end of the corresponding list of the node the method is called on; <code>prepend_attribute</code> and <code>prepend_child</code> create a new node/attribute at the beginning of the list; <code>insert_attribute_after</code>, <code>insert_attribute_before</code>, <code>insert_child_after</code> and <code>insert_attribute_before</code> add the node/attribute before or after the specified node/attribute.</p> </div> <div class="paragraph"> <p>Attribute functions create an attribute with the specified name; you can specify the empty name and change the name later if you want to. Node functions with the <code>type</code> argument create the node with the specified type; since node type can&#8217;t be changed, you have to know the desired type beforehand. Also note that not all types can be added as children; see below for clarification. Node functions with the <code>name</code> argument create the element node (<a href="#node_element">node_element</a>) with the specified name.</p> </div> <div class="paragraph"> <p>All functions return the handle to the created object on success, and null handle on failure. There are several reasons for failure:</p> </div> <div class="ulist"> <ul> <li> <p>Adding fails if the target node is null;</p> </li> <li> <p>Only <a href="#node_element">node_element</a> nodes can contain attributes, so attribute adding fails if node is not an element;</p> </li> <li> <p>Only <a href="#node_document">node_document</a> and <a href="#node_element">node_element</a> nodes can contain children, so child node adding fails if the target node is not an element or a document;</p> </li> <li> <p><a href="#node_document">node_document</a> and <a href="#node_null">node_null</a> nodes can not be inserted as children, so passing <a href="#node_document">node_document</a> or <a href="#node_null">node_null</a> value as <code>type</code> results in operation failure;</p> </li> <li> <p><a href="#node_declaration">node_declaration</a> nodes can only be added as children of the document node; attempt to insert declaration node as a child of an element node fails;</p> </li> <li> <p>Adding node/attribute results in memory allocation, which may fail;</p> </li> <li> <p>Insertion functions fail if the specified node or attribute is null or is not in the target node&#8217;s children/attribute list.</p> </li> </ul> </div> <div class="paragraph"> <p>Even if the operation fails, the document remains in consistent state, but the requested node/attribute is not added.</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> <code>attribute()</code> and <code>child()</code> functions do not add attributes or nodes to the tree, so code like <code>node.attribute("id") = 123;</code> will not do anything if <code>node</code> does not have an attribute with name <code>"id"</code>. Make sure you&#8217;re operating with existing attributes/nodes by adding them if necessary. </td> </tr> </table> </div> <div class="paragraph"> <p>This is an example of adding new attributes/nodes to the document (<a href="samples/modify_add.cpp" class="bare">samples/modify_add.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// add node with some name</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// add description node with text child</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">descr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">);</span> <span class="tok-n">descr</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">node_pcdata</span><span class="tok-p">).</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;Simple node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// add param node before the description</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">insert_child_before</span><span class="tok-p">(</span><span class="tok-s">&quot;param&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">descr</span><span class="tok-p">);</span> <span class="tok-c1">// add attributes to param node</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">;</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;value&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mf">1.1</span><span class="tok-p">;</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">insert_attribute_after</span><span class="tok-p">(</span><span class="tok-s">&quot;type&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;float&quot;</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.remove"><a class="anchor" href="#modify.remove"></a><a class="link" href="#modify.remove">6.4. Removing nodes/attributes</a></h3> <div class="paragraph"> <p><a id="xml_node::remove_attribute"></a><a id="xml_node::remove_attributes"></a><a id="xml_node::remove_child"></a><a id="xml_node::remove_children"></a> If you do not want your document to contain some node or attribute, you can remove it with one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">a</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_attributes</span><span class="tok-p">();</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_child</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_children</span><span class="tok-p">();</span></code></pre> </div> </div> <div class="paragraph"> <p><code>remove_attribute</code> removes the attribute from the attribute list of the node, and returns the operation result. <code>remove_child</code> removes the child node with the entire subtree (including all descendant nodes and attributes) from the document, and returns the operation result. <code>remove_attributes</code> removes all the attributes of the node, and returns the operation result. <code>remove_children</code> removes all the child nodes of the node, and returns the operation result. Removing fails if one of the following is true:</p> </div> <div class="ulist"> <ul> <li> <p>The node the function is called on is null;</p> </li> <li> <p>The attribute/node to be removed is null;</p> </li> <li> <p>The attribute/node to be removed is not in the node&#8217;s attribute/child list.</p> </li> </ul> </div> <div class="paragraph"> <p>Removing the attribute or node invalidates all handles to the same underlying object, and also invalidates all iterators pointing to the same object. Removing node also invalidates all past-the-end iterators to its attribute or child node list. Be careful to ensure that all such handles and iterators either do not exist or are not used after the attribute/node is removed.</p> </div> <div class="paragraph"> <p>If you want to remove the attribute or child node by its name, two additional helper functions are available:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_attribute</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_attribute</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_child</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_node::remove_child</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions look for the first attribute or child with the specified name, and then remove it, returning the result. If there is no attribute or child with such name, the function returns <code>false</code>; if there are two nodes with the given name, only the first node is deleted. If you want to delete all nodes with the specified name, you can use code like this: <code>while (node.remove_child("tool")) ;</code>.</p> </div> <div class="paragraph"> <p>This is an example of removing attributes/nodes from the document (<a href="samples/modify_remove.cpp" class="bare">samples/modify_remove.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// remove description node with the whole subtree</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">remove_child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// remove value attribute</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;param&quot;</span><span class="tok-p">);</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">remove_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;value&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// we can also remove nodes/attributes by handles</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">id</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">);</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">remove_attribute</span><span class="tok-p">(</span><span class="tok-n">id</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.text"><a class="anchor" href="#modify.text"></a><a class="link" href="#modify.text">6.5. Working with text contents</a></h3> <div class="paragraph"> <p>pugixml provides a special class, <code>xml_text</code>, to work with text contents stored as a value of some node, i.e. <code>&lt;node&gt;&lt;description&gt;This is a node&lt;/description&gt;&lt;/node&gt;</code>. Working with text objects to retrieve data is described in <a href="#access.text">the documentation for accessing document data</a>; this section describes the modification interface of <code>xml_text</code>.</p> </div> <div id="xml_text::set" class="paragraph"> <p>Once you have an <code>xml_text</code> object, you can set the text contents using the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>This function tries to set the contents to the specified string, and returns the operation result. The operation fails if the text object was retrieved from a node that can not have a value and is not an element node (i.e. it is a <a href="#node_declaration">node_declaration</a> node), if the text object is empty, or if there is insufficient memory to handle the request. The provided string is copied into document managed memory and can be destroyed after the function returns (for example, you can safely pass stack-allocated buffers to this function). Note that if the text object was retrieved from an element node, this function creates the PCDATA child node if necessary (i.e. if the element node does not have a PCDATA/CDATA child already).</p> </div> <div id="xml_text::set_value" class="paragraph"> <p>In addition to a string function, several functions are provided for handling text with numbers and booleans as contents:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">precision</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">precision</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xml_text::set</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The above functions convert the argument to string and then call the base <code>set</code> function. These functions have the same semantics as similar <code>xml_attribute</code> functions. You can <a href="#xml_attribute::set_value">refer to documentation for the attribute functions</a> for details.</p> </div> <div id="xml_text::assign" class="paragraph"> <p>For convenience, all <code>set</code> functions have the corresponding assignment operators:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-o">=</span><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These operators simply call the right <code>set</code> function and return the attribute they&#8217;re called on; the return value of <code>set</code> is ignored, so errors are ignored.</p> </div> <div class="paragraph"> <p>This is an example of using <code>xml_text</code> object to modify text contents (<a href="samples/text.cpp" class="bare">samples/text.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// change project version</span> <span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mf">1.2</span><span class="tok-p">;</span> <span class="tok-c1">// add description element and set the contents</span> <span class="tok-c1">// note that we do not have to explicitly add the node_pcdata child</span> <span class="tok-n">project</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">).</span><span class="tok-n">text</span><span class="tok-p">().</span><span class="tok-n">set</span><span class="tok-p">(</span><span class="tok-s">&quot;a test project&quot;</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.clone"><a class="anchor" href="#modify.clone"></a><a class="link" href="#modify.clone">6.6. Cloning nodes/attributes</a></h3> <div class="paragraph"> <p><a id="xml_node::prepend_copy"></a><a id="xml_node::append_copy"></a><a id="xml_node::insert_copy_after"></a><a id="xml_node::insert_copy_before"></a> With the help of previously described functions, it is possible to create trees with any contents and structure, including cloning the existing data. However since this is an often needed operation, pugixml provides built-in node/attribute cloning facilities. Since nodes and attributes do not exist without a document tree, you can&#8217;t create a standalone copy - you have to immediately insert it somewhere in the tree. For this, you can use one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_copy</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_copy</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_copy_after</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_copy_before</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_copy</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_copy</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_copy_after</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_copy_before</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions mirror the structure of <code>append_child</code>, <code>prepend_child</code>, <code>insert_child_before</code> and related functions - they take the handle to the prototype object, which is to be cloned, insert a new attribute/node at the appropriate place, and then copy the attribute data or the whole node subtree to the new object. The functions return the handle to the resulting duplicate object, or null handle on failure.</p> </div> <div class="paragraph"> <p>The attribute is copied along with the name and value; the node is copied along with its type, name and value; additionally attribute list and all children are recursively cloned, resulting in the deep subtree clone. The prototype object can be a part of the same document, or a part of any other document.</p> </div> <div class="paragraph"> <p>The failure conditions resemble those of <code>append_child</code>, <code>insert_child_before</code> and related functions, <a href="#xml_node::append_child">consult their documentation for more information</a>. There are additional caveats specific to cloning functions:</p> </div> <div class="ulist"> <ul> <li> <p>Cloning null handles results in operation failure;</p> </li> <li> <p>Node cloning starts with insertion of the node of the same type as that of the prototype; for this reason, cloning functions can not be directly used to clone entire documents, since <a href="#node_document">node_document</a> is not a valid insertion type. The example below provides a workaround.</p> </li> <li> <p>It is possible to copy a subtree as a child of some node inside this subtree, i.e. <code>node.append_copy(node.parent().parent());</code>. This is a valid operation, and it results in a clone of the subtree in the state before cloning started, i.e. no infinite recursion takes place.</p> </li> </ul> </div> <div class="paragraph"> <p>This is an example with one possible implementation of include tags in XML (<a href="samples/include.cpp" class="bare">samples/include.cpp</a>). It illustrates node cloning and usage of other document modification functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">load_preprocess</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">preprocess</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">type</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">==</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">node_pi</span><span class="tok-w"> </span><span class="tok-o">&amp;&amp;</span><span class="tok-w"> </span><span class="tok-n">strcmp</span><span class="tok-p">(</span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">(),</span><span class="tok-w"> </span><span class="tok-s">&quot;include&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">==</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">include</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-c1">// load new preprocessed document (note: ideally this should handle relative paths)</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">include</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">!</span><span class="tok-n">load_preprocess</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-c1">// insert the comment marker above include directive</span> <span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">insert_child_before</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">node_comment</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">include</span><span class="tok-p">).</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-n">path</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-c1">// copy the document above the include directive (this retains the original order!)</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">ic</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">ic</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">ic</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">ic</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">insert_copy_before</span><span class="tok-p">(</span><span class="tok-n">ic</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">include</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-c1">// remove the include node and move to the next child</span> <span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">remove_child</span><span class="tok-p">(</span><span class="tok-n">include</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-k">else</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">!</span><span class="tok-n">preprocess</span><span class="tok-p">(</span><span class="tok-n">child</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">load_preprocess</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_file</span><span class="tok-p">(</span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_default</span><span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">parse_pi</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-c1">// for &lt;?include?&gt;</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">?</span><span class="tok-w"> </span><span class="tok-n">preprocess</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="modify.move"><a class="anchor" href="#modify.move"></a><a class="link" href="#modify.move">6.7. Moving nodes</a></h3> <div class="paragraph"> <p><a id="xml_node::prepend_move"></a><a id="xml_node::append_move"></a><a id="xml_node::insert_move_after"></a><a id="xml_node::insert_move_before"></a> Sometimes instead of cloning a node you need to move an existing node to a different position in a tree. This can be accomplished by copying the node and removing the original; however, this is expensive since it results in a lot of extra operations. For moving nodes within the same document tree, you can use of the following functions instead:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_move</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::prepend_move</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_move_after</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::insert_move_before</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions mirror the structure of <code>append_copy</code>, <code>prepend_copy</code>, <code>insert_copy_before</code> and <code>insert_copy_after</code> - they take the handle to the moved object and move it to the appropriate place with all attributes and/or child nodes. The functions return the handle to the resulting object (which is the same as the moved object), or null handle on failure.</p> </div> <div class="paragraph"> <p>The failure conditions resemble those of <code>append_child</code>, <code>insert_child_before</code> and related functions, <a href="#xml_node::append_child">consult their documentation for more information</a>. There are additional caveats specific to moving functions:</p> </div> <div class="ulist"> <ul> <li> <p>Moving null handles results in operation failure;</p> </li> <li> <p>Moving is only possible for nodes that belong to the same document; attempting to move nodes between documents will fail.</p> </li> <li> <p><code>insert_move_after</code> and <code>insert_move_before</code> functions fail if the moved node is the same as the <code>node</code> argument (this operation would be a no-op otherwise).</p> </li> <li> <p>It is impossible to move a subtree to a child of some node inside this subtree, i.e. <code>node.append_move(node.parent().parent());</code> will fail.</p> </li> </ul> </div> </div> <div class="sect2"> <h3 id="modify.fragments"><a class="anchor" href="#modify.fragments"></a><a class="link" href="#modify.fragments">6.8. Assembling document from fragments</a></h3> <div id="xml_node::append_buffer" class="paragraph"> <p>pugixml provides several ways to assemble an XML document from other XML documents. Assuming there is a set of document fragments, represented as in-memory buffers, the implementation choices are as follows:</p> </div> <div class="ulist"> <ul> <li> <p>Use a temporary document to parse the data from a string, then clone the nodes to a destination node. For example:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">append_fragment</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">target</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">!</span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_buffer</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-n">target</span><span class="tok-p">.</span><span class="tok-n">append_copy</span><span class="tok-p">(</span><span class="tok-n">child</span><span class="tok-p">);</span> <span class="tok-p">}</span></code></pre> </div> </div> </li> <li> <p>Cache the parsing step - instead of keeping in-memory buffers, keep document objects that already contain the parsed fragment:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">append_fragment</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">target</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">cached_fragment</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">cached_fragment</span><span class="tok-p">.</span><span class="tok-n">first_child</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-n">target</span><span class="tok-p">.</span><span class="tok-n">append_copy</span><span class="tok-p">(</span><span class="tok-n">child</span><span class="tok-p">);</span> <span class="tok-p">}</span></code></pre> </div> </div> </li> <li> <p>Use <code>xml_node::append_buffer</code> directly:</p> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-nf">xml_node::append_buffer</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span></code></pre> </div> </div> </li> </ul> </div> <div class="paragraph"> <p>The first method is more convenient, but slower than the other two. The relative performance of <code>append_copy</code> and <code>append_buffer</code> depends on the buffer format - usually <code>append_buffer</code> is faster if the buffer is in native encoding (UTF-8 or wchar_t, depending on <code>PUGIXML_WCHAR_MODE</code>). At the same time it might be less efficient in terms of memory usage - the implementation makes a copy of the provided buffer, and the copy has the same lifetime as the document - the memory used by that copy will be reclaimed after the document is destroyed, but no sooner. Even deleting all nodes in the document, including the appended ones, won&#8217;t reclaim the memory.</p> </div> <div class="paragraph"> <p><code>append_buffer</code> behaves in the same way as <a href="#xml_document::load_buffer">xml_document::load_buffer</a> - the input buffer is a byte buffer, with size in bytes; the buffer is not modified and can be freed after the function returns.</p> </div> <div id="status_append_invalid_root" class="paragraph"> <p>Since <code>append_buffer</code> needs to append child nodes to the current node, it only works if the current node is either document or element node. Calling <code>append_buffer</code> on a node with any other type results in an error with <code>status_append_invalid_root</code> status.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="saving"><a class="anchor" href="#saving"></a><a class="link" href="#saving">7. Saving document</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>Often after creating a new document or loading the existing one and processing it, it is necessary to save the result back to file. Also it is occasionally useful to output the whole document or a subtree to some stream; use cases include debug printing, serialization via network or other text-oriented medium, etc. pugixml provides several functions to output any subtree of the document to a file, stream or another generic transport interface; these functions allow to customize the output format (see <a href="#saving.options">Output options</a>), and also perform necessary encoding conversions (see <a href="#saving.encoding">Encodings</a>). This section documents the relevant functionality.</p> </div> <div class="paragraph"> <p>Before writing to the destination the node/attribute data is properly formatted according to the node type; all special XML symbols, such as <code>&lt;</code> and <code>&amp;</code>, are properly escaped (unless <a href="#format_no_escapes">format_no_escapes</a> flag is set). In order to guard against forgotten node/attribute names, empty node/attribute names are printed as <code>":anonymous"</code>. For well-formed output, make sure all node and attribute names are set to meaningful values.</p> </div> <div class="paragraph"> <p>CDATA sections with values that contain <code>"]]&gt;"</code> are split into several sections as follows: section with value <code>"pre]]&gt;post"</code> is written as <code>&lt;![CDATA[pre]]]]&gt;&lt;![CDATA[&gt;post]]&gt;</code>. While this alters the structure of the document (if you load the document after saving it, there will be two CDATA sections instead of one), this is the only way to escape CDATA contents.</p> </div> <div class="sect2"> <h3 id="saving.file"><a class="anchor" href="#saving.file"></a><a class="link" href="#saving.file">7.1. Saving document to a file</a></h3> <div class="paragraph"> <p><a id="xml_document::save_file"></a><a id="xml_document::save_file_wide"></a> If you want to save the whole document to a file, you can use one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">::</span><span class="tok-n">save_file</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">::</span><span class="tok-n">save_file</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions accept file path as its first argument, and also three optional arguments, which specify indentation and other output options (see <a href="#saving.options">Output options</a>) and output data encoding (see <a href="#saving.encoding">Encodings</a>). The path has the target operating system format, so it can be a relative or absolute one, it should have the delimiters of the target system, it should have the exact case if the target file system is case-sensitive, etc. The functions return <code>true</code> on success and <code>false</code> if the file could not be opened or written to.</p> </div> <div class="paragraph"> <p>File path is passed to the system file opening function as is in case of the first function (which accepts <code>const char* path</code>); the second function either uses a special file opening function if it is provided by the runtime library or converts the path to UTF-8 and uses the system file opening function.</p> </div> <div id="xml_writer_file" class="paragraph"> <p><code>save_file</code> opens the target file for writing, outputs the requested header (by default a document declaration is output, unless the document already has one), and then saves the document contents. Calling <code>save_file</code> is equivalent to creating an <code>xml_writer_file</code> object with <code>FILE*</code> handle as the only constructor argument and then calling <code>save</code>; see <a href="#saving.writer">Saving document via writer interface</a> for writer interface details.</p> </div> <div class="paragraph"> <p>This is a simple example of saving XML document to file (<a href="samples/save_file.cpp" class="bare">samples/save_file.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// save document to file</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Saving result: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save_file</span><span class="tok-p">(</span><span class="tok-s">&quot;save_file_output.xml&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="saving.stream"><a class="anchor" href="#saving.stream"></a><a class="link" href="#saving.stream">7.2. Saving document to C&#43;&#43; IOstreams</a></h3> <div id="xml_document::save_stream" class="paragraph"> <p>To enhance interoperability pugixml provides functions for saving document to any object which implements C&#43;&#43; <code>std::ostream</code> interface. This allows you to save documents to any standard C&#43;&#43; stream (i.e. file stream) or any third-party compliant implementation (i.e. Boost Iostreams). Most notably, this allows for easy debug output, since you can use <code>std::cout</code> stream as saving target. There are two functions, one works with narrow character streams, another handles wide character ones:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">::</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">::</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>save</code> with <code>std::ostream</code> argument saves the document to the stream in the same way as <code>save_file</code> (i.e. with requested header and with encoding conversions). On the other hand, <code>save</code> with <code>std::wstream</code> argument saves the document to the wide stream with <a href="#encoding_wchar">encoding_wchar</a> encoding. Because of this, using <code>save</code> with wide character streams requires careful (usually platform-specific) stream setup (i.e. using the <code>imbue</code> function). Generally use of wide streams is discouraged, however it provides you with the ability to save documents to non-Unicode encodings, i.e. you can save Shift-JIS encoded data if you set the correct locale.</p> </div> <div id="xml_writer_stream" class="paragraph"> <p>Calling <code>save</code> with stream target is equivalent to creating an <code>xml_writer_stream</code> object with stream as the only constructor argument and then calling <code>save</code>; see <a href="#saving.writer">Saving document via writer interface</a> for writer interface details.</p> </div> <div class="paragraph"> <p>This is a simple example of saving XML document to standard output (<a href="samples/save_stream.cpp" class="bare">samples/save_stream.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// save document to standard output</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Document:</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="saving.writer"><a class="anchor" href="#saving.writer"></a><a class="link" href="#saving.writer">7.3. Saving document via writer interface</a></h3> <div class="paragraph"> <p><a id="xml_document::save"></a><a id="xml_writer"></a><a id="xml_writer::write"></a> All of the above saving functions are implemented in terms of writer interface. This is a simple interface with a single function, which is called several times during output process with chunks of document data as input:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">class</span><span class="tok-w"> </span><span class="tok-nc">xml_writer</span> <span class="tok-p">{</span> <span class="tok-k">public</span><span class="tok-o">:</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">write</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">data</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span> <span class="tok-p">};</span> <span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">::</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">xml_writer</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">writer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>In order to output the document via some custom transport, for example sockets, you should create an object which implements <code>xml_writer</code> interface and pass it to <code>save</code> function. <code>xml_writer::write</code> function is called with a buffer as an input, where <code>data</code> points to buffer start, and <code>size</code> is equal to the buffer size in bytes. <code>write</code> implementation must write the buffer to the transport; it can not save the passed buffer pointer, as the buffer contents will change after <code>write</code> returns. The buffer contains the chunk of document data in the desired encoding.</p> </div> <div class="paragraph"> <p><code>write</code> function is called with relatively large blocks (size is usually several kilobytes, except for the last block that may be small), so there is often no need for additional buffering in the implementation.</p> </div> <div class="paragraph"> <p>This is a simple example of custom writer for saving document data to STL string (<a href="samples/save_custom_writer.cpp" class="bare">samples/save_custom_writer.cpp</a>); read the sample code for more complex examples:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">xml_string_writer</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_writer</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-nf">write</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">data</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">append</span><span class="tok-p">(</span><span class="tok-k">static_cast</span><span class="tok-o">&lt;</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*&gt;</span><span class="tok-p">(</span><span class="tok-n">data</span><span class="tok-p">),</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-p">};</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="saving.subtree"><a class="anchor" href="#saving.subtree"></a><a class="link" href="#saving.subtree">7.4. Saving a single subtree</a></h3> <div class="paragraph"> <p><a id="xml_node::print"></a><a id="xml_node::print_stream"></a> While the previously described functions save the whole document to the destination, it is easy to save a single subtree. The following functions are provided:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">os</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">os</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">::</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">xml_writer</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">writer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions have the same arguments with the same meaning as the corresponding <code>xml_document::save</code> functions, and allow you to save the subtree to either a C&#43;&#43; IOstream or to any object that implements <code>xml_writer</code> interface.</p> </div> <div class="paragraph"> <p>Saving a subtree differs from saving the whole document: the process behaves as if <a href="#format_write_bom">format_write_bom</a> is off, and <a href="#format_no_declaration">format_no_declaration</a> is on, even if actual values of the flags are different. This means that BOM is not written to the destination, and document declaration is only written if it is the node itself or is one of node&#8217;s children. Note that this also holds if you&#8217;re saving a document; this example (<a href="samples/save_subtree.cpp" class="bare">samples/save_subtree.cpp</a>) illustrates the difference:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// get a test document</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-s">&quot;&lt;foo bar=&#39;baz&#39;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// print document to standard output (prints &lt;?xml version=&quot;1.0&quot;?&gt;&lt;foo bar=&quot;baz&quot;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;)</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_raw</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// print document to standard output as a regular node (prints &lt;foo bar=&quot;baz&quot;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;)</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_raw</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// print a subtree to standard output (prints &lt;call&gt;hey&lt;/call&gt;)</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;foo&quot;</span><span class="tok-p">).</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;call&quot;</span><span class="tok-p">).</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_raw</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="saving.options"><a class="anchor" href="#saving.options"></a><a class="link" href="#saving.options">7.5. Output options</a></h3> <div class="paragraph"> <p>All saving functions accept the optional parameter <code>flags</code>. This is a bitmask that customizes the output format; you can select the way the document nodes are printed and select the needed additional information that is output before the document contents.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> You should use the usual bitwise arithmetics to manipulate the bitmask: to enable a flag, use <code>mask | flag</code>; to disable a flag, use <code>mask &amp; ~flag</code>. </td> </tr> </table> </div> <div class="paragraph"> <p>These flags control the resulting tree contents:</p> </div> <div class="ulist"> <ul> <li> <p><a id="format_indent"></a><code>format_indent</code> determines if all nodes should be indented with the indentation string (this is an additional parameter for all saving functions, and is <code>"\t"</code> by default). If this flag is on, the indentation string is printed several times before every node, where the amount of indentation depends on the node&#8217;s depth relative to the output subtree. This flag has no effect if <a href="#format_raw">format_raw</a> is enabled. This flag is <strong>on</strong> by default.</p> </li> <li> <p><a id="format_indent_attributes"></a><code>format_indent_attributes</code> determines if all attributes should be printed on a new line, indented with the indentation string according to the attribute&#8217;s depth. This flag implies <a href="#format_indent">format_indent</a>. This flag has no effect if <a href="#format_raw">format_raw</a> is enabled. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_raw"></a><code>format_raw</code> switches between formatted and raw output. If this flag is on, the nodes are not indented in any way, and also no newlines that are not part of document text are printed. Raw mode can be used for serialization where the result is not intended to be read by humans; also it can be useful if the document was parsed with <a href="#parse_ws_pcdata">parse_ws_pcdata</a> flag, to preserve the original document formatting as much as possible. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_no_escapes"></a><code>format_no_escapes</code> disables output escaping for attribute values and PCDATA contents. If this flag is off, special symbols (<code>"</code>, <code>&amp;</code>, <code>&lt;</code>, <code>&gt;</code>) and all non-printable characters (those with codepoint values less than 32) are converted to XML escape sequences (i.e. <code>&amp;amp;</code>) during output. If this flag is on, no text processing is performed; therefore, output XML can be malformed if output contents contains invalid symbols (i.e. having a stray <code>&lt;</code> in the PCDATA will make the output malformed). This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_no_empty_element_tags"></a><code>format_no_empty_element_tags</code> determines if start/end tags should be output instead of empty element tags for empty elements (that is, elements with no children). This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_skip_control_chars"></a><code>format_skip_control_chars</code> enables skipping characters belonging to range [0; 32) instead of "&amp;#xNN;" encoding. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_attribute_single_quote"></a><code>format_attribute_single_quote</code> enables using single quotes <code>'</code> instead of double quotes <code>"</code> for enclosing attribute values. This flag is <strong>off</strong> by default.</p> </li> </ul> </div> <div class="paragraph"> <p>These flags control the additional output information:</p> </div> <div class="ulist"> <ul> <li> <p><a id="format_no_declaration"></a><code>format_no_declaration</code> disables default node declaration output. By default, if the document is saved via <code>save</code> or <code>save_file</code> function, and it does not have any document declaration, a default declaration is output before the document contents. Enabling this flag disables this declaration. This flag has no effect in <code>xml_node::print</code> functions: they never output the default declaration. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_write_bom"></a><code>format_write_bom</code> enables Byte Order Mark (BOM) output. By default, no BOM is output, so in case of non UTF-8 encodings the resulting document&#8217;s encoding may not be recognized by some parsers and text editors, if they do not implement sophisticated encoding detection. Enabling this flag adds an encoding-specific BOM to the output. This flag has no effect in <code>xml_node::print</code> functions: they never output the BOM. This flag is <strong>off</strong> by default.</p> </li> <li> <p><a id="format_save_file_text"></a><code>format_save_file_text</code> changes the file mode when using <code>save_file</code> function. By default, file is opened in binary mode, which means that the output file will contain platform-independent newline <code>\n</code> (ASCII 10). If this flag is on, file is opened in text mode, which on some systems changes the newline format (i.e. on Windows you can use this flag to output XML documents with <code>\r\n</code> (ASCII 13 10) newlines. This flag is <strong>off</strong> by default.</p> </li> </ul> </div> <div class="paragraph"> <p>Additionally, there is one predefined option mask:</p> </div> <div class="ulist"> <ul> <li> <p><a id="format_default"></a><code>format_default</code> is the default set of flags, i.e. it has all options set to their default values. It sets formatted output with indentation, without BOM and with default node declaration, if necessary.</p> </li> </ul> </div> <div class="paragraph"> <p>This is an example that shows the outputs of different output options (<a href="samples/save_options.cpp" class="bare">samples/save_options.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// get a test document</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-s">&quot;&lt;foo bar=&#39;baz&#39;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// default options; prints</span> <span class="tok-c1">// &lt;?xml version=&quot;1.0&quot;?&gt;</span> <span class="tok-c1">// &lt;foo bar=&quot;baz&quot;&gt;</span> <span class="tok-c1">// &lt;call&gt;hey&lt;/call&gt;</span> <span class="tok-c1">// &lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// default options with custom indentation string; prints</span> <span class="tok-c1">// &lt;?xml version=&quot;1.0&quot;?&gt;</span> <span class="tok-c1">// &lt;foo bar=&quot;baz&quot;&gt;</span> <span class="tok-c1">// --&lt;call&gt;hey&lt;/call&gt;</span> <span class="tok-c1">// &lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;--&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// default options without indentation; prints</span> <span class="tok-c1">// &lt;?xml version=&quot;1.0&quot;?&gt;</span> <span class="tok-c1">// &lt;foo bar=&quot;baz&quot;&gt;</span> <span class="tok-c1">// &lt;call&gt;hey&lt;/call&gt;</span> <span class="tok-c1">// &lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_default</span><span class="tok-w"> </span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-o">~</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_indent</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-c1">// can also pass &quot;&quot; instead of indentation string for the same effect</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// raw output; prints</span> <span class="tok-c1">// &lt;?xml version=&quot;1.0&quot;?&gt;&lt;foo bar=&quot;baz&quot;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_raw</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// raw output without declaration; prints</span> <span class="tok-c1">// &lt;foo bar=&quot;baz&quot;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_raw</span><span class="tok-w"> </span><span class="tok-o">|</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">format_no_declaration</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="saving.encoding"><a class="anchor" href="#saving.encoding"></a><a class="link" href="#saving.encoding">7.6. Encodings</a></h3> <div class="paragraph"> <p>pugixml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it&#8217;s a strict subset of UTF-16) and handles all encoding conversions during output. The output encoding is set via the <code>encoding</code> parameter of saving functions, which is of type <code>xml_encoding</code>. The possible values for the encoding are documented in <a href="#loading.encoding">Encodings</a>; the only flag that has a different meaning is <code>encoding_auto</code>.</p> </div> <div class="paragraph"> <p>While all other flags set the exact encoding, <code>encoding_auto</code> is meant for automatic encoding detection. The automatic detection does not make sense for output encoding, since there is usually nothing to infer the actual encoding from, so here <code>encoding_auto</code> means UTF-8 encoding, which is the most popular encoding for XML data storage. This is also the default value of output encoding; specify another value if you do not want UTF-8 encoded output.</p> </div> <div class="paragraph"> <p>Also note that wide stream saving functions do not have <code>encoding</code> argument and always assume <a href="#encoding_wchar">encoding_wchar</a> encoding.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> The current behavior for Unicode conversion is to skip all invalid UTF sequences during conversion. This behavior should not be relied upon; if your node/attribute names do not contain any valid UTF sequences, they may be output as if they are empty, which will result in malformed XML document. </td> </tr> </table> </div> </div> <div class="sect2"> <h3 id="saving.declaration"><a class="anchor" href="#saving.declaration"></a><a class="link" href="#saving.declaration">7.7. Customizing document declaration</a></h3> <div class="paragraph"> <p>When you are saving the document using <code>xml_document::save()</code> or <code>xml_document::save_file()</code>, a default XML document declaration is output, if <code>format_no_declaration</code> is not specified and if the document does not have a declaration node. However, the default declaration is not customizable. If you want to customize the declaration output, you need to create the declaration node yourself.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> By default the declaration node is not added to the document during parsing. If you just need to preserve the original declaration node, you have to add the flag <a href="#parse_declaration">parse_declaration</a> to the parsing flags; the resulting document will contain the original declaration node, which will be output during saving. </td> </tr> </table> </div> <div class="paragraph"> <p>Declaration node is a node with type <a href="#node_declaration">node_declaration</a>; it behaves like an element node in that it has attributes with values (but it does not have child nodes). Therefore setting custom version, encoding or standalone declaration involves adding attributes and setting attribute values.</p> </div> <div class="paragraph"> <p>This is an example that shows how to create a custom declaration node (<a href="samples/save_declaration.cpp" class="bare">samples/save_declaration.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// get a test document</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-s">&quot;&lt;foo bar=&#39;baz&#39;&gt;&lt;call&gt;hey&lt;/call&gt;&lt;/foo&gt;&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// add a custom declaration node</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">decl</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">prepend_child</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">node_declaration</span><span class="tok-p">);</span> <span class="tok-n">decl</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;1.0&quot;</span><span class="tok-p">;</span> <span class="tok-n">decl</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;encoding&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;UTF-8&quot;</span><span class="tok-p">;</span> <span class="tok-n">decl</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;standalone&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;no&quot;</span><span class="tok-p">;</span> <span class="tok-c1">// &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;</span> <span class="tok-c1">// &lt;foo bar=&quot;baz&quot;&gt;</span> <span class="tok-c1">// &lt;call&gt;hey&lt;/call&gt;</span> <span class="tok-c1">// &lt;/foo&gt;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="xpath"><a class="anchor" href="#xpath"></a><a class="link" href="#xpath">8. XPath</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>If the task at hand is to select a subset of document nodes that match some criteria, it is possible to code a function using the existing traversal functionality for any practical criteria. However, often either a data-driven approach is desirable, in case the criteria are not predefined and come from a file, or it is inconvenient to use traversal interfaces and a higher-level DSL is required. There is a standard language for XML processing, XPath, that can be useful for these cases. pugixml implements an almost complete subset of XPath 1.0. Because of differences in document object model and some performance implications, there are minor violations of the official specifications, which can be found in <a href="#xpath.w3c">Conformance to W3C specification</a>. The rest of this section describes the interface for XPath functionality. Please note that if you wish to learn to use XPath language, you have to look for other tutorials or manuals; for example, you can read <a href="https://www.w3schools.com/xml/xpath_intro.asp">W3Schools XPath tutorial</a> or <a href="https://www.w3.org/TR/xpath-10/">the XPath 1.0 specification</a>.</p> </div> <div class="sect2"> <h3 id="xpath.types"><a class="anchor" href="#xpath.types"></a><a class="link" href="#xpath.types">8.1. XPath types</a></h3> <div class="paragraph"> <p><a id="xpath_value_type"></a><a id="xpath_type_number"></a><a id="xpath_type_string"></a><a id="xpath_type_boolean"></a><a id="xpath_type_node_set"></a><a id="xpath_type_none"></a> Each XPath expression can have one of the following types: boolean, number, string or node set. Boolean type corresponds to <code>bool</code> type, number type corresponds to <code>double</code> type, string type corresponds to either <code>std::string</code> or <code>std::wstring</code>, depending on whether <a href="#dom.unicode">wide character interface is enabled</a>, and node set corresponds to <a href="#xpath_node_set">xpath_node_set</a> type. There is an enumeration, <code>xpath_value_type</code>, which can take the values <code>xpath_type_boolean</code>, <code>xpath_type_number</code>, <code>xpath_type_string</code> or <code>xpath_type_node_set</code>, accordingly.</p> </div> <div class="paragraph"> <p><a id="xpath_node"></a><a id="xpath_node::node"></a><a id="xpath_node::attribute"></a><a id="xpath_node::parent"></a> Because an XPath node can be either a node or an attribute, there is a special type, <code>xpath_node</code>, which is a discriminated union of these types. A value of this type contains two node handles, one of <code>xml_node</code> type, and another one of <code>xml_attribute</code> type; at most one of them can be non-null. The accessors to get these handles are available:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xpath_node::node</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-nf">xpath_node::attribute</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>XPath nodes can be null, in which case both accessors return null handles.</p> </div> <div class="paragraph"> <p>Note that as per XPath specification, each XPath node has a parent, which can be retrieved via this function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-nf">xpath_node::parent</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>parent</code> function returns the node&#8217;s parent if the XPath node corresponds to <code>xml_node</code> handle (equivalent to <code>node().parent()</code>), or the node to which the attribute belongs to, if the XPath node corresponds to <code>xml_attribute</code> handle. For null nodes, <code>parent</code> returns null handle.</p> </div> <div class="paragraph"> <p><a id="xpath_node::unspecified_bool_type"></a><a id="xpath_node::comparison"></a> Like node and attribute handles, XPath node handles can be implicitly cast to boolean-like object to check if it is a null node, and also can be compared for equality with each other.</p> </div> <div id="xpath_node::ctor" class="paragraph"> <p>You can also create XPath nodes with one of the three constructors: the default constructor, the constructor that takes node argument, and the constructor that takes attribute and node arguments (in which case the attribute must belong to the attribute list of the node). The constructor from <code>xml_node</code> is implicit, so you can usually pass <code>xml_node</code> to functions that expect <code>xpath_node</code>. Apart from that you usually don&#8217;t need to create your own XPath node objects, since they are returned to you via selection functions.</p> </div> <div id="xpath_node_set" class="paragraph"> <p>XPath expressions operate not on single nodes, but instead on node sets. A node set is a collection of nodes, which can be optionally ordered in either a forward document order or a reverse one. Document order is defined in XPath specification; an XPath node is before another node in document order if it appears before it in XML representation of the corresponding document.</p> </div> <div class="paragraph"> <p><a id="xpath_node_set::const_iterator"></a><a id="xpath_node_set::begin"></a><a id="xpath_node_set::end"></a> Node sets are represented by <code>xpath_node_set</code> object, which has an interface that resembles one of sequential random-access containers. It has an iterator type along with usual begin/past-the-end iterator accessors:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">::</span><span class="tok-n">const_iterator</span><span class="tok-p">;</span> <span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::begin</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::end</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="xpath_node_set::index"></a><a id="xpath_node_set::size"></a><a id="xpath_node_set::empty"></a> And it also can be iterated via indices, just like <code>std::vector</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">::</span><span class="tok-k">operator</span><span class="tok-p">[](</span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">index</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::size</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::empty</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>All of the above operations have the same semantics as that of <code>std::vector</code>: the iterators are random-access, all of the above operations are constant time, and accessing the element at index that is greater or equal than the set size results in undefined behavior. You can use both iterator-based and index-based access for iteration, however the iterator-based one can be faster.</p> </div> <div class="paragraph"> <p><a id="xpath_node_set::type"></a><a id="xpath_node_set::type_unsorted"></a><a id="xpath_node_set::type_sorted"></a><a id="xpath_node_set::type_sorted_reverse"></a><a id="xpath_node_set::sort"></a> The order of iteration depends on the order of nodes inside the set; the order can be queried via the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">enum</span><span class="tok-w"> </span><span class="tok-nc">xpath_node_set</span><span class="tok-o">::</span><span class="tok-n">type_t</span><span class="tok-w"> </span><span class="tok-p">{</span><span class="tok-n">type_unsorted</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">type_sorted</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">type_sorted_reverse</span><span class="tok-p">};</span> <span class="tok-n">type_t</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::type</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>type</code> function returns the current order of nodes; <code>type_sorted</code> means that the nodes are in forward document order, <code>type_sorted_reverse</code> means that the nodes are in reverse document order, and <code>type_unsorted</code> means that neither order is guaranteed (nodes can accidentally be in a sorted order even if <code>type()</code> returns <code>type_unsorted</code>). If you require a specific order of iteration, you can change it via <code>sort</code> function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::sort</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">reverse</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Calling <code>sort</code> sorts the nodes in either forward or reverse document order, depending on the argument; after this call <code>type()</code> will return <code>type_sorted</code> or <code>type_sorted_reverse</code>.</p> </div> <div id="xpath_node_set::first" class="paragraph"> <p>Often the actual iteration is not needed; instead, only the first element in document order is required. For this, a special accessor is provided:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-nf">xpath_node_set::first</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>This function returns the first node in forward document order from the set, or null node if the set is empty. Note that while the result of the node does not depend on the order of nodes in the set (i.e. on the result of <code>type()</code>), the complexity does - if the set is sorted, the complexity is constant, otherwise it is linear in the number of elements or worse.</p> </div> <div id="xpath_node_set::ctor" class="paragraph"> <p>While in the majority of cases the node set is returned by XPath functions, sometimes there is a need to manually construct a node set. For such cases, a constructor is provided which takes an iterator range (<code>const_iterator</code> is a typedef for <code>const xpath_node*</code>), and an optional type:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_node_set</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-p">(</span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">begin</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">end</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">type_t</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">type_unsorted</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The constructor copies the specified range and sets the specified type. The objects in the range are not checked in any way; you&#8217;ll have to ensure that the range contains no duplicates, and that the objects are sorted according to the <code>type</code> parameter. Otherwise XPath operations with this set may produce unexpected results.</p> </div> </div> <div class="sect2"> <h3 id="xpath.select"><a class="anchor" href="#xpath.select"></a><a class="link" href="#xpath.select">8.2. Selecting nodes via XPath expression</a></h3> <div class="paragraph"> <p><a id="xml_node::select_node"></a><a id="xml_node::select_nodes"></a> If you want to select nodes that match some XPath expression, you can do it with the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_node</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_nodes</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>select_nodes</code> function compiles the expression and then executes it with the node as a context node, and returns the resulting node set. <code>select_node</code> returns only the first node in document order from the result, and is equivalent to calling <code>select_nodes(query).first()</code>. If the XPath expression does not match anything, or the node handle is null, <code>select_nodes</code> returns an empty set, and <code>select_node</code> returns null XPath node.</p> </div> <div class="paragraph"> <p>If exception handling is not disabled, both functions throw <a href="#xpath_exception">xpath_exception</a> if the query can not be compiled or if it returns a value with type other than node set; see <a href="#xpath.errors">Error handling</a> for details.</p> </div> <div class="paragraph"> <p><a id="xml_node::select_node_precomp"></a><a id="xml_node::select_nodes_precomp"></a> While compiling expressions is fast, the compilation time can introduce a significant overhead if the same expression is used many times on small subtrees. If you&#8217;re doing many similar queries, consider compiling them into query objects (see <a href="#xpath.query">Using query objects</a> for further reference). Once you get a compiled query object, you can pass it to select functions instead of an expression string:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_node</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_nodes</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>If exception handling is not disabled, both functions throw <a href="#xpath_exception">xpath_exception</a> if the query returns a value with type other than node set.</p> </div> <div class="paragraph"> <p>This is an example of selecting nodes using XPath expressions (<a href="samples/xpath_select.cpp" class="bare">samples/xpath_select.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;/Profile/Tools/Tool[@AllowRemote=&#39;true&#39; and @DeriveCaptionFrom=&#39;lastparam&#39;]&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tools:</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-o">::</span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">it</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-o">*</span><span class="tok-n">it</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-n">build_tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_node</span><span class="tok-p">(</span><span class="tok-s">&quot;//Tool[contains(Description, &#39;build system&#39;)]&quot;</span><span class="tok-p">);</span> <span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">build_tool</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Build tool: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">build_tool</span><span class="tok-p">.</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="xpath.query"><a class="anchor" href="#xpath.query"></a><a class="link" href="#xpath.query">8.3. Using query objects</a></h3> <div id="xpath_query" class="paragraph"> <p>When you call <code>select_nodes</code> with an expression string as an argument, a query object is created behind the scenes. A query object represents a compiled XPath expression. Query objects can be needed in the following circumstances:</p> </div> <div class="ulist"> <ul> <li> <p>You can precompile expressions to query objects to save compilation time if it becomes an issue;</p> </li> <li> <p>You can use query objects to evaluate XPath expressions which result in booleans, numbers or strings;</p> </li> <li> <p>You can get the type of expression value via query object.</p> </li> </ul> </div> <div class="paragraph"> <p>Query objects correspond to <code>xpath_query</code> type. They are immutable and non-copyable: they are bound to the expression at creation time and can not be cloned. If you want to put query objects in a container, either allocate them on heap via <code>new</code> operator and store pointers to <code>xpath_query</code> in the container, or use a C11 compiler (query objects are movable in C11).</p> </div> <div id="xpath_query::ctor" class="paragraph"> <p>You can create a query object with the constructor that takes XPath expression as an argument:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">explicit</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">);</span></code></pre> </div> </div> <div id="xpath_query::return_type" class="paragraph"> <p>The expression is compiled and the compiled representation is stored in the new query object. If compilation fails, <a href="#xpath_exception">xpath_exception</a> is thrown if exception handling is not disabled (see <a href="#xpath.errors">Error handling</a> for details). After the query is created, you can query the type of the evaluation result using the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::return_type</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="xpath_query::evaluate_boolean"></a><a id="xpath_query::evaluate_number"></a><a id="xpath_query::evaluate_string"></a><a id="xpath_query::evaluate_node_set"></a><a id="xpath_query::evaluate_node"></a> You can evaluate the query using one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_boolean</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_number</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">string_t</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_string</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_node_set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_node</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>All functions take the context node as an argument, compute the expression and return the result, converted to the requested type. According to XPath specification, value of any type can be converted to boolean, number or string value, but no type other than node set can be converted to node set. Because of this, <code>evaluate_boolean</code>, <code>evaluate_number</code> and <code>evaluate_string</code> always return a result, but <code>evaluate_node_set</code> and <code>evaluate_node</code> result in an error if the return type is not node set (see <a href="#xpath.errors">Error handling</a>).</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> Calling <code>node.select_nodes("query")</code> is equivalent to calling <code>xpath_query("query").evaluate_node_set(node)</code>. Calling <code>node.select_node("query")</code> is equivalent to calling <code>xpath_query("query").evaluate_node(node)</code>. </td> </tr> </table> </div> <div id="xpath_query::evaluate_string_buffer" class="paragraph"> <p>Note that <code>evaluate_string</code> function returns the STL string; as such, it&#8217;s not available in <a href="#PUGIXML_NO_STL">PUGIXML_NO_STL</a> mode and also usually allocates memory. There is another string evaluation function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::evaluate_string</span><span class="tok-p">(</span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">capacity</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>This function evaluates the string, and then writes the result to <code>buffer</code> (but at most <code>capacity</code> characters); then it returns the full size of the result in characters, including the terminating zero. If <code>capacity</code> is not 0, the resulting buffer is always zero-terminated. You can use this function as follows:</p> </div> <div class="ulist"> <ul> <li> <p>First call the function with <code>buffer = 0</code> and <code>capacity = 0</code>; then allocate the returned amount of characters, and call the function again, passing the allocated storage and the amount of characters;</p> </li> <li> <p>First call the function with small buffer and buffer capacity; then, if the result is larger than the capacity, the output has been trimmed, so allocate a larger buffer and call the function again.</p> </li> </ul> </div> <div class="paragraph"> <p>This is an example of using query objects (<a href="samples/xpath_query.cpp" class="bare">samples/xpath_query.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// Select nodes via compiled query</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-w"> </span><span class="tok-n">query_remote_tools</span><span class="tok-p">(</span><span class="tok-s">&quot;/Profile/Tools/Tool[@AllowRemote=&#39;true&#39;]&quot;</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">query_remote_tools</span><span class="tok-p">.</span><span class="tok-n">evaluate_node_set</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Remote tool: &quot;</span><span class="tok-p">;</span> <span class="tok-n">tools</span><span class="tok-p">[</span><span class="tok-mi">2</span><span class="tok-p">].</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span> <span class="tok-c1">// Evaluate numbers via compiled query</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-w"> </span><span class="tok-n">query_timeouts</span><span class="tok-p">(</span><span class="tok-s">&quot;sum(//Tool/@Timeout)&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">query_timeouts</span><span class="tok-p">.</span><span class="tok-n">evaluate_number</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// Evaluate strings via compiled query for different context nodes</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-w"> </span><span class="tok-n">query_name_valid</span><span class="tok-p">(</span><span class="tok-s">&quot;string-length(substring-before(@Filename, &#39;_&#39;)) &gt; 0 and @OutputFileMasks&quot;</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-w"> </span><span class="tok-n">query_name</span><span class="tok-p">(</span><span class="tok-s">&quot;concat(substring-before(@Filename, &#39;_&#39;), &#39; produces &#39;, @OutputFileMasks)&quot;</span><span class="tok-p">);</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">first_element_by_path</span><span class="tok-p">(</span><span class="tok-s">&quot;Profile/Tools/Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">())</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><span class="tok-n">s</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">query_name</span><span class="tok-p">.</span><span class="tok-n">evaluate_string</span><span class="tok-p">(</span><span class="tok-n">tool</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">query_name_valid</span><span class="tok-p">.</span><span class="tok-n">evaluate_boolean</span><span class="tok-p">(</span><span class="tok-n">tool</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">s</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="xpath.variables"><a class="anchor" href="#xpath.variables"></a><a class="link" href="#xpath.variables">8.4. Using variables</a></h3> <div class="paragraph"> <p>XPath queries may contain references to variables; this is useful if you want to use queries that depend on some dynamic parameter without manually preparing the complete query string, or if you want to reuse the same query object for similar queries.</p> </div> <div class="paragraph"> <p>Variable references have the form <code>$name</code>; in order to use them, you have to provide a variable set, which includes all variables present in the query with correct types. This set is passed to <code>xpath_query</code> constructor or to <code>select_nodes</code>/<code>select_node</code> functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">explicit</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">);</span> <span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_node</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-nf">xml_node::select_nodes</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>If you&#8217;re using query objects, you can change the variable values before <code>evaluate</code>/<code>select</code> calls to change the query behavior.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> The variable set pointer is stored in the query object; you have to ensure that the lifetime of the set exceeds that of query object. </td> </tr> </table> </div> <div id="xpath_variable_set" class="paragraph"> <p>Variable sets correspond to <code>xpath_variable_set</code> type, which is essentially a variable container.</p> </div> <div id="xpath_variable_set::add" class="paragraph"> <p>You can add new variables with the following function:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::add</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The function tries to add a new variable with the specified name and type; if the variable with such name does not exist in the set, the function adds a new variable and returns the variable handle; if there is already a variable with the specified name, the function returns the variable handle if variable has the specified type. Otherwise the function returns null pointer; it also returns null pointer on allocation failure.</p> </div> <div class="paragraph"> <p>New variables are assigned the default value which depends on the type: <code>0</code> for numbers, <code>false</code> for booleans, empty string for strings and empty set for node sets.</p> </div> <div id="xpath_variable_set::get" class="paragraph"> <p>You can get the existing variables with the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::get</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::get</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>The functions return the variable handle, or null pointer if the variable with the specified name is not found.</p> </div> <div id="xpath_variable_set::set" class="paragraph"> <p>Additionally, there are the helper functions for setting the variable value by name; they try to add the variable with the corresponding type, if it does not exist, and to set the value. If the variable with the same name but with different type is already present, they return <code>false</code>; they also return <code>false</code> on allocation failure. Note that these functions do not perform any type conversions.</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable_set::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The variable values are copied to the internal variable storage, so you can modify or destroy them after the functions return.</p> </div> <div id="xpath_variable" class="paragraph"> <p>If setting variables by name is not efficient enough, or if you have to inspect variable information or get variable values, you can use variable handles. A variable corresponds to the <code>xpath_variable</code> type, and a variable handle is simply a pointer to <code>xpath_variable</code>.</p> </div> <div class="paragraph"> <p><a id="xpath_variable::type"></a><a id="xpath_variable::name"></a> In order to get variable information, you can use one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::type</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Note that each variable has a distinct type which is specified upon variable creation and can not be changed later.</p> </div> <div class="paragraph"> <p><a id="xpath_variable::get_boolean"></a><a id="xpath_variable::get_number"></a><a id="xpath_variable::get_string"></a><a id="xpath_variable::get_node_set"></a> In order to get variable value, you should use one of the following functions, depending on the variable type:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::get_boolean</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::get_number</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::get_string</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::get_node_set</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions return the value of the variable. Note that no type conversions are performed; if the type mismatch occurs, a dummy value is returned (<code>false</code> for booleans, <code>NaN</code> for numbers, empty string for strings and empty set for node sets).</p> </div> <div id="xpath_variable::set" class="paragraph"> <p>In order to set variable value, you should use one of the following functions, depending on the variable type:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::set</span><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::set</span><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">xpath_variable::set</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>These functions modify the variable value. Note that no type conversions are performed; if the type mismatch occurs, the functions return <code>false</code>; they also return <code>false</code> on allocation failure. The variable values are copied to the internal variable storage, so you can modify or destroy them after the functions return.</p> </div> <div class="paragraph"> <p>This is an example of using variables in XPath queries (<a href="samples/xpath_variables.cpp" class="bare">samples/xpath_variables.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// Select nodes via compiled query</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_variable_set</span><span class="tok-w"> </span><span class="tok-n">vars</span><span class="tok-p">;</span> <span class="tok-n">vars</span><span class="tok-p">.</span><span class="tok-n">add</span><span class="tok-p">(</span><span class="tok-s">&quot;remote&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_type_boolean</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_query</span><span class="tok-w"> </span><span class="tok-n">query_remote_tools</span><span class="tok-p">(</span><span class="tok-s">&quot;/Profile/Tools/Tool[@AllowRemote = string($remote)]&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-o">&amp;</span><span class="tok-n">vars</span><span class="tok-p">);</span> <span class="tok-n">vars</span><span class="tok-p">.</span><span class="tok-n">set</span><span class="tok-p">(</span><span class="tok-s">&quot;remote&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools_remote</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">query_remote_tools</span><span class="tok-p">.</span><span class="tok-n">evaluate_node_set</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">);</span> <span class="tok-n">vars</span><span class="tok-p">.</span><span class="tok-n">set</span><span class="tok-p">(</span><span class="tok-s">&quot;remote&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools_local</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">query_remote_tools</span><span class="tok-p">.</span><span class="tok-n">evaluate_node_set</span><span class="tok-p">(</span><span class="tok-n">doc</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Remote tool: &quot;</span><span class="tok-p">;</span> <span class="tok-n">tools_remote</span><span class="tok-p">[</span><span class="tok-mi">2</span><span class="tok-p">].</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Local tool: &quot;</span><span class="tok-p">;</span> <span class="tok-n">tools_local</span><span class="tok-p">[</span><span class="tok-mi">0</span><span class="tok-p">].</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span> <span class="tok-c1">// You can pass the context directly to select_nodes/select_node</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools_local_imm</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;/Profile/Tools/Tool[@AllowRemote = string($remote)]&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-o">&amp;</span><span class="tok-n">vars</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Local tool imm: &quot;</span><span class="tok-p">;</span> <span class="tok-n">tools_local_imm</span><span class="tok-p">[</span><span class="tok-mi">0</span><span class="tok-p">].</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">print</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="xpath.errors"><a class="anchor" href="#xpath.errors"></a><a class="link" href="#xpath.errors">8.5. Error handling</a></h3> <div class="paragraph"> <p>There are two different mechanisms for error handling in XPath implementation; the mechanism used depends on whether exception support is disabled (this is controlled with <a href="#PUGIXML_NO_EXCEPTIONS">PUGIXML_NO_EXCEPTIONS</a> define).</p> </div> <div class="paragraph"> <p><a id="xpath_exception"></a><a id="xpath_exception::result"></a><a id="xpath_exception::what"></a> By default, XPath functions throw <code>xpath_exception</code> object in case of errors; additionally, in the event any memory allocation fails, an <code>std::bad_alloc</code> exception is thrown. Also <code>xpath_exception</code> is thrown if the query is evaluated to a node set, but the return type is not node set. If the query constructor succeeds (i.e. no exception is thrown), the query object is valid. Otherwise you can get the error details via one of the following functions:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">xpath_exception::what</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-k">noexcept</span><span class="tok-p">;</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_parse_result</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-nf">xpath_exception::result</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><a id="xpath_query::unspecified_bool_type"></a><a id="xpath_query::result"></a> If exceptions are disabled, then in the event of parsing failure the query is initialized to invalid state; you can test if the query object is valid by using it in a boolean expression: <code>if (query) { &#8230;&#8203; }</code>. Additionally, you can get parsing result via the result() accessor:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_parse_result</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-nf">xpath_query::result</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Without exceptions, evaluating invalid query results in <code>false</code>, empty string, <code>NaN</code> or an empty node set, depending on the type; evaluating a query as a node set results in an empty node set if the return type is not node set.</p> </div> <div id="xpath_parse_result" class="paragraph"> <p>The information about parsing result is returned via <code>xpath_parse_result</code> object. It contains parsing status and the offset of last successfully parsed character from the beginning of the source stream:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">xpath_parse_result</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">error</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><span class="tok-n">offset</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-nf">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-p">};</span></code></pre> </div> </div> <div id="xpath_parse_result::error" class="paragraph"> <p>Parsing result is represented as the error message; it is either a null pointer, in case there is no error, or the error message in the form of ASCII zero-terminated string.</p> </div> <div id="xpath_parse_result::description" class="paragraph"> <p><code>description()</code> member function can be used to get the error message; it never returns the null pointer, so you can safely use <code>description()</code> even if query parsing succeeded. Note that <code>description()</code> returns a <code>char</code> string even in <code>PUGIXML_WCHAR_MODE</code>; you&#8217;ll have to call <a href="#as_wide">as_wide</a> to get the <code>wchar_t</code> string.</p> </div> <div id="xpath_parse_result::offset" class="paragraph"> <p>In addition to the error message, parsing result has an <code>offset</code> member, which contains the offset of last successfully parsed character. This offset is in units of <a href="#char_t">pugi::char_t</a> (bytes for character mode, wide characters for wide character mode).</p> </div> <div id="xpath_parse_result::bool" class="paragraph"> <p>Parsing result object can be implicitly converted to <code>bool</code> like this: <code>if (result) { &#8230;&#8203; } else { &#8230;&#8203; }</code>.</p> </div> <div class="paragraph"> <p>This is an example of XPath error handling (<a href="samples/xpath_error.cpp" class="bare">samples/xpath_error.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// Exception is thrown for incorrect query syntax</span> <span class="tok-k">try</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;//nodes[#true()]&quot;</span><span class="tok-p">);</span> <span class="tok-p">}</span> <span class="tok-k">catch</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_exception</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Select failed: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">.</span><span class="tok-n">what</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-c1">// Exception is thrown for incorrect query semantics</span> <span class="tok-k">try</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;(123)/next&quot;</span><span class="tok-p">);</span> <span class="tok-p">}</span> <span class="tok-k">catch</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_exception</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Select failed: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">.</span><span class="tok-n">what</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-c1">// Exception is thrown for query with incorrect return type</span> <span class="tok-k">try</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;123&quot;</span><span class="tok-p">);</span> <span class="tok-p">}</span> <span class="tok-k">catch</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_exception</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Select failed: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">e</span><span class="tok-p">.</span><span class="tok-n">what</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="xpath.w3c"><a class="anchor" href="#xpath.w3c"></a><a class="link" href="#xpath.w3c">8.6. Conformance to W3C specification</a></h3> <div class="paragraph"> <p>Because of the differences in document object models, performance considerations and implementation complexity, pugixml does not provide a fully conformant XPath 1.0 implementation. This is the current list of incompatibilities:</p> </div> <div class="ulist"> <ul> <li> <p>Consecutive text nodes sharing the same parent are not merged, i.e. in <code>&lt;node&gt;text1 &lt;![CDATA[data]]&gt; text2&lt;/node&gt;</code> node should have one text node child, but instead has three.</p> </li> <li> <p>Since the document type declaration is not used for parsing, <code>id()</code> function always returns an empty node set.</p> </li> <li> <p>Namespace nodes are not supported (affects <code>namespace::</code> axis).</p> </li> <li> <p>Name tests are performed on QNames in XML document instead of expanded names; for <code>&lt;foo xmlns:ns1='uri' xmlns:ns2='uri'&gt;&lt;ns1:child/&gt;&lt;ns2:child/&gt;&lt;/foo&gt;</code>, query <code>foo/ns1:*</code> will return only the first child, not both of them. Compliant XPath implementations can return both nodes if the user provides appropriate namespace declarations.</p> </li> <li> <p>String functions consider a character to be either a single <code>char</code> value or a single <code>wchar_t</code> value, depending on the library configuration; this means that some string functions are not fully Unicode-aware. This affects <code>substring()</code>, <code>string-length()</code> and <code>translate()</code> functions.</p> </li> </ul> </div> </div> </div> </div> <div class="sect1"> <h2 id="changes"><a class="anchor" href="#changes"></a><a class="link" href="#changes">9. Changelog</a></h2> <div class="sectionbody"> <div class="sect2"> <h3 id="v1.15"><a class="anchor" href="#v1.15"></a><a class="link" href="#v1.15">v1.15 <sup>2024-01-10</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Many <code>xml_attribute::</code> and <code>xml_node::</code> functions now transparently support <code>std::string_view</code> and <code>std::string</code> when C++17 support is detected.</p> </li> </ol> </div> </li> <li> <p>CMake improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Improve <code>pkg-config</code> file generation for NixOS</p> </li> <li> <p><code>PUGIXML_BUILD_APPLE_FRAMEWORK</code> CMake option can be used to build pugixml as <code>.xcframework</code></p> </li> <li> <p><code>PUGIXML_INSTALL</code> CMake option can be used to disable installation targets</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix clang/gcc warnings <code>-Wzero-as-null-pointer-constant</code>, <code>-Wuseless-cast</code>, <code>-Wshorten-64-to-32</code></p> </li> <li> <p>Fix unreferenced function warnings in <code>PUGIXML_NO_STL</code> configuration</p> </li> <li> <p>Fix CMake 3.31 deprecation warnings</p> </li> <li> <p>Stop using deprecated <code>throw()</code> when <code>noexcept</code> is available</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.14"><a class="anchor" href="#v1.14"></a><a class="link" href="#v1.14">v1.14 <sup>2023-10-01</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xml_attribute::set_name</code> and <code>xml_node::set_name</code> now have overloads that accept pointer to non-null-terminated string and size</p> </li> <li> <p>Implement <code>parse_merge_pcdata</code> parsing mode in which PCDATA contents is merged into a single node when original document had comments that were skipped during parsing</p> </li> <li> <p><code>xml_document::load_file</code> now returns a more consistent error status when given a path to a folder</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix assertion in XPath number&#8594;string conversion when using non-English locales</p> </li> <li> <p>Fix PUGIXML_STATIC_CRT CMake option to correctly select static CRT when using MSVC and recent CMake</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix GCC 2.95/3.3 builds</p> </li> <li> <p>Fix CMake 3.27 deprecation warnings</p> </li> <li> <p>Fix XCode 14 sprintf deprecation warning when compiling in C++03 mode</p> </li> <li> <p>Fix clang/gcc warnings <code>-Wweak-vtables</code>, <code>-Wreserved-macro-identifier</code></p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.13"><a class="anchor" href="#v1.13"></a><a class="link" href="#v1.13">v1.13 <sup>2022-11-01</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xml_attribute::set_value</code>, <code>xml_node::set_value</code> and <code>xml_text::set</code> now have overloads that accept pointer to non-null-terminated string and size</p> </li> <li> <p>Improve performance of tree traversal when using compact mode (<code>PUGIXML_COMPACT</code>)</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix error handling in <code>xml_document::save_file</code> that could result in the function succeeding while running out of disk space</p> </li> <li> <p>Fix memory leak during error handling of some out-of-memory conditions during <code>xml_document::load</code></p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix exported symbols in CMake DLL builds when using CMake</p> </li> <li> <p>Fix exported symbols in CMake shared object builds when using -fvisibility=hidden</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.12"><a class="anchor" href="#v1.12"></a><a class="link" href="#v1.12">v1.12 <sup>2022-02-09</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix a bug in xml_document move construction when the source of the move is empty</p> </li> <li> <p>Fix const-correctness issues with iterator objects to support C++20 ranges</p> </li> </ol> </div> </li> <li> <p>XPath improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Improved detection of overly complex queries that may result in stack overflow during parsing</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix Cygwin support for DLL builds</p> </li> <li> <p>Fix Windows CE support</p> </li> <li> <p>Add NuGet builds and project files for VS2022</p> </li> </ol> </div> </li> <li> <p>Build system changes</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>All CMake options now have the prefix <code>PUGIXML_</code>. This may require changing dependent build configurations.</p> </li> <li> <p>Many build settings are now exposed via CMake settings, most notably <code>PUGIXML_COMPACT</code> and <code>PUGIXML_WCHAR_MODE</code> can be set without changing <code>pugiconfig.hpp</code></p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.11"><a class="anchor" href="#v1.11"></a><a class="link" href="#v1.11">v1.11 <sup>2020-11-26</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Add xml_node::remove_attributes and xml_node::remove_children</p> </li> <li> <p>Add a way to customize floating point precision via xml_attribute::set and xml_text::set overloads</p> </li> </ol> </div> </li> <li> <p>XPath improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>XPath parser now limits recursion depth which prevents stack overflow on malicious queries</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix Visual Studio warnings when built using clang-cl compiler</p> </li> <li> <p>Fix Wconversion warnings in gcc</p> </li> <li> <p>Fix Wzero-as-null-pointer-constant warnings in pugixml.hpp</p> </li> <li> <p>Work around several static analysis false positives</p> </li> </ol> </div> </li> <li> <p>Build system changes</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>The CMake package for pugixml now provides a <code>pugixml::pugixml</code> target rather than a <code>pugixml</code> target. A compatibility <code>pugixml</code> target is provided if at least version 1.11 is not requested.</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.10"><a class="anchor" href="#v1.10"></a><a class="link" href="#v1.10">v1.10 <sup>2019-09-15</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Behavior changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Tab characters (ASCII 9) in attribute values are now encoded as '&amp;#9;' to survive roundtripping</p> </li> <li> <p><code>&gt;</code> characters are no longer escaped in attribute values</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Add Visual Studio .natvis files to improve debugging experience</p> </li> <li> <p>CMake improvements (USE_POSTFIX and BUILD_SHARED_AND_STATIC_LIBS options for building multiple versions and pkg-config tweaks)</p> </li> <li> <p>Add format_skip_control_chars formatting flag to skip non-printable ASCII characters that are invalid to use in well-formed XML files</p> </li> <li> <p>Add format_attribute_single_quote formatting flag to use single quotes for attribute values instead of default double quotes.</p> </li> </ol> </div> </li> <li> <p>XPath improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>XPath union now results in a stable order that doesn&#8217;t depend on memory allocations; crucially, this may require sorting the output of XPath query operation if you rely on the document-ordered traversal</p> </li> <li> <p>Improve performance of XPath union operation, making it ~2x faster</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix Visual Studio warnings when built in a DLL configuration</p> </li> <li> <p>Fix static analysis false positives in Coverity and clang</p> </li> <li> <p>Fix Wdouble-promotion warnings in gcc</p> </li> <li> <p>Add Visual Studio 2019 support for NuGet packages</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.9"><a class="anchor" href="#v1.9"></a><a class="link" href="#v1.9">v1.9 <sup>2018-04-04</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xml_document::load(const char*)</code> (deprecated in 1.5) now has <code>deprecated</code> attribute; use <code>xml_document::load_string</code> instead</p> </li> <li> <p><code>xml_node::select_single_node</code> (deprecated in 1.5) now has <code>deprecated</code> attribute; use <code>xml_node::select_node</code> instead</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Add move semantics support for xml_document and improve move semantics support for other objects</p> </li> <li> <p>CMake build now exports include directories</p> </li> <li> <p>CMake build with BUILD_SHARED_LIBS=ON now uses dllexport attribute for MSVC</p> </li> </ol> </div> </li> <li> <p>XPath improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Rework parser/evaluator to not rely on exceptional control flow; longjmp is no longer used when exceptions are disabled</p> </li> <li> <p>Improve error messages for certain invalid expressions such as <code>.[1]</code> or <code>(1</code></p> </li> <li> <p>Minor performance improvements</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix Texas Instruments compiler warnings</p> </li> <li> <p>Fix compilation issues with limits.h for some versions of gcc</p> </li> <li> <p>Fix compilation issues with Clang/C2</p> </li> <li> <p>Fix implicit fallthrough warnings in gcc 7</p> </li> <li> <p>Fix unknown attribute directive warnings in gcc 8</p> </li> <li> <p>Fix cray++ compiler errors</p> </li> <li> <p>Fix unsigned integer overflow errors with -fsanitize=integer</p> </li> <li> <p>Fix undefined behavior sanitizer issues in compact mode</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.8"><a class="anchor" href="#v1.8"></a><a class="link" href="#v1.8">v1.8 <sup>2016-11-24</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>When printing empty elements, a space is no longer added before / in format_raw mode</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added parse_embed_pcdata parsing mode in which PCDATA value is stored in the element node if possible (significantly reducing memory consumption for some documents)</p> </li> <li> <p>Added auto-detection support for Latin-1 (ISO-8859-1) encoding during parsing</p> </li> <li> <p>Added format_no_empty_element_tags formatting flag that outputs start/end tags instead of empty element tags for empty elements</p> </li> </ol> </div> </li> <li> <p>Performance improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Minor memory allocation improvements (yielding up to 1% memory savings in some cases)</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed compilation issues for Borland C++ 5.4</p> </li> <li> <p>Fixed compilation issues for some distributions of MinGW 3.8</p> </li> <li> <p>Fixed various Clang/GCC warnings</p> </li> <li> <p>Enabled move semantics support for XPath objects for MSVC 2010 and above</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.7"><a class="anchor" href="#v1.7"></a><a class="link" href="#v1.7">v1.7 <sup>2015-10-19</sup></a></h3> <div class="paragraph"> <p>Major release, featuring performance and memory improvements along with some new features. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Compact mode:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Introduced a new tree storage mode that takes significantly less memory (2-5x smaller DOM) at some performance cost.</p> </li> <li> <p>The mode can be enabled using <code>PUGIXML_COMPACT</code> define.</p> </li> </ol> </div> </li> <li> <p>New integer parsing/formatting implementation:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Functions that convert from and to integers (e.g. <code>as_int</code>/<code>set_value</code>) do not rely on CRT any more.</p> </li> <li> <p>New implementation is 3-5x faster and is always correct wrt overflow or underflow. This is a behavior change - where previously <code>as_uint()</code> would return UINT_MAX on a value "-1", it now returns 0.</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>XPath objects (<code>xpath_query</code>, <code>xpath_node_set</code>, <code>xpath_variable_set</code>) are now movable if your compiler supports C++11. Additionally, <code>xpath_variable_set</code> is copyable.</p> </li> <li> <p>Added <code>format_indent_attributes</code> that makes the resulting XML friendlier to line diff/merge tools.</p> </li> <li> <p>Added a variant of <code>xml_node::attribute</code> function with a hint that can improve lookup performance.</p> </li> <li> <p>Custom allocation functions are now allowed (but not required) to throw instead of returning a null pointer.</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fix Clang 3.7 crashes in out-of-memory cases (C++ DR 1748)</p> </li> <li> <p>Fix XPath crashes on SPARC64 (and other 32-bit architectures where doubles have to be aligned to 8 bytes)</p> </li> <li> <p>Fix xpath_node_set assignment to provide strong exception guarantee</p> </li> <li> <p>Fix saving for custom xml_writer implementations that can throw from write()</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.6"><a class="anchor" href="#v1.6"></a><a class="link" href="#v1.6">v1.6 <sup>2015-04-10</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Attribute/text values now use more digits when printing floating point numbers to guarantee round-tripping.</p> </li> <li> <p>Text nodes no longer get extra surrounding whitespace when pretty-printing nodes with mixed contents</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed translate and normalize-space XPath functions to no longer return internal NUL characters</p> </li> <li> <p>Fixed buffer overrun on malformed comments inside DOCTYPE sections</p> </li> <li> <p>DOCTYPE parsing can no longer run out of stack space on malformed inputs (XML parsing is now using bounded stack space)</p> </li> <li> <p>Adjusted processing instruction output to avoid malformed documents if the PI value contains <code>?&gt;</code></p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.5"><a class="anchor" href="#v1.5"></a><a class="link" href="#v1.5">v1.5 <sup>2014-11-27</sup></a></h3> <div class="paragraph"> <p>Major release, featuring a lot of performance improvements and some new features.</p> </div> <div class="ulist"> <ul> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xml_document::load(const char_t*)</code> was renamed to <code>load_string</code>; the old method is still available and will be deprecated in a future release</p> </li> <li> <p><code>xml_node::select_single_node</code> was renamed to <code>select_node</code>; the old method is still available and will be deprecated in a future release.</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added <code>xml_node::append_move</code> and other functions for moving nodes within a document</p> </li> <li> <p>Added <code>xpath_query::evaluate_node</code> for evaluating queries with a single node as a result</p> </li> </ol> </div> </li> <li> <p>Performance improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Optimized XML parsing (10-40% faster with clang/gcc, up to 10% faster with MSVC)</p> </li> <li> <p>Optimized memory consumption when copying nodes in the same document (string contents is now shared)</p> </li> <li> <p>Optimized node copying (10% faster for cross-document copies, 3x faster for inter-document copies; also it now consumes a constant amount of stack space)</p> </li> <li> <p>Optimized node output (60% faster; also it now consumes a constant amount of stack space)</p> </li> <li> <p>Optimized XPath allocation (query evaluation now results in fewer temporary allocations)</p> </li> <li> <p>Optimized XPath sorting (node set sorting is 2-3x faster in some cases)</p> </li> <li> <p>Optimized XPath evaluation (XPathMark suite is 100x faster; some commonly used queries are 3-4x faster)</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed <code>xml_node::offset_debug</code> for corner cases</p> </li> <li> <p>Fixed undefined behavior while calling memcpy in some cases</p> </li> <li> <p>Fixed MSVC 2015 compilation warnings</p> </li> <li> <p>Fixed <code>contrib/foreach.hpp</code> for Boost 1.56.0</p> </li> </ol> </div> </li> <li> <p>Bug fixes</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Adjusted comment output to avoid malformed documents if the comment value contains <code>--</code></p> </li> <li> <p>Fix XPath sorting for documents that were constructed using append_buffer</p> </li> <li> <p>Fix <code>load_file</code> for wide-character paths with non-ASCII characters in MinGW with C&#43;&#43;11 mode enabled</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.4"><a class="anchor" href="#v1.4"></a><a class="link" href="#v1.4">v1.4 <sup>2014-02-27</sup></a></h3> <div class="paragraph"> <p>Major release, featuring various new features, bug fixes and compatibility improvements.</p> </div> <div class="ulist"> <ul> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Documents without element nodes are now rejected with <code>status_no_document_element</code> error, unless <code>parse_fragment</code> option is used</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added XML fragment parsing (<code>parse_fragment</code> flag)</p> </li> <li> <p>Added PCDATA whitespace trimming (<code>parse_trim_pcdata</code> flag)</p> </li> <li> <p>Added long long support for <code>xml_attribute</code> and <code>xml_text</code> (<code>as_llong</code>, <code>as_ullong</code> and <code>set_value</code>/<code>set</code> overloads)</p> </li> <li> <p>Added hexadecimal integer parsing support for <code>as_int</code>/<code>as_uint</code>/<code>as_llong</code>/<code>as_ullong</code></p> </li> <li> <p>Added <code>xml_node::append_buffer</code> to improve performance of assembling documents from fragments</p> </li> <li> <p><code>xml_named_node_iterator</code> is now bidirectional</p> </li> <li> <p>Reduced XPath stack consumption during compilation and evaluation (useful for embedded systems)</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Improved support for platforms without wchar_t support</p> </li> <li> <p>Fixed several false positives in clang static analysis</p> </li> <li> <p>Fixed several compilation warnings for various GCC versions</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed undefined pointer arithmetic in XPath implementation</p> </li> <li> <p>Fixed non-seekable iostream support for certain stream types, i.e. Boost <code>file_source</code> with pipe input</p> </li> <li> <p>Fixed <code>xpath_query::return_type</code> for some expressions</p> </li> <li> <p>Fixed dllexport issues with <code>xml_named_node_iterator</code></p> </li> <li> <p>Fixed <code>find_child_by_attribute</code> assertion for attributes with null name/value</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.2"><a class="anchor" href="#v1.2"></a><a class="link" href="#v1.2">v1.2 <sup>2012-05-01</sup></a></h3> <div class="paragraph"> <p>Major release, featuring header-only mode, various interface enhancements (i.e. PCDATA manipulation and C&#43;&#43;11 iteration), many other features and compatibility improvements.</p> </div> <div class="ulist"> <ul> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added <code>xml_text</code> helper class for working with PCDATA/CDATA contents of an element node</p> </li> <li> <p>Added optional header-only mode (controlled by <code>PUGIXML_HEADER_ONLY</code> define)</p> </li> <li> <p>Added <code>xml_node::children()</code> and <code>xml_node::attributes()</code> for C&#43;&#43;11 ranged for loop or <code>BOOST_FOREACH</code></p> </li> <li> <p>Added support for Latin-1 (ISO-8859-1) encoding conversion during loading and saving</p> </li> <li> <p>Added custom default values for <code>xml_attribute::as_*</code> (they are returned if the attribute does not exist)</p> </li> <li> <p>Added <code>parse_ws_pcdata_single</code> flag for preserving whitespace-only PCDATA in case it&#8217;s the only child</p> </li> <li> <p>Added <code>format_save_file_text</code> for <code>xml_document::save_file</code> to open files as text instead of binary (changes newlines on Windows)</p> </li> <li> <p>Added <code>format_no_escapes</code> flag to disable special symbol escaping (complements <code>~parse_escapes</code>)</p> </li> <li> <p>Added support for loading document from streams that do not support seeking</p> </li> <li> <p>Added <code>PUGIXML_MEMORY_*</code> constants for tweaking allocation behavior (useful for embedded systems)</p> </li> <li> <p>Added <code>PUGIXML_VERSION</code> preprocessor define</p> </li> </ol> </div> </li> <li> <p>Compatibility improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Parser does not require setjmp support (improves compatibility with some embedded platforms, enables <code>/clr:pure</code> compilation)</p> </li> <li> <p>STL forward declarations are no longer used (fixes SunCC/RWSTL compilation, fixes clang compilation in C&#43;&#43;11 mode)</p> </li> <li> <p>Fixed AirPlay SDK, Android, Windows Mobile (WinCE) and C&#43;&#43;/CLI compilation</p> </li> <li> <p>Fixed several compilation warnings for various GCC versions, Intel C&#43;&#43; compiler and Clang</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed unsafe bool conversion to avoid problems on C&#43;&#43;/CLI</p> </li> <li> <p>Iterator dereference operator is const now (fixes Boost <code>filter_iterator</code> support)</p> </li> <li> <p><code>xml_document::save_file</code> now checks for file I/O errors during saving</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v1.0"><a class="anchor" href="#v1.0"></a><a class="link" href="#v1.0">v1.0 <sup>2010-11-01</sup></a></h3> <div class="paragraph"> <p>Major release, featuring many XPath enhancements, wide character filename support, miscellaneous performance improvements, bug fixes and more.</p> </div> <div class="ulist"> <ul> <li> <p>XPath:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>XPath implementation is moved to <code>pugixml.cpp</code> (which is the only source file now); use <code>PUGIXML_NO_XPATH</code> if you want to disable XPath to reduce code size</p> </li> <li> <p>XPath is now supported without exceptions (<code>PUGIXML_NO_EXCEPTIONS</code>); the error handling mechanism depends on the presence of exception support</p> </li> <li> <p>XPath is now supported without STL (<code>PUGIXML_NO_STL</code>)</p> </li> <li> <p>Introduced variable support</p> </li> <li> <p>Introduced new <code>xpath_query::evaluate_string</code>, which works without STL</p> </li> <li> <p>Introduced new <code>xpath_node_set</code> constructor (from an iterator range)</p> </li> <li> <p>Evaluation function now accept attribute context nodes</p> </li> <li> <p>All internal allocations use custom allocation functions</p> </li> <li> <p>Improved error reporting; now a last parsed offset is returned together with the parsing error</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed memory leak for loading from streams with stream exceptions turned on</p> </li> <li> <p>Fixed custom deallocation function calling with null pointer in one case</p> </li> <li> <p>Fixed missing attributes for iterator category functions; all functions/classes can now be DLL-exported</p> </li> <li> <p>Worked around Digital Mars compiler bug, which lead to minor read overfetches in several functions</p> </li> <li> <p><code>load_file</code> now works with 2+ Gb files in MSVC/MinGW</p> </li> <li> <p>XPath: fixed memory leaks for incorrect queries</p> </li> <li> <p>XPath: fixed <code>xpath_node()</code> attribute constructor with empty attribute argument</p> </li> <li> <p>XPath: fixed <code>lang()</code> function for non-ASCII arguments</p> </li> </ol> </div> </li> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>CDATA nodes containing <code>]]&gt;</code> are printed as several nodes; while this changes the internal structure, this is the only way to escape CDATA contents</p> </li> <li> <p>Memory allocation errors during parsing now preserve last parsed offset (to give an idea about parsing progress)</p> </li> <li> <p>If an element node has the only child, and it is of CDATA type, then the extra indentation is omitted (previously this behavior only held for PCDATA children)</p> </li> </ol> </div> </li> <li> <p>Additional functionality:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added <code>xml_parse_result</code> default constructor</p> </li> <li> <p>Added <code>xml_document::load_file</code> and <code>xml_document::save_file</code> with wide character paths</p> </li> <li> <p>Added <code>as_utf8</code> and <code>as_wide</code> overloads for <code>std::wstring</code>/<code>std::string</code> arguments</p> </li> <li> <p>Added DOCTYPE node type (<code>node_doctype</code>) and a special parse flag, <code>parse_doctype</code>, to add such nodes to the document during parsing</p> </li> <li> <p>Added <code>parse_full</code> parse flag mask, which extends <code>parse_default</code> with all node type parsing flags except <code>parse_ws_pcdata</code></p> </li> <li> <p>Added <code>xml_node::hash_value()</code> and <code>xml_attribute::hash_value()</code> functions for use in hash-based containers</p> </li> <li> <p>Added <code>internal_object()</code> and additional constructor for both <code>xml_node</code> and <code>xml_attribute</code> for easier marshalling (useful for language bindings)</p> </li> <li> <p>Added <code>xml_document::document_element()</code> function</p> </li> <li> <p>Added <code>xml_node::prepend_attribute</code>, <code>xml_node::prepend_child</code> and <code>xml_node::prepend_copy</code> functions</p> </li> <li> <p>Added <code>xml_node::append_child</code>, <code>xml_node::prepend_child</code>, <code>xml_node::insert_child_before</code> and <code>xml_node::insert_child_after</code> overloads for element nodes (with name instead of type)</p> </li> <li> <p>Added <code>xml_document::reset()</code> function</p> </li> </ol> </div> </li> <li> <p>Performance improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xml_node::root()</code> and <code>xml_node::offset_debug()</code> are now O(1) instead of O(logN)</p> </li> <li> <p>Minor parsing optimizations</p> </li> <li> <p>Minor memory optimization for strings in DOM tree (<code>set_name</code>/<code>set_value</code>)</p> </li> <li> <p>Memory optimization for string memory reclaiming in DOM tree (<code>set_name</code>/<code>set_value</code> now reallocate the buffer if memory waste is too big)</p> </li> <li> <p>XPath: optimized document order sorting</p> </li> <li> <p>XPath: optimized child/attribute axis step</p> </li> <li> <p>XPath: optimized number-to-string conversions in MSVC</p> </li> <li> <p>XPath: optimized concat for many arguments</p> </li> <li> <p>XPath: optimized evaluation allocation mechanism: constant and document strings are not heap-allocated</p> </li> <li> <p>XPath: optimized evaluation allocation mechanism: all temporaries' allocations use fast stack-like allocator</p> </li> </ol> </div> </li> <li> <p>Compatibility:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Removed wildcard functions (<code>xml_node::child_w</code>, <code>xml_node::attribute_w</code>, etc.)</p> </li> <li> <p>Removed <code>xml_node::all_elements_by_name</code></p> </li> <li> <p>Removed <code>xpath_type_t</code> enumeration; use <code>xpath_value_type</code> instead</p> </li> <li> <p>Removed <code>format_write_bom_utf8</code> enumeration; use <code>format_write_bom</code> instead</p> </li> <li> <p>Removed <code>xml_document::precompute_document_order</code>, <code>xml_attribute::document_order</code> and <code>xml_node::document_order</code> functions; document order sort optimization is now automatic</p> </li> <li> <p>Removed <code>xml_document::parse</code> functions and <code>transfer_ownership</code> struct; use <code>xml_document::load_buffer_inplace</code> and <code>xml_document::load_buffer_inplace_own</code> instead</p> </li> <li> <p>Removed <code>as_utf16</code> function; use <code>as_wide</code> instead</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.9"><a class="anchor" href="#v0.9"></a><a class="link" href="#v0.9">v0.9 <sup>2010-07-01</sup></a></h3> <div class="paragraph"> <p>Major release, featuring extended and improved Unicode support, miscellaneous performance improvements, bug fixes and more.</p> </div> <div class="ulist"> <ul> <li> <p>Major Unicode improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Introduced encoding support (automatic/manual encoding detection on load, manual encoding selection on save, conversion from/to UTF8, UTF16 LE/BE, UTF32 LE/BE)</p> </li> <li> <p>Introduced <code>wchar_t</code> mode (you can set <code>PUGIXML_WCHAR_MODE</code> define to switch pugixml internal encoding from UTF8 to <code>wchar_t</code>; all functions are switched to their Unicode variants)</p> </li> <li> <p>Load/save functions now support wide streams</p> </li> </ol> </div> </li> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed document corruption on failed parsing bug</p> </li> <li> <p>XPath string/number conversion improvements (increased precision, fixed crash for huge numbers)</p> </li> <li> <p>Improved DOCTYPE parsing: now parser recognizes all well-formed DOCTYPE declarations</p> </li> <li> <p>Fixed <code>xml_attribute::as_uint()</code> for large numbers (i.e. 2<sup>32</sup>-1)</p> </li> <li> <p>Fixed <code>xml_node::first_element_by_path</code> for path components that are prefixes of node names, but are not exactly equal to them.</p> </li> </ol> </div> </li> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>parse()</code> API changed to <code>load_buffer</code>/<code>load_buffer_inplace</code>/<code>load_buffer_inplace_own</code>; <code>load_buffer</code> APIs do not require zero-terminated strings.</p> </li> <li> <p>Renamed <code>as_utf16</code> to <code>as_wide</code></p> </li> <li> <p>Changed <code>xml_node::offset_debug</code> return type and <code>xml_parse_result::offset</code> type to <code>ptrdiff_t</code></p> </li> <li> <p>Nodes/attributes with empty names are now printed as <code>:anonymous</code></p> </li> </ol> </div> </li> <li> <p>Performance improvements:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Optimized document parsing and saving</p> </li> <li> <p>Changed internal memory management: internal allocator is used for both metadata and name/value data; allocated pages are deleted if all allocations from them are deleted</p> </li> <li> <p>Optimized memory consumption: <code>sizeof(xml_node_struct)</code> reduced from 40 bytes to 32 bytes on x86</p> </li> <li> <p>Optimized debug mode parsing/saving by order of magnitude</p> </li> </ol> </div> </li> <li> <p>Miscellaneous:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>All STL includes except <code>&lt;exception&gt;</code> in <code>pugixml.hpp</code> are replaced with forward declarations</p> </li> <li> <p><code>xml_node::remove_child</code> and <code>xml_node::remove_attribute</code> now return the operation result</p> </li> </ol> </div> </li> <li> <p>Compatibility:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>parse()</code> and <code>as_utf16</code> are left for compatibility (these functions are deprecated and will be removed in version 1.0)</p> </li> <li> <p>Wildcard functions, <code>document_order</code>/<code>precompute_document_order</code> functions, <code>all_elements_by_name</code> function and <code>format_write_bom_utf8</code> flag are deprecated and will be removed in version 1.0</p> </li> <li> <p><code>xpath_type_t</code> enumeration was renamed to <code>xpath_value_type</code>; <code>xpath_type_t</code> is deprecated and will be removed in version 1.0</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.5"><a class="anchor" href="#v0.5"></a><a class="link" href="#v0.5">v0.5 <sup>2009-11-08</sup></a></h3> <div class="paragraph"> <p>Major bugfix release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>XPath bugfixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed <code>translate()</code>, <code>lang()</code> and <code>concat()</code> functions (infinite loops/crashes)</p> </li> <li> <p>Fixed compilation of queries with empty literal strings (<code>""</code>)</p> </li> <li> <p>Fixed axis tests: they never add empty nodes/attributes to the resulting node set now</p> </li> <li> <p>Fixed string-value evaluation for node-set (the result excluded some text descendants)</p> </li> <li> <p>Fixed <code>self::</code> axis (it behaved like <code>ancestor-or-self::</code>)</p> </li> <li> <p>Fixed <code>following::</code> and <code>preceding::</code> axes (they included descendent and ancestor nodes, respectively)</p> </li> <li> <p>Minor fix for <code>namespace-uri()</code> function (namespace declaration scope includes the parent element of namespace declaration attribute)</p> </li> <li> <p>Some incorrect queries are no longer parsed now (i.e. <code>foo: *</code>)</p> </li> <li> <p>Fixed <code>text()</code>/etc. node test parsing bug (i.e. <code>foo[text()]</code> failed to compile)</p> </li> <li> <p>Fixed root step (<code>/</code>) - it now selects empty node set if query is evaluated on empty node</p> </li> <li> <p>Fixed string to number conversion (<code>"123 "</code> converted to NaN, <code>"123 .456"</code> converted to 123.456 - now the results are 123 and NaN, respectively)</p> </li> <li> <p>Node set copying now preserves sorted type; leads to better performance on some queries</p> </li> </ol> </div> </li> <li> <p>Miscellaneous bugfixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed <code>xml_node::offset_debug</code> for PI nodes</p> </li> <li> <p>Added empty attribute checks to <code>xml_node::remove_attribute</code></p> </li> <li> <p>Fixed <code>node_pi</code> and <code>node_declaration</code> copying</p> </li> <li> <p>Const-correctness fixes</p> </li> </ol> </div> </li> <li> <p>Specification changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>xpath_node::select_nodes()</code> and related functions now throw exception if expression return type is not node set (instead of assertion)</p> </li> <li> <p><code>xml_node::traverse()</code> now sets depth to -1 for both <code>begin()</code> and <code>end()</code> callbacks (was 0 at <code>begin()</code> and -1 at <code>end()</code>)</p> </li> <li> <p>In case of non-raw node printing a newline is output after PCDATA inside nodes if the PCDATA has siblings</p> </li> <li> <p>UTF8 &#8594; <code>wchar_t</code> conversion now considers 5-byte UTF8-like sequences as invalid</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added <code>xpath_node_set::operator[]</code> for index-based iteration</p> </li> <li> <p>Added <code>xpath_query::return_type()</code></p> </li> <li> <p>Added getter accessors for memory-management functions</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.42"><a class="anchor" href="#v0.42"></a><a class="link" href="#v0.42">v0.42 <sup>2009-09-17</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed deallocation in case of custom allocation functions or if <code>delete[]</code> / <code>free</code> are incompatible</p> </li> <li> <p>XPath parser fixed for incorrect queries (i.e. incorrect XPath queries should now always fail to compile)</p> </li> <li> <p>Const-correctness fixes for <code>find_child_by_attribute</code></p> </li> <li> <p>Improved compatibility (miscellaneous warning fixes, fixed <code>&lt;cstring&gt;</code> include dependency for GCC)</p> </li> <li> <p>Fixed iterator begin/end and print function to work correctly for empty nodes</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added <code>PUGIXML_API</code>/<code>PUGIXML_CLASS</code>/<code>PUGIXML_FUNCTION</code> configuration macros to control class/function attributes</p> </li> <li> <p>Added <code>xml_attribute::set_value</code> overloads for different types</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.41"><a class="anchor" href="#v0.41"></a><a class="link" href="#v0.41">v0.41 <sup>2009-02-08</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed bug with node printing (occasionally some content was not written to output stream)</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.4"><a class="anchor" href="#v0.4"></a><a class="link" href="#v0.4">v0.4 <sup>2009-01-18</sup></a></h3> <div class="paragraph"> <p>Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Documentation fix in samples for <code>parse()</code> with manual lifetime control</p> </li> <li> <p>Fixed document order sorting in XPath (it caused wrong order of nodes after <code>xpath_node_set::sort</code> and wrong results of some XPath queries)</p> </li> </ol> </div> </li> <li> <p>Node printing changes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Single quotes are no longer escaped when printing nodes</p> </li> <li> <p>Symbols in second half of ASCII table are no longer escaped when printing nodes; because of this, <code>format_utf8</code> flag is deleted as it&#8217;s no longer needed and <code>format_write_bom</code> is renamed to <code>format_write_bom_utf8</code>.</p> </li> <li> <p>Reworked node printing - now it works via <code>xml_writer</code> interface; implementations for <code>FILE*</code> and <code>std::ostream</code> are available. As a side-effect, <code>xml_document::save_file</code> now works without STL.</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added unsigned integer support for attributes (<code>xml_attribute::as_uint</code>, <code>xml_attribute::operator=</code>)</p> </li> <li> <p>Now document declaration (<code>&lt;?xml &#8230;&#8203;?&gt;</code>) is parsed as node with type <code>node_declaration</code> when <code>parse_declaration</code> flag is specified (access to encoding/version is performed as if they were attributes, i.e. <code>doc.child("xml").attribute("version").as_float()</code>); corresponding flags for node printing were also added</p> </li> <li> <p>Added support for custom memory management (see <code>set_memory_management_functions</code> for details)</p> </li> <li> <p>Implemented node/attribute copying (see <code>xml_node::insert_copy_*</code> and <code>xml_node::append_copy</code> for details)</p> </li> <li> <p>Added <code>find_child_by_attribute</code> and <code>find_child_by_attribute_w</code> to simplify parsing code in some cases (i.e. COLLADA files)</p> </li> <li> <p>Added file offset information querying for debugging purposes (now you&#8217;re able to determine exact location of any <code>xml_node</code> in parsed file, see <code>xml_node::offset_debug</code> for details)</p> </li> <li> <p>Improved error handling for parsing - now <code>load()</code>, <code>load_file()</code> and <code>parse()</code> return <code>xml_parse_result</code>, which contains error code and last parsed offset; this does not break old interface as <code>xml_parse_result</code> can be implicitly casted to <code>bool</code>.</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.34"><a class="anchor" href="#v0.34"></a><a class="link" href="#v0.34">v0.34 <sup>2007-10-31</sup></a></h3> <div class="paragraph"> <p>Maintenance release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed bug with loading from text-mode iostreams</p> </li> <li> <p>Fixed leak when <code>transfer_ownership</code> is true and parsing is failing</p> </li> <li> <p>Fixed bug in saving (<code>\r</code> and <code>\n</code> are now escaped in attribute values)</p> </li> <li> <p>Renamed <code>free()</code> to <code>destroy()</code> - some macro conflicts were reported</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Improved compatibility (supported Digital Mars C&#43;&#43;, MSVC 6, CodeWarrior 8, PGI C&#43;&#43;, Comeau, supported PS3 and XBox360)</p> </li> <li> <p><code>PUGIXML_NO_EXCEPTION</code> flag for platforms without exception handling</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.3"><a class="anchor" href="#v0.3"></a><a class="link" href="#v0.3">v0.3 <sup>2007-02-21</sup></a></h3> <div class="paragraph"> <p>Refactored, reworked and improved version. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Interface:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Added XPath</p> </li> <li> <p>Added tree modification functions</p> </li> <li> <p>Added no STL compilation mode</p> </li> <li> <p>Added saving document to file</p> </li> <li> <p>Refactored parsing flags</p> </li> <li> <p>Removed <code>xml_parser</code> class in favor of <code>xml_document</code></p> </li> <li> <p>Added transfer ownership parsing mode</p> </li> <li> <p>Modified the way <code>xml_tree_walker</code> works</p> </li> <li> <p>Iterators are now non-constant</p> </li> </ol> </div> </li> <li> <p>Implementation:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Support of several compilers and platforms</p> </li> <li> <p>Refactored and sped up parsing core</p> </li> <li> <p>Improved standard compliancy</p> </li> <li> <p>Added XPath implementation</p> </li> <li> <p>Fixed several bugs</p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.2"><a class="anchor" href="#v0.2"></a><a class="link" href="#v0.2">v0.2 <sup>2006-11-06</sup></a></h3> <div class="paragraph"> <p>First public release. Changes:</p> </div> <div class="ulist"> <ul> <li> <p>Bug fixes:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Fixed <code>child_value()</code> (for empty nodes)</p> </li> <li> <p>Fixed <code>xml_parser_impl</code> warning at W4</p> </li> </ol> </div> </li> <li> <p>New features:</p> <div class="olist arabic"> <ol class="arabic"> <li> <p>Introduced <code>child_value(name)</code> and <code>child_value_w(name)</code></p> </li> <li> <p><code>parse_eol_pcdata</code> and <code>parse_eol_attribute</code> flags + <code>parse_minimal</code> optimizations</p> </li> <li> <p>Optimizations of <code>strconv_t</code></p> </li> </ol> </div> </li> </ul> </div> </div> <div class="sect2"> <h3 id="v0.1"><a class="anchor" href="#v0.1"></a><a class="link" href="#v0.1">v0.1 <sup>2006-07-15</sup></a></h3> <div class="paragraph"> <p>First private release for testing purposes</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="apiref"><a class="anchor" href="#apiref"></a><a class="link" href="#apiref">10. API Reference</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>This is the reference for all macros, types, enumerations, classes and functions in pugixml. Each symbol is a link that leads to the relevant section of the manual.</p> </div> <div class="sect2"> <h3 id="apiref.macros"><a class="anchor" href="#apiref.macros"></a><a class="link" href="#apiref.macros">10.1. Macros</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-cp">#define <a href="#PUGIXML_WCHAR_MODE">PUGIXML_WCHAR_MODE</a></span> <span class="tok-cp">#define <a href="#PUGIXML_COMPACT">PUGIXML_COMPACT</a></span> <span class="tok-cp">#define <a href="#PUGIXML_NO_XPATH">PUGIXML_NO_XPATH</a></span> <span class="tok-cp">#define <a href="#PUGIXML_NO_STL">PUGIXML_NO_STL</a></span> <span class="tok-cp">#define <a href="#PUGIXML_NO_EXCEPTIONS">PUGIXML_NO_EXCEPTIONS</a></span> <span class="tok-cp">#define <a href="#PUGIXML_API">PUGIXML_API</a></span> <span class="tok-cp">#define <a href="#PUGIXML_CLASS">PUGIXML_CLASS</a></span> <span class="tok-cp">#define <a href="#PUGIXML_FUNCTION">PUGIXML_FUNCTION</a></span> <span class="tok-cp">#define <a href="#PUGIXML_MEMORY_PAGE_SIZE">PUGIXML_MEMORY_PAGE_SIZE</a></span> <span class="tok-cp">#define <a href="#PUGIXML_MEMORY_OUTPUT_STACK">PUGIXML_MEMORY_OUTPUT_STACK</a></span> <span class="tok-cp">#define <a href="#PUGIXML_MEMORY_XPATH_PAGE_SIZE">PUGIXML_MEMORY_XPATH_PAGE_SIZE</a></span> <span class="tok-cp">#define <a href="#PUGIXML_HEADER_ONLY">PUGIXML_HEADER_ONLY</a></span> <span class="tok-cp">#define <a href="#PUGIXML_HAS_LONG_LONG">PUGIXML_HAS_LONG_LONG</a></span> <span class="tok-cp">#define <a href="#PUGIXML_HAS_STRING_VIEW">PUGIXML_HAS_STRING_VIEW</a></span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="apiref.types"><a class="anchor" href="#apiref.types"></a><a class="link" href="#apiref.types">10.2. Types</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">configuration</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#char_t">char_t</a><span class="tok-p">;</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">configuration</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#string_t">string_t</a><span class="tok-p">;</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">configuration</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#string_view_t">string_view_t</a><span class="tok-p">;</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">*</span><a href="#allocation_function">allocation_function</a><span class="tok-p">)(</span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-o">*</span><a href="#deallocation_function">deallocation_function</a><span class="tok-p">)(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">ptr</span><span class="tok-p">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="apiref.enums"><a class="anchor" href="#apiref.enums"></a><a class="link" href="#apiref.enums">10.3. Enumerations</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">enum</span><span class="tok-w"> </span><a href="#xml_node_type">xml_node_type</a> <span class="tok-w"> </span><a href="#node_null">node_null</a> <span class="tok-w"> </span><a href="#node_document">node_document</a> <span class="tok-w"> </span><a href="#node_element">node_element</a> <span class="tok-w"> </span><a href="#node_pcdata">node_pcdata</a> <span class="tok-w"> </span><a href="#node_cdata">node_cdata</a> <span class="tok-w"> </span><a href="#node_comment">node_comment</a> <span class="tok-w"> </span><a href="#node_pi">node_pi</a> <span class="tok-w"> </span><a href="#node_declaration">node_declaration</a> <span class="tok-w"> </span><a href="#node_doctype">node_doctype</a> <span class="tok-k">enum</span><span class="tok-w"> </span><a href="#xml_parse_status">xml_parse_status</a> <span class="tok-w"> </span><a href="#status_ok">status_ok</a> <span class="tok-w"> </span><a href="#status_file_not_found">status_file_not_found</a> <span class="tok-w"> </span><a href="#status_io_error">status_io_error</a> <span class="tok-w"> </span><a href="#status_out_of_memory">status_out_of_memory</a> <span class="tok-w"> </span><a href="#status_internal_error">status_internal_error</a> <span class="tok-w"> </span><a href="#status_unrecognized_tag">status_unrecognized_tag</a> <span class="tok-w"> </span><a href="#status_bad_pi">status_bad_pi</a> <span class="tok-w"> </span><a href="#status_bad_comment">status_bad_comment</a> <span class="tok-w"> </span><a href="#status_bad_cdata">status_bad_cdata</a> <span class="tok-w"> </span><a href="#status_bad_doctype">status_bad_doctype</a> <span class="tok-w"> </span><a href="#status_bad_pcdata">status_bad_pcdata</a> <span class="tok-w"> </span><a href="#status_bad_start_element">status_bad_start_element</a> <span class="tok-w"> </span><a href="#status_bad_attribute">status_bad_attribute</a> <span class="tok-w"> </span><a href="#status_bad_end_element">status_bad_end_element</a> <span class="tok-w"> </span><a href="#status_end_element_mismatch">status_end_element_mismatch</a> <span class="tok-w"> </span><a href="#status_append_invalid_root">status_append_invalid_root</a> <span class="tok-w"> </span><a href="#status_no_document_element">status_no_document_element</a> <span class="tok-k">enum</span><span class="tok-w"> </span><a href="#xml_encoding">xml_encoding</a> <span class="tok-w"> </span><a href="#encoding_auto">encoding_auto</a> <span class="tok-w"> </span><a href="#encoding_utf8">encoding_utf8</a> <span class="tok-w"> </span><a href="#encoding_utf16_le">encoding_utf16_le</a> <span class="tok-w"> </span><a href="#encoding_utf16_be">encoding_utf16_be</a> <span class="tok-w"> </span><a href="#encoding_utf16">encoding_utf16</a> <span class="tok-w"> </span><a href="#encoding_utf32_le">encoding_utf32_le</a> <span class="tok-w"> </span><a href="#encoding_utf32_be">encoding_utf32_be</a> <span class="tok-w"> </span><a href="#encoding_utf32">encoding_utf32</a> <span class="tok-w"> </span><a href="#encoding_wchar">encoding_wchar</a> <span class="tok-w"> </span><a href="#encoding_latin1">encoding_latin1</a> <span class="tok-k">enum</span><span class="tok-w"> </span><a href="#xpath_value_type">xpath_value_type</a> <span class="tok-w"> </span><a href="#xpath_type_none">xpath_type_none</a> <span class="tok-w"> </span><a href="#xpath_type_node_set">xpath_type_node_set</a> <span class="tok-w"> </span><a href="#xpath_type_number">xpath_type_number</a> <span class="tok-w"> </span><a href="#xpath_type_string">xpath_type_string</a> <span class="tok-w"> </span><a href="#xpath_type_boolean">xpath_type_boolean</a></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="apiref.constants"><a class="anchor" href="#apiref.constants"></a><a class="link" href="#apiref.constants">10.4. Constants</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// Formatting options bit flags:</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_attribute_single_quote">format_attribute_single_quote</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_default">format_default</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_indent">format_indent</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_indent_attributes">format_indent_attributes</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_no_declaration">format_no_declaration</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_no_empty_element_tags">format_no_empty_element_tags</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_no_escapes">format_no_escapes</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_raw">format_raw</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_save_file_text">format_save_file_text</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_skip_control_chars">format_skip_control_chars</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#format_write_bom">format_write_bom</a> <span class="tok-c1">// Parsing options bit flags:</span> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_cdata">parse_cdata</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_comments">parse_comments</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_declaration">parse_declaration</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_default">parse_default</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_doctype">parse_doctype</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_eol">parse_eol</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_escapes">parse_escapes</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_fragment">parse_fragment</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_full">parse_full</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_minimal">parse_minimal</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_pi">parse_pi</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_trim_pcdata">parse_trim_pcdata</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_ws_pcdata">parse_ws_pcdata</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_ws_pcdata_single">parse_ws_pcdata_single</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_embed_pcdata">parse_embed_pcdata</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_merge_pcdata">parse_merge_pcdata</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_wconv_attribute">parse_wconv_attribute</a> <span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#parse_wnorm_attribute">parse_wnorm_attribute</a></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="apiref.classes"><a class="anchor" href="#apiref.classes"></a><a class="link" href="#apiref.classes">10.5. Classes</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">class</span> <a href="#xml_attribute">xml_attribute</a> <span class="tok-w"> </span><a href="#xml_attribute::ctor">xml_attribute</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::empty">empty</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xml_attribute::unspecified_bool_type">unspecified_bool_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator==</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator!=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator&lt;</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator&gt;</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator&lt;=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::comparison">operator&gt;=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><a href="#xml_attribute::hash_value">hash_value</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_attribute::next_attribute">next_attribute</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_attribute::previous_attribute">previous_attribute</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_attribute::name">name</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_attribute::value">value</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_attribute::as_string">as_string</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#xml_attribute::as_int">as_int</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#xml_attribute::as_uint">as_uint</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><a href="#xml_attribute::as_double">as_double</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">float</span><span class="tok-w"> </span><a href="#xml_attribute::as_float">as_float</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::as_bool">as_bool</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><a href="#xml_attribute::as_llong">as_llong</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><a href="#xml_attribute::as_ullong">as_ullong</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_name">set_name</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_name">set_name</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_name">set_name</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_attribute::set_value">set_value</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_attribute::assign">operator=</a><span class="tok-p">(</span><span class="tok-n">unsnigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-k">class</span> <a href="#xml_node">xml_node</a> <span class="tok-w"> </span><a href="#xml_node::ctor">xml_node</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::empty">empty</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xml_node::unspecified_bool_type">unspecified_bool_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator==</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator!=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator&lt;</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator&gt;</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator&lt;=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::comparison">operator&gt;=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">r</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><a href="#xml_node::hash_value">hash_value</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><a href="#xml_node::type">type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_node::name">name</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_node::value">value</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::parent">parent</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::first_child">first_child</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::last_child">last_child</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::next_sibling">next_sibling</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::previous_sibling">previous_sibling</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::first_attribute">first_attribute</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::last_attribute">last_attribute</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">implementation</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#xml_node::children">children</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">implementation</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#xml_node::children">children</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">implementation</span><span class="tok-o">-</span><span class="tok-n">defined</span><span class="tok-o">-</span><span class="tok-n">type</span><span class="tok-w"> </span><a href="#xml_node::attributes">attributes</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::child">child</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::child">child</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::attribute">attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::attribute">attribute</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::next_sibling_name">next_sibling</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::next_sibling_name">next_sibling</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::previous_sibling_name">previous_sibling</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::previous_sibling_name">previous_sibling</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::attribute_hinted">attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::attribute_hinted">attribute</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">hint</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::find_child_by_attribute">find_child_by_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_value</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::find_child_by_attribute">find_child_by_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">attr_value</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_node::child_value">child_value</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_node::child_value">child_value</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-w"> </span><a href="#xml_node::text">text</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">xml_node_iterator</span><span class="tok-w"> </span><a href="#xml_node_iterator">iterator</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">iterator</span><span class="tok-w"> </span><a href="#xml_node::begin">begin</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">iterator</span><span class="tok-w"> </span><a href="#xml_node::end">end</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-n">xml_attribute_iterator</span><span class="tok-w"> </span><a href="#xml_attribute_iterator">attribute_iterator</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">attribute_iterator</span><span class="tok-w"> </span><a href="#xml_node::attributes_begin">attributes_begin</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">attribute_iterator</span><span class="tok-w"> </span><a href="#xml_node::attributes_end">attributes_end</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::traverse">traverse</a><span class="tok-p">(</span><span class="tok-n">xml_tree_walker</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">walker</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::find_attribute">find_attribute</a><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::find_child">find_child</a><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">template</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-k">typename</span><span class="tok-w"> </span><span class="tok-nc">Predicate</span><span class="tok-o">&gt;</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::find_node">find_node</a><span class="tok-p">(</span><span class="tok-n">Predicate</span><span class="tok-w"> </span><span class="tok-n">pred</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">string_t</span><span class="tok-w"> </span><a href="#xml_node::path">path</a><span class="tok-p">(</span><span class="tok-n">char_t</span><span class="tok-w"> </span><span class="tok-n">delimiter</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-sc">&#39;/&#39;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::first_element_by_path">xml_node::first_element_by_path</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-w"> </span><span class="tok-n">delimiter</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-sc">&#39;/&#39;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::root">root</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><a href="#xml_node::offset_debug">offset_debug</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_name">set_name</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_name">set_name</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_name">set_name</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_value">set_value</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_value">set_value</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::set_value">set_value</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::append_attribute">append_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::append_attribute">append_attribute</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::prepend_attribute">prepend_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::prepend_attribute">prepend_attribute</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_attribute_after">insert_attribute_after</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_attribute_after">insert_attribute_after</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_attribute_before">insert_attribute_before</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_attribute_before">insert_attribute_before</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::append_child">append_child</a><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node_element</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::prepend_child">prepend_child</a><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node_element</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_after">insert_child_after</a><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_before">insert_child_before</a><span class="tok-p">(</span><span class="tok-n">xml_node_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::append_child">append_child</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::append_child">append_child</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::prepend_child">prepend_child</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::prepend_child">prepend_child</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_after">insert_child_after</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_after">insert_child_after</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_before">insert_child_before</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_child_before">insert_child_before</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::append_copy">append_copy</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::prepend_copy">prepend_copy</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_copy_after">insert_copy_after</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xml_node::insert_copy_before">insert_copy_before</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::append_copy">append_copy</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::prepend_copy">prepend_copy</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_copy_after">insert_copy_after</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_copy_before">insert_copy_before</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::append_move">append_move</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::prepend_move">prepend_move</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_move_after">insert_move_after</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_node::insert_move_before">insert_move_before</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">moved</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_attribute">remove_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">a</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_attribute">remove_attribute</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_attribute">remove_attribute</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_attributes">remove_attributes</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_child">remove_child</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_child">remove_child</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_child">remove_child</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_node::remove_children">remove_children</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_node::append_buffer">append_buffer</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_node::print">print</a><span class="tok-p">(</span><span class="tok-n">xml_writer</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">writer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_node::print_stream">print</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">os</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_node::print_stream">print</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">os</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><a href="#xml_node::select_node">select_node</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><a href="#xml_node::select_node_precomp">select_node</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><a href="#xml_node::select_nodes">select_nodes</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><a href="#xml_node::select_nodes_precomp">select_nodes</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_query</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xml_document">xml_document</a> <span class="tok-w"> </span><a href="#xml_document::ctor">xml_document</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-o">~</span><a href="#xml_document::dtor">xml_document</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_document::reset">reset</a><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_document::reset">reset</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_document</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">proto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_stream">load</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">istream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_stream">load</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wistream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_string">load_string</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_file">load_file</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_file_wide">load_file</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_buffer">load_buffer</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_buffer_inplace">load_buffer_inplace</a><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><a href="#xml_document::load_buffer_inplace_own">load_buffer_inplace_own</a><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">contents</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">options</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">parse_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_document::save_file">save_file</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_document::save_file_wide">save_file</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">path</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_document::save_stream">save</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_document::save_stream">save</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_document::save">save</a><span class="tok-p">(</span><span class="tok-n">xml_writer</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">writer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">indent</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\t</span><span class="tok-s">&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">flags</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">format_default</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><span class="tok-n">encoding</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">encoding_auto</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_document::document_element">document_element</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">struct</span> <a href="#xml_parse_result">xml_parse_result</a> <span class="tok-w"> </span><span class="tok-n">xml_parse_status</span><span class="tok-w"> </span><a href="#xml_parse_result::status">status</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><a href="#xml_parse_result::offset">offset</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_encoding</span><span class="tok-w"> </span><a href="#xml_parse_result::encoding">encoding</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xml_parse_result::bool">bool</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_parse_result::description">description</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xml_node_iterator">xml_node_iterator</a> <span class="tok-k">class</span> <a href="#xml_attribute_iterator">xml_attribute_iterator</a> <span class="tok-k">class</span> <a href="#xml_tree_walker">xml_tree_walker</a> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_tree_walker::begin">begin</a><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_tree_walker::for_each">for_each</a><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_tree_walker::end">end</a><span class="tok-p">(</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#xml_tree_walker::depth">depth</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xml_text">xml_text</a> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::empty">empty</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xml_text::unspecified_bool_type">xml_text::unspecified_bool_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_text::get">xml_text::get</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xml_text::as_string">as_string</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#xml_text::as_int">as_int</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><a href="#xml_text::as_uint">as_uint</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><a href="#xml_text::as_double">as_double</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">float</span><span class="tok-w"> </span><a href="#xml_text::as_float">as_float</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::as_bool">as_bool</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><a href="#xml_text::as_llong">as_llong</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><a href="#xml_text::as_ullong">as_ullong</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">def</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set">set</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xml_text::set_value">set</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-n">string_view_t</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">float</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_text</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xml_text::assign">operator=</a><span class="tok-p">(</span><span class="tok-kt">unsigned</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-kt">long</span><span class="tok-w"> </span><span class="tok-n">rhs</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xml_text::data">data</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xml_writer">xml_writer</a> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xml_writer::write">write</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">data</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xml_writer_file">xml_writer_file</a><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-k">public</span><span class="tok-w"> </span><span class="tok-n">xml_writer</span> <span class="tok-w"> </span><a href="#xml_writer_file">xml_writer_file</a><span class="tok-p">(</span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">file</span><span class="tok-p">);</span> <span class="tok-k">class</span> <a href="#xml_writer_stream">xml_writer_stream</a><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-k">public</span><span class="tok-w"> </span><span class="tok-n">xml_writer</span> <span class="tok-w"> </span><a href="#xml_writer_stream">xml_writer_stream</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">);</span> <span class="tok-w"> </span><a href="#xml_writer_stream">xml_writer_stream</a><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wostream</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">);</span> <span class="tok-k">struct</span> <a href="#xpath_parse_result">xpath_parse_result</a> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_parse_result::error">error</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">ptrdiff_t</span><span class="tok-w"> </span><a href="#xpath_parse_result::offset">offset</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xpath_parse_result::bool">bool</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_parse_result::description">description</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xpath_query">xpath_query</a> <span class="tok-w"> </span><span class="tok-k">explicit</span><span class="tok-w"> </span><a href="#xpath_query::ctor">xpath_query</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">query</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_variable_set</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">variables</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_boolean">evaluate_boolean</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_number">evaluate_number</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">string_t</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_string">evaluate_string</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_string_buffer">evaluate_string</a><span class="tok-p">(</span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">capacity</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_node_set">evaluate_node_set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><a href="#xpath_query::evaluate_node">evaluate_node</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><a href="#xpath_query::return_type">return_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_parse_result</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xpath_query::result">result</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xpath_query::unspecified_bool_type">unspecified_bool_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xpath_exception">xpath_exception</a><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-k">public</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">exception</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_exception::what">what</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-k">noexcept</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_parse_result</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xpath_exception::result">result</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xpath_node">xpath_node</a> <span class="tok-w"> </span><a href="#xpath_node::ctor">xpath_node</a><span class="tok-p">();</span> <span class="tok-w"> </span><a href="#xpath_node::ctor">xpath_node</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">);</span> <span class="tok-w"> </span><a href="#xpath_node::ctor">xpath_node</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">attribute</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">parent</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xpath_node::node">node</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><a href="#xpath_node::attribute">attribute</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xml_node</span><span class="tok-w"> </span><a href="#xpath_node::parent">parent</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">operator</span><span class="tok-w"> </span><a href="#xpath_node::unspecified_bool_type">unspecified_bool_type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_node::comparison">operator==</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_node::comparison">operator!=</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">n</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-k">class</span> <a href="#xpath_node_set">xpath_node_set</a> <span class="tok-w"> </span><a href="#xpath_node_set::ctor">xpath_node_set</a><span class="tok-p">();</span> <span class="tok-w"> </span><a href="#xpath_node_set::ctor">xpath_node_set</a><span class="tok-p">(</span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">begin</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">end</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">type_t</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">type_unsorted</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">typedef</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_node_set::const_iterator">const_iterator</a><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><a href="#xpath_node_set::begin">begin</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><a href="#xpath_node_set::end">end</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xpath_node_set::index">operator[</a><span class="tok-p">](</span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">index</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><a href="#xpath_node_set::size">size</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_node_set::empty">empty</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><a href="#xpath_node_set::first">first</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">enum</span><span class="tok-w"> </span><span class="tok-nc">type_t</span><span class="tok-w"> </span><span class="tok-p">{</span><a href="#xpath_node_set::type_unsorted">type_unsorted</a><span class="tok-p">,</span><span class="tok-w"> </span><a href="#xpath_node_set::type_sorted">type_sorted</a><span class="tok-p">,</span><span class="tok-w"> </span><a href="#xpath_node_set::type_sorted_reverse">type_sorted_reverse</a><span class="tok-p">};</span> <span class="tok-w"> </span><span class="tok-n">type_t</span><span class="tok-w"> </span><a href="#xpath_node_set::type">type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><a href="#xpath_node_set::sort">sort</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">reverse</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">false</span><span class="tok-p">);</span> <span class="tok-k">class</span> <a href="#xpath_variable">xpath_variable</a> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_variable::name">name</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><a href="#xpath_variable::type">type</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable::get_boolean">get_boolean</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><a href="#xpath_variable::get_number">get_number</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_variable::get_string">get_string</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><a href="#xpath_variable::get_node_set">get_node_set</a><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable::set">set</a><span class="tok-p">(</span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable::set">set</a><span class="tok-p">(</span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-k">class</span> <a href="#xpath_variable_set">xpath_variable_set</a> <span class="tok-w"> </span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_variable_set::add">add</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">xpath_value_type</span><span class="tok-w"> </span><span class="tok-n">type</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable_set::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable_set::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">double</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable_set::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><a href="#xpath_variable_set::set">set</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_node_set</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">value</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_variable_set::get">get</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">xpath_variable</span><span class="tok-o">*</span><span class="tok-w"> </span><a href="#xpath_variable_set::get">get</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">char_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">name</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-k">const</span><span class="tok-p">;</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="apiref.functions"><a class="anchor" href="#apiref.functions"></a><a class="link" href="#apiref.functions">10.6. Functions</a></h3> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><a href="#as_utf8">as_utf8</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">wchar_t</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><a href="#as_utf8">as_utf8</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-w"> </span><a href="#as_wide">as_wide</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">wstring</span><span class="tok-w"> </span><a href="#as_wide">as_wide</a><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">str</span><span class="tok-p">);</span> <span class="tok-kt">void</span><span class="tok-w"> </span><a href="#set_memory_management_functions">set_memory_management_functions</a><span class="tok-p">(</span><span class="tok-n">allocation_function</span><span class="tok-w"> </span><span class="tok-n">allocate</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">deallocation_function</span><span class="tok-w"> </span><span class="tok-n">deallocate</span><span class="tok-p">);</span> <span class="tok-n">allocation_function</span><span class="tok-w"> </span><a href="#get_memory_allocation_function">get_memory_allocation_function</a><span class="tok-p">();</span> <span class="tok-n">deallocation_function</span><span class="tok-w"> </span><a href="#get_memory_deallocation_function">get_memory_deallocation_function</a><span class="tok-p">();</span></code></pre> </div> </div> </div> </div> </div> </div> <div id="footnotes"> <hr> <div class="footnote" id="_footnotedef_1"> <a href="#_footnoteref_1">1</a>. All trademarks used are properties of their respective owners. </div> </div> <div id="footer"> <div id="footer-text"> Last updated 2026-01-02 09:52:21 -0800 </div> </div> </body> </html>
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/quickstart.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 2.0.23"> <meta name="author" content="website, repository"> <title>pugixml 1.15 quick start guide</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"> <style> /*! Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */ /* Uncomment the following line when using as a custom stylesheet */ /* @import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700"; */ html{font-family:sans-serif;-webkit-text-size-adjust:100%} a{background:none} a:focus{outline:thin dotted} a:active,a:hover{outline:0} h1{font-size:2em;margin:.67em 0} b,strong{font-weight:bold} abbr{font-size:.9em} abbr[title]{cursor:help;border-bottom:1px dotted #dddddf;text-decoration:none} dfn{font-style:italic} hr{height:0} mark{background:#ff0;color:#000} code,kbd,pre,samp{font-family:monospace;font-size:1em} pre{white-space:pre-wrap} q{quotes:"\201C" "\201D" "\2018" "\2019"} small{font-size:80%} sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline} sup{top:-.5em} sub{bottom:-.25em} img{border:0} svg:not(:root){overflow:hidden} figure{margin:0} audio,video{display:inline-block} audio:not([controls]){display:none;height:0} fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em} legend{border:0;padding:0} button,input,select,textarea{font-family:inherit;font-size:100%;margin:0} button,input{line-height:normal} button,select{text-transform:none} button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer} button[disabled],html input[disabled]{cursor:default} input[type=checkbox],input[type=radio]{padding:0} button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0} textarea{overflow:auto;vertical-align:top} table{border-collapse:collapse;border-spacing:0} *,::before,::after{box-sizing:border-box} html,body{font-size:100%} body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;line-height:1;position:relative;cursor:auto;-moz-tab-size:4;-o-tab-size:4;tab-size:4;word-wrap:anywhere;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased} a:hover{cursor:pointer} img,object,embed{max-width:100%;height:auto} object,embed{height:100%} img{-ms-interpolation-mode:bicubic} .left{float:left!important} .right{float:right!important} .text-left{text-align:left!important} .text-right{text-align:right!important} .text-center{text-align:center!important} .text-justify{text-align:justify!important} .hide{display:none} img,object,svg{display:inline-block;vertical-align:middle} textarea{height:auto;min-height:50px} select{width:100%} .subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em} div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0} a{color:#2156a5;text-decoration:underline;line-height:inherit} a:hover,a:focus{color:#1d4b8f} a img{border:0} p{line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility} p aside{font-size:.875em;line-height:1.35;font-style:italic} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em} h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0} h1{font-size:2.125em} h2{font-size:1.6875em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em} h4,h5{font-size:1.125em} h6{font-size:1em} hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em} em,i{font-style:italic;line-height:inherit} strong,b{font-weight:bold;line-height:inherit} small{font-size:60%;line-height:inherit} code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)} ul,ol,dl{line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit} ul,ol{margin-left:1.5em} ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0} ul.circle{list-style-type:circle} ul.disc{list-style-type:disc} ul.square{list-style-type:square} ul.circle ul:not([class]),ul.disc ul:not([class]),ul.square ul:not([class]){list-style:inherit} ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0} dl dt{margin-bottom:.3125em;font-weight:bold} dl dd{margin-bottom:1.25em} blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd} blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)} @media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2} h1{font-size:2.75em} h2{font-size:2.3125em} h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em} h4{font-size:1.4375em}} table{background:#fff;margin-bottom:1.25em;border:1px solid #dedede;word-wrap:normal} table thead,table tfoot{background:#f7f8f7} table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left} table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)} table tr.even,table tr.alt{background:#f8f8f7} table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{line-height:1.6} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em} h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400} .center{margin-left:auto;margin-right:auto} .stretch{width:100%} .clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table} .clearfix::after,.float-group::after{clear:both} :not(pre).nobreak{word-wrap:normal} :not(pre).nowrap{white-space:nowrap} :not(pre).pre-wrap{white-space:pre-wrap} :not(pre):not([class^=L])>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background:#f7f7f8;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed} pre{color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;line-height:1.45;text-rendering:optimizeSpeed} pre code,pre pre{color:inherit;font-size:inherit;line-height:inherit} pre>code{display:block} pre.nowrap,pre.nowrap pre{white-space:pre;word-wrap:normal} em em{font-style:normal} strong strong{font-weight:400} .keyseq{color:rgba(51,51,51,.8)} kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background:#f7f7f7;border:1px solid #ccc;border-radius:3px;box-shadow:0 1px 0 rgba(0,0,0,.2),inset 0 0 0 .1em #fff;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} .keyseq kbd:first-child{margin-left:0} .keyseq kbd:last-child{margin-right:0} .menuseq,.menuref{color:#000} .menuseq b:not(.caret),.menuref{font-weight:inherit} .menuseq{word-spacing:-.02em} .menuseq b.caret{font-size:1.25em;line-height:.8} .menuseq i.caret{font-weight:bold;text-align:center;width:.45em} b.button::before,b.button::after{position:relative;top:-1px;font-weight:400} b.button::before{content:"[";padding:0 3px 0 2px} b.button::after{content:"]";padding:0 2px 0 3px} p a>code:hover{color:rgba(0,0,0,.9)} #header,#content,#footnotes,#footer{width:100%;margin:0 auto;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em} #header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table} #header::after,#content::after,#footnotes::after,#footer::after{clear:both} #content{margin-top:1.25em} #content::before{content:none} #header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0} #header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf} #header>h1:only-child{border-bottom:1px solid #dddddf;padding-bottom:8px} #header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:flex;flex-flow:row wrap} #header .details span:first-child{margin-left:-.125em} #header .details span.email a{color:rgba(0,0,0,.85)} #header .details br{display:none} #header .details br+span::before{content:"\00a0\2013\00a0"} #header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)} #header .details br+span#revremark::before{content:"\00a0|\00a0"} #header #revnumber{text-transform:capitalize} #header #revnumber::after{content:"\00a0"} #content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem} #toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em} #toc>ul{margin-left:.125em} #toc ul.sectlevel0>li>a{font-style:italic} #toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0} #toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none} #toc li{line-height:1.3334;margin-top:.3334em} #toc a{text-decoration:none} #toc a:active{text-decoration:underline} #toctitle{color:#7a2518;font-size:1.2em} @media screen and (min-width:768px){#toctitle{font-size:1.375em} body.toc2{padding-left:15em;padding-right:0} body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px} #toc.toc2{margin-top:0!important;background:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto} #toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em} #toc.toc2>ul{font-size:.9em;margin-bottom:0} #toc.toc2 ul ul{margin-left:0;padding-left:1em} #toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em} body.toc2.toc-right{padding-left:0;padding-right:15em} body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}} @media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0} #toc.toc2{width:20em} #toc.toc2 #toctitle{font-size:1.375em} #toc.toc2>ul{font-size:.95em} #toc.toc2 ul ul{padding-left:1.25em} body.toc2.toc-right{padding-left:0;padding-right:20em}} #content #toc{border:1px solid #e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;border-radius:4px} #content #toc>:first-child{margin-top:0} #content #toc>:last-child{margin-bottom:0} #footer{max-width:none;background:rgba(0,0,0,.8);padding:1.25em} #footer-text{color:hsla(0,0%,100%,.8);line-height:1.44} #content{margin-bottom:.625em} .sect1{padding-bottom:.625em} @media screen and (min-width:768px){#content{margin-bottom:1.25em} .sect1{padding-bottom:1.25em}} .sect1:last-child{padding-bottom:0} .sect1+.sect1{border-top:1px solid #e7e7e9} #content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400} #content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em} #content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible} #content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none} #content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221} details,.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em} details{margin-left:1.25rem} details>summary{cursor:pointer;display:block;position:relative;line-height:1.6;margin-bottom:.625rem;outline:none;-webkit-tap-highlight-color:transparent} details>summary::-webkit-details-marker{display:none} details>summary::before{content:"";border:solid transparent;border-left:solid;border-width:.3em 0 .3em .5em;position:absolute;top:.5em;left:-1.25rem;transform:translateX(15%)} details[open]>summary::before{border:solid transparent;border-top:solid;border-width:.5em .3em 0;transform:translateY(15%)} details>summary::after{content:"";width:1.25rem;height:1em;position:absolute;top:.3em;left:-1.25rem} .admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic} table.tableblock.fit-content>caption.title{white-space:nowrap;width:0} .paragraph.lead>p,#preamble>.sectionbody>[class=paragraph]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)} .admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%} .admonitionblock>table td.icon{text-align:center;width:80px} .admonitionblock>table td.icon img{max-width:none} .admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase} .admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6);word-wrap:anywhere} .admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0} .exampleblock>.content{border:1px solid #e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;border-radius:4px} .sidebarblock{border:1px solid #dbdbd6;margin-bottom:1.25em;padding:1.25em;background:#f3f3f2;border-radius:4px} .sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center} .exampleblock>.content>:first-child,.sidebarblock>.content>:first-child{margin-top:0} .exampleblock>.content>:last-child,.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0} .literalblock pre,.listingblock>.content>pre{border-radius:4px;overflow-x:auto;padding:1em;font-size:.8125em} @media screen and (min-width:768px){.literalblock pre,.listingblock>.content>pre{font-size:.90625em}} @media screen and (min-width:1280px){.literalblock pre,.listingblock>.content>pre{font-size:1em}} .literalblock pre,.listingblock>.content>pre:not(.highlight),.listingblock>.content>pre[class=highlight],.listingblock>.content>pre[class^="highlight "]{background:#f7f7f8} .literalblock.output pre{color:#f7f7f8;background:rgba(0,0,0,.9)} .listingblock>.content{position:relative} .listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:inherit;opacity:.5} .listingblock:hover code[data-lang]::before{display:block} .listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:inherit;opacity:.5} .listingblock.terminal pre .command:not([data-prompt])::before{content:"$"} .listingblock pre.highlightjs{padding:0} .listingblock pre.highlightjs>code{padding:1em;border-radius:4px} .listingblock pre.prettyprint{border-width:0} .prettyprint{background:#f7f7f8} pre.prettyprint .linenums{line-height:1.45;margin-left:2em} pre.prettyprint li{background:none;list-style-type:inherit;padding-left:0} pre.prettyprint li code[data-lang]::before{opacity:1} pre.prettyprint li:not(:first-child) code[data-lang]::before{display:none} table.linenotable{border-collapse:separate;border:0;margin-bottom:0;background:none} table.linenotable td[class]{color:inherit;vertical-align:top;padding:0;line-height:inherit;white-space:normal} table.linenotable td.code{padding-left:.75em} table.linenotable td.linenos,pre.pygments .linenos{border-right:1px solid;opacity:.35;padding-right:.5em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none} pre.pygments span.linenos{display:inline-block;margin-right:.75em} .quoteblock{margin:0 1em 1.25em 1.5em;display:table} .quoteblock:not(.excerpt)>.title{margin-left:-1.5em;margin-bottom:.75em} .quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify} .quoteblock blockquote{margin:0;padding:0;border:0} .quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)} .quoteblock blockquote>.paragraph:last-child p{margin-bottom:0} .quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right} .verseblock{margin:0 1em 1.25em} .verseblock pre{font-family:"Open Sans","DejaVu Sans",sans-serif;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility} .verseblock pre strong{font-weight:400} .verseblock .attribution{margin-top:1.25rem;margin-left:.5ex} .quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic} .quoteblock .attribution br,.verseblock .attribution br{display:none} .quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)} .quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none} .quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0} .quoteblock.abstract{margin:0 1em 1.25em;display:block} .quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center} .quoteblock.excerpt>blockquote,.quoteblock .quoteblock{padding:0 0 .25em 1em;border-left:.25em solid #dddddf} .quoteblock.excerpt,.quoteblock .quoteblock{margin-left:0} .quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem} .quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;font-size:.85rem;text-align:left;margin-right:0} p.tableblock:last-child{margin-bottom:0} td.tableblock>.content{margin-bottom:1.25em;word-wrap:anywhere} td.tableblock>.content>:last-child{margin-bottom:-1.25em} table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede} table.grid-all>*>tr>*{border-width:1px} table.grid-cols>*>tr>*{border-width:0 1px} table.grid-rows>*>tr>*{border-width:1px 0} table.frame-all{border-width:1px} table.frame-ends{border-width:1px 0} table.frame-sides{border-width:0 1px} table.frame-none>colgroup+*>:first-child>*,table.frame-sides>colgroup+*>:first-child>*{border-top-width:0} table.frame-none>:last-child>:last-child>*,table.frame-sides>:last-child>:last-child>*{border-bottom-width:0} table.frame-none>*>tr>:first-child,table.frame-ends>*>tr>:first-child{border-left-width:0} table.frame-none>*>tr>:last-child,table.frame-ends>*>tr>:last-child{border-right-width:0} table.stripes-all>*>tr,table.stripes-odd>*>tr:nth-of-type(odd),table.stripes-even>*>tr:nth-of-type(even),table.stripes-hover>*>tr:hover{background:#f8f8f7} th.halign-left,td.halign-left{text-align:left} th.halign-right,td.halign-right{text-align:right} th.halign-center,td.halign-center{text-align:center} th.valign-top,td.valign-top{vertical-align:top} th.valign-bottom,td.valign-bottom{vertical-align:bottom} th.valign-middle,td.valign-middle{vertical-align:middle} table thead th,table tfoot th{font-weight:bold} tbody tr th{background:#f7f8f7} tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold} p.tableblock>code:only-child{background:none;padding:0} p.tableblock{font-size:1em} ol{margin-left:1.75em} ul li ol{margin-left:1.5em} dl dd{margin-left:1.125em} dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0} li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em} ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none} ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em} ul.unstyled,ol.unstyled{margin-left:0} li>p:empty:only-child::before{content:"";display:inline-block} ul.checklist>li>p:first-child{margin-left:-1em} ul.checklist>li>p:first-child>.fa-square-o:first-child,ul.checklist>li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em} ul.checklist>li>p:first-child>input[type=checkbox]:first-child{margin-right:.25em} ul.inline{display:flex;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em} ul.inline>li{margin-left:1.25em} .unstyled dl dt{font-weight:400;font-style:normal} ol.arabic{list-style-type:decimal} ol.decimal{list-style-type:decimal-leading-zero} ol.loweralpha{list-style-type:lower-alpha} ol.upperalpha{list-style-type:upper-alpha} ol.lowerroman{list-style-type:lower-roman} ol.upperroman{list-style-type:upper-roman} ol.lowergreek{list-style-type:lower-greek} .hdlist>table,.colist>table{border:0;background:none} .hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none} td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em} td.hdlist1{font-weight:bold;padding-bottom:1.25em} td.hdlist2{word-wrap:anywhere} .literalblock+.colist,.listingblock+.colist{margin-top:-.5em} .colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top} .colist td:not([class]):first-child img{max-width:none} .colist td:not([class]):last-child{padding:.25em 0} .thumb,.th{line-height:0;display:inline-block;border:4px solid #fff;box-shadow:0 0 0 1px #ddd} .imageblock.left{margin:.25em .625em 1.25em 0} .imageblock.right{margin:.25em 0 1.25em .625em} .imageblock>.title{margin-bottom:0} .imageblock.thumb,.imageblock.th{border-width:6px} .imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em} .image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0} .image.left{margin-right:.625em} .image.right{margin-left:.625em} a.image{text-decoration:none;display:inline-block} a.image object{pointer-events:none} sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super} sup.footnote a,sup.footnoteref a{text-decoration:none} sup.footnote a:active,sup.footnoteref a:active,#footnotes .footnote a:first-of-type:active{text-decoration:underline} #footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em} #footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0} #footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em} #footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em} #footnotes .footnote:last-of-type{margin-bottom:0} #content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0} div.unbreakable{page-break-inside:avoid} .big{font-size:larger} .small{font-size:smaller} .underline{text-decoration:underline} .overline{text-decoration:overline} .line-through{text-decoration:line-through} .aqua{color:#00bfbf} .aqua-background{background:#00fafa} .black{color:#000} .black-background{background:#000} .blue{color:#0000bf} .blue-background{background:#0000fa} .fuchsia{color:#bf00bf} .fuchsia-background{background:#fa00fa} .gray{color:#606060} .gray-background{background:#7d7d7d} .green{color:#006000} .green-background{background:#007d00} .lime{color:#00bf00} .lime-background{background:#00fa00} .maroon{color:#600000} .maroon-background{background:#7d0000} .navy{color:#000060} .navy-background{background:#00007d} .olive{color:#606000} .olive-background{background:#7d7d00} .purple{color:#600060} .purple-background{background:#7d007d} .red{color:#bf0000} .red-background{background:#fa0000} .silver{color:#909090} .silver-background{background:#bcbcbc} .teal{color:#006060} .teal-background{background:#007d7d} .white{color:#bfbfbf} .white-background{background:#fafafa} .yellow{color:#bfbf00} .yellow-background{background:#fafa00} span.icon>.fa{cursor:default} a span.icon>.fa{cursor:inherit} .admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default} .admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c} .admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111} .admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900} .admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400} .admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000} .conum[data-value]{display:inline-block;color:#fff!important;background:rgba(0,0,0,.8);border-radius:50%;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold} .conum[data-value] *{color:#fff!important} .conum[data-value]+b{display:none} .conum[data-value]::after{content:attr(data-value)} pre .conum[data-value]{position:relative;top:-.125em} b.conum *{color:inherit!important} .conum:not([data-value]):empty{display:none} dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility} h1,h2,p,td.content,span.alt,summary{letter-spacing:-.01em} p strong,td.content strong,div.footnote strong{letter-spacing:-.005em} p,blockquote,dt,td.content,td.hdlist1,span.alt,summary{font-size:1.0625rem} p{margin-bottom:1.25rem} .sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em} .exampleblock>.content{background:#fffef7;border-color:#e0e0dc;box-shadow:0 1px 4px #e0e0dc} .print-only{display:none!important} @page{margin:1.25cm .75cm} @media print{*{box-shadow:none!important;text-shadow:none!important} html{font-size:80%} a{color:inherit!important;text-decoration:underline!important} a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important} a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em} abbr[title]{border-bottom:1px dotted} abbr[title]::after{content:" (" attr(title) ")"} pre,blockquote,tr,img,object,svg{page-break-inside:avoid} thead{display:table-header-group} svg{max-width:100%} p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3} h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid} #header,#content,#footnotes,#footer{max-width:none} #toc,.sidebarblock,.exampleblock>.content{background:none!important} #toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important} body.book #header{text-align:center} body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em} body.book #header .details{border:0!important;display:block;padding:0!important} body.book #header .details span:first-child{margin-left:0!important} body.book #header .details br{display:block} body.book #header .details br+span::before{content:none!important} body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important} body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always} .listingblock code[data-lang]::before{display:block} #footer{padding:0 .9375em} .hide-on-print{display:none!important} .print-only{display:block!important} .hide-for-print{display:none!important} .show-for-print{display:inherit!important}} @media amzn-kf8,print{#header>h1:first-child{margin-top:1.25rem} .sect1{padding:0!important} .sect1+.sect1{border:0} #footer{background:none} #footer-text{color:rgba(0,0,0,.6);font-size:.9em}} @media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}} </style> <style> pre.pygments .hll { background-color: #ffffcc } pre.pygments { background: #f8f8f8; } pre.pygments .tok-c { color: #3D7B7B; font-style: italic } /* Comment */ pre.pygments .tok-err { border: 1px solid #FF0000 } /* Error */ pre.pygments .tok-k { color: #008000; font-weight: bold } /* Keyword */ pre.pygments .tok-o { color: #666666 } /* Operator */ pre.pygments .tok-ch { color: #3D7B7B; font-style: italic } /* Comment.Hashbang */ pre.pygments .tok-cm { color: #3D7B7B; font-style: italic } /* Comment.Multiline */ pre.pygments .tok-cp { color: #9C6500 } /* Comment.Preproc */ pre.pygments .tok-cpf { color: #3D7B7B; font-style: italic } /* Comment.PreprocFile */ pre.pygments .tok-c1 { color: #3D7B7B; font-style: italic } /* Comment.Single */ pre.pygments .tok-cs { color: #3D7B7B; font-style: italic } /* Comment.Special */ pre.pygments .tok-gd { color: #A00000 } /* Generic.Deleted */ pre.pygments .tok-ge { font-style: italic } /* Generic.Emph */ pre.pygments .tok-ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ pre.pygments .tok-gr { color: #E40000 } /* Generic.Error */ pre.pygments .tok-gh { color: #000080; font-weight: bold } /* Generic.Heading */ pre.pygments .tok-gi { color: #008400 } /* Generic.Inserted */ pre.pygments .tok-go { color: #717171 } /* Generic.Output */ pre.pygments .tok-gp { color: #000080; font-weight: bold } /* Generic.Prompt */ pre.pygments .tok-gs { font-weight: bold } /* Generic.Strong */ pre.pygments .tok-gu { color: #800080; font-weight: bold } /* Generic.Subheading */ pre.pygments .tok-gt { color: #0044DD } /* Generic.Traceback */ pre.pygments .tok-kc { color: #008000; font-weight: bold } /* Keyword.Constant */ pre.pygments .tok-kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ pre.pygments .tok-kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ pre.pygments .tok-kp { color: #008000 } /* Keyword.Pseudo */ pre.pygments .tok-kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ pre.pygments .tok-kt { color: #B00040 } /* Keyword.Type */ pre.pygments .tok-m { color: #666666 } /* Literal.Number */ pre.pygments .tok-s { color: #BA2121 } /* Literal.String */ pre.pygments .tok-na { color: #687822 } /* Name.Attribute */ pre.pygments .tok-nb { color: #008000 } /* Name.Builtin */ pre.pygments .tok-nc { color: #0000FF; font-weight: bold } /* Name.Class */ pre.pygments .tok-no { color: #880000 } /* Name.Constant */ pre.pygments .tok-nd { color: #AA22FF } /* Name.Decorator */ pre.pygments .tok-ni { color: #717171; font-weight: bold } /* Name.Entity */ pre.pygments .tok-ne { color: #CB3F38; font-weight: bold } /* Name.Exception */ pre.pygments .tok-nf { color: #0000FF } /* Name.Function */ pre.pygments .tok-nl { color: #767600 } /* Name.Label */ pre.pygments .tok-nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ pre.pygments .tok-nt { color: #008000; font-weight: bold } /* Name.Tag */ pre.pygments .tok-nv { color: #19177C } /* Name.Variable */ pre.pygments .tok-ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ pre.pygments .tok-w { color: #bbbbbb } /* Text.Whitespace */ pre.pygments .tok-mb { color: #666666 } /* Literal.Number.Bin */ pre.pygments .tok-mf { color: #666666 } /* Literal.Number.Float */ pre.pygments .tok-mh { color: #666666 } /* Literal.Number.Hex */ pre.pygments .tok-mi { color: #666666 } /* Literal.Number.Integer */ pre.pygments .tok-mo { color: #666666 } /* Literal.Number.Oct */ pre.pygments .tok-sa { color: #BA2121 } /* Literal.String.Affix */ pre.pygments .tok-sb { color: #BA2121 } /* Literal.String.Backtick */ pre.pygments .tok-sc { color: #BA2121 } /* Literal.String.Char */ pre.pygments .tok-dl { color: #BA2121 } /* Literal.String.Delimiter */ pre.pygments .tok-sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ pre.pygments .tok-s2 { color: #BA2121 } /* Literal.String.Double */ pre.pygments .tok-se { color: #AA5D1F; font-weight: bold } /* Literal.String.Escape */ pre.pygments .tok-sh { color: #BA2121 } /* Literal.String.Heredoc */ pre.pygments .tok-si { color: #A45A77; font-weight: bold } /* Literal.String.Interpol */ pre.pygments .tok-sx { color: #008000 } /* Literal.String.Other */ pre.pygments .tok-sr { color: #A45A77 } /* Literal.String.Regex */ pre.pygments .tok-s1 { color: #BA2121 } /* Literal.String.Single */ pre.pygments .tok-ss { color: #19177C } /* Literal.String.Symbol */ pre.pygments .tok-bp { color: #008000 } /* Name.Builtin.Pseudo */ pre.pygments .tok-fm { color: #0000FF } /* Name.Function.Magic */ pre.pygments .tok-vc { color: #19177C } /* Name.Variable.Class */ pre.pygments .tok-vg { color: #19177C } /* Name.Variable.Global */ pre.pygments .tok-vi { color: #19177C } /* Name.Variable.Instance */ pre.pygments .tok-vm { color: #19177C } /* Name.Variable.Magic */ pre.pygments .tok-il { color: #666666 } /* Literal.Number.Integer.Long */ </style> </head> <body class="article toc2 toc-right"> <div id="header"> <h1>pugixml 1.15 quick start guide</h1> <div class="details"> <span id="author" class="author">website</span><br> <span id="email" class="email"><a href="https://pugixml.org" class="bare">https://pugixml.org</a></span><br> <span id="author2" class="author">repository</span><br> <span id="email2" class="email"><a href="https://github.com/zeux/pugixml" class="bare">https://github.com/zeux/pugixml</a></span><br> </div> <div id="toc" class="toc2"> <div id="toctitle">Table of Contents</div> <ul class="sectlevel1"> <li><a href="#introduction">Introduction</a></li> <li><a href="#install">Installation</a></li> <li><a href="#dom">Document object model</a></li> <li><a href="#loading">Loading document</a></li> <li><a href="#access">Accessing document data</a></li> <li><a href="#modify">Modifying document data</a></li> <li><a href="#saving">Saving document</a></li> <li><a href="#feedback">Feedback</a></li> <li><a href="#license">License</a></li> </ul> </div> </div> <div id="content"> <div class="sect1"> <h2 id="introduction"><a class="anchor" href="#introduction"></a><a class="link" href="#introduction">Introduction</a></h2> <div class="sectionbody"> <div class="paragraph"> <p><a href="https://pugixml.org/">pugixml</a> is a light-weight C&#43;&#43; XML processing library. It consists of a DOM-like interface with rich traversal/modification capabilities, an extremely fast XML parser which constructs the DOM tree from an XML file/buffer, and an XPath 1.0 implementation for complex data-driven tree queries. Full Unicode support is also available, with two Unicode interface variants and conversions between different Unicode encodings (which happen automatically during parsing/saving). The library is extremely portable and easy to integrate and use. pugixml is developed and maintained since 2006 and has many users. All code is distributed under the <a href="#license">MIT license</a>, making it completely free to use in both open-source and proprietary applications.</p> </div> <div class="paragraph"> <p>pugixml enables very fast, convenient and memory-efficient XML document processing. However, since pugixml has a DOM parser, it can&#8217;t process XML documents that do not fit in memory; also the parser is a non-validating one, so if you need DTD/Schema validation, the library is not for you.</p> </div> <div class="paragraph"> <p>This is the quick start guide for pugixml, which purpose is to enable you to start using the library quickly. Many important library features are either not described at all or only mentioned briefly; for more complete information you <a href="manual.html">should read the complete manual</a>.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> No documentation is perfect; neither is this one. If you find errors or omissions, please don’t hesitate to <a href="https://github.com/zeux/pugixml/issues/new">submit an issue or open a pull request</a> with a fix. </td> </tr> </table> </div> </div> </div> <div class="sect1"> <h2 id="install"><a class="anchor" href="#install"></a><a class="link" href="#install">Installation</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>You can download the latest source distribution as an archive:</p> </div> <div class="paragraph"> <p><a href="https://github.com/zeux/pugixml/releases/download/v1.15/pugixml-1.15.zip">pugixml-1.15.zip</a> (Windows line endings) / <a href="https://github.com/zeux/pugixml/releases/download/v1.15/pugixml-1.15.tar.gz">pugixml-1.15.tar.gz</a> (Unix line endings)</p> </div> <div class="paragraph"> <p>The distribution contains library source, documentation (the guide you&#8217;re reading now and the manual) and some code examples. After downloading the distribution, install pugixml by extracting all files from the compressed archive.</p> </div> <div class="paragraph"> <p>The complete pugixml source consists of three files - one source file, <code>pugixml.cpp</code>, and two header files, <code>pugixml.hpp</code> and <code>pugiconfig.hpp</code>. <code>pugixml.hpp</code> is the primary header which you need to include in order to use pugixml classes/functions. The rest of this guide assumes that <code>pugixml.hpp</code> is either in the current directory or in one of include directories of your projects, so that <code>#include "pugixml.hpp"</code> can find the header; however you can also use relative path (i.e. <code>#include "../libs/pugixml/src/pugixml.hpp"</code>) or include directory-relative path (i.e. <code>#include &lt;xml/thirdparty/pugixml/src/pugixml.hpp&gt;</code>).</p> </div> <div class="paragraph"> <p>The easiest way to build pugixml is to compile the source file, <code>pugixml.cpp</code>, along with the existing library/executable. This process depends on the method of building your application; for example, if you&#8217;re using Microsoft Visual Studio <sup class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnotedef_1" title="View footnote.">1</a>]</sup>, Apple Xcode, Code::Blocks or any other IDE, just <strong>add <code>pugixml.cpp</code> to one of your projects</strong>. There are other building methods available, including building pugixml as a standalone static/shared library; <a href="manual.html#install.building">read the manual</a> for further information.</p> </div> </div> </div> <div class="sect1"> <h2 id="dom"><a class="anchor" href="#dom"></a><a class="link" href="#dom">Document object model</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml stores XML data in DOM-like way: the entire XML document (both document structure and element data) is stored in memory as a tree. The tree can be loaded from character stream (file, string, C&#43;&#43; I/O stream), then traversed via special API or XPath expressions. The whole tree is mutable: both node structure and node/attribute data can be changed at any time. Finally, the result of document transformations can be saved to a character stream (file, C&#43;&#43; I/O stream or custom transport).</p> </div> <div class="paragraph"> <p>The root of the tree is the document itself, which corresponds to C&#43;&#43; type <code>xml_document</code>. Document has one or more child nodes, which correspond to C&#43;&#43; type <code>xml_node</code>. Nodes have different types; depending on a type, a node can have a collection of child nodes, a collection of attributes, which correspond to C&#43;&#43; type <code>xml_attribute</code>, and some additional data (i.e. name).</p> </div> <div class="paragraph"> <p>The most common node types are:</p> </div> <div class="ulist"> <ul> <li> <p>Document node (<code>node_document</code>) - this is the root of the tree, which consists of several child nodes. This node corresponds to <code>xml_document</code> class; note that <code>xml_document</code> is a sub-class of <code>xml_node</code>, so the entire node interface is also available.</p> </li> <li> <p>Element/tag node (<code>node_element</code>) - this is the most common type of node, which represents XML elements. Element nodes have a name, a collection of attributes and a collection of child nodes (both of which may be empty). The attribute is a simple name/value pair.</p> </li> <li> <p>Plain character data nodes (<code>node_pcdata</code>) represent plain text in XML. PCDATA nodes have a value, but do not have name or children/attributes. Note that <strong>plain character data is not a part of the element node but instead has its own node</strong>; for example, an element node can have several child PCDATA nodes.</p> </li> </ul> </div> <div class="paragraph"> <p>Despite the fact that there are several node types, there are only three C&#43;&#43; types representing the tree (<code>xml_document</code>, <code>xml_node</code>, <code>xml_attribute</code>); some operations on <code>xml_node</code> are only valid for certain node types. They are described below.</p> </div> <div class="admonitionblock note"> <table> <tr> <td class="icon"> <div class="title">Note</div> </td> <td class="content"> All pugixml classes and functions are located in <code>pugi</code> namespace; you have to either use explicit name qualification (i.e. <code>pugi::xml_node</code>), or to gain access to relevant symbols via <code>using</code> directive (i.e. <code>using pugi::xml_node;</code> or <code>using namespace pugi;</code>). </td> </tr> </table> </div> <div class="paragraph"> <p><code>xml_document</code> is the owner of the entire document structure; destroying the document destroys the whole tree. The interface of <code>xml_document</code> consists of loading functions, saving functions and the entire interface of <code>xml_node</code>, which allows for document inspection and/or modification. Note that while <code>xml_document</code> is a sub-class of <code>xml_node</code>, <code>xml_node</code> is not a polymorphic type; the inheritance is present only to simplify usage.</p> </div> <div class="paragraph"> <p><code>xml_node</code> is the handle to document node; it can point to any node in the document, including document itself. There is a common interface for nodes of all types. Note that <code>xml_node</code> is only a handle to the actual node, not the node itself - you can have several <code>xml_node</code> handles pointing to the same underlying object. Destroying <code>xml_node</code> handle does not destroy the node and does not remove it from the tree.</p> </div> <div class="paragraph"> <p>There is a special value of <code>xml_node</code> type, known as null node or empty node. It does not correspond to any node in any document, and thus resembles null pointer. However, all operations are defined on empty nodes; generally the operations don&#8217;t do anything and return empty nodes/attributes or empty strings as their result. This is useful for chaining calls; i.e. you can get the grandparent of a node like so: <code>node.parent().parent()</code>; if a node is a null node or it does not have a parent, the first <code>parent()</code> call returns null node; the second <code>parent()</code> call then also returns null node, so you don&#8217;t have to check for errors twice. You can test if a handle is null via implicit boolean cast: <code>if (node) { &#8230;&#8203; }</code> or <code>if (!node) { &#8230;&#8203; }</code>.</p> </div> <div class="paragraph"> <p><code>xml_attribute</code> is the handle to an XML attribute; it has the same semantics as <code>xml_node</code>, i.e. there can be several <code>xml_attribute</code> handles pointing to the same underlying object and there is a special null attribute value, which propagates to function results.</p> </div> <div class="paragraph"> <p>There are two choices of interface and internal representation when configuring pugixml: you can either choose the UTF-8 (also called char) interface or UTF-16/32 (also called wchar_t) one. The choice is controlled via <code>PUGIXML_WCHAR_MODE</code> define; you can set it via <code>pugiconfig.hpp</code> or via preprocessor options. All tree functions that work with strings work with either C-style null terminated strings or STL strings of the selected character type. <a href="manual.html#dom.unicode">Read the manual</a> for additional information on Unicode interface.</p> </div> </div> </div> <div class="sect1"> <h2 id="loading"><a class="anchor" href="#loading"></a><a class="link" href="#loading">Loading document</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml provides several functions for loading XML data from various places - files, C&#43;&#43; iostreams, memory buffers. All functions use an extremely fast non-validating parser. This parser is not fully W3C conformant - it can load any valid XML document, but does not perform some well-formedness checks. While considerable effort is made to reject invalid XML documents, some validation is not performed because of performance reasons. XML data is always converted to internal character format before parsing. pugixml supports all popular Unicode encodings (UTF-8, UTF-16 (big and little endian), UTF-32 (big and little endian); UCS-2 is naturally supported since it&#8217;s a strict subset of UTF-16) and handles all encoding conversions automatically.</p> </div> <div class="paragraph"> <p>The most common source of XML data is files; pugixml provides a separate function for loading XML document from file. This function accepts file path as its first argument, and also two optional arguments, which specify parsing options and input data encoding, which are described in the manual.</p> </div> <div class="paragraph"> <p>This is an example of loading XML document from file (<a href="samples/load_file.cpp" class="bare">samples/load_file.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_file</span><span class="tok-p">(</span><span class="tok-s">&quot;tree.xml&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Load result: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, mesh name: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;mesh&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p><code>load_file</code>, as well as other loading functions, destroys the existing document tree and then tries to load the new tree from the specified file. The result of the operation is returned in an <code>xml_parse_result</code> object; this object contains the operation status, and the related information (i.e. last successfully parsed position in the input file, if parsing fails).</p> </div> <div class="paragraph"> <p>Parsing result object can be implicitly converted to <code>bool</code>; if you do not want to handle parsing errors thoroughly, you can just check the return value of load functions as if it was a <code>bool</code>: <code>if (doc.load_file("file.xml")) { &#8230;&#8203; } else { &#8230;&#8203; }</code>. Otherwise you can use the <code>status</code> member to get parsing status, or the <code>description()</code> member function to get the status in a string form.</p> </div> <div class="paragraph"> <p>This is an example of handling loading errors (<a href="samples/load_error_handling.cpp" class="bare">samples/load_error_handling.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_document</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">;</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_string</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">);</span> <span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">result</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;XML [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;] parsed without errors, attr value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;attr&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-k">else</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;XML [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;] parsed with errors, attr value: [&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;attr&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Error description: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">description</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Error offset: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">offset</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; (error at [...&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-w"> </span><span class="tok-o">+</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">offset</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;]</span><span class="tok-se">\n\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Sometimes XML data should be loaded from some other source than file, i.e. HTTP URL; also you may want to load XML data from file using non-standard functions, i.e. to use your virtual file system facilities or to load XML from gzip-compressed files. These scenarios either require loading document from memory, in which case you should prepare a contiguous memory block with all XML data and to pass it to one of buffer loading functions, or loading document from C&#43;&#43; IOstream, in which case you should provide an object which implements <code>std::istream</code> or <code>std::wistream</code> interface.</p> </div> <div class="paragraph"> <p>There are different functions for loading document from memory; they treat the passed buffer as either an immutable one (<code>load_buffer</code>), a mutable buffer which is owned by the caller (<code>load_buffer_inplace</code>), or a mutable buffer which ownership belongs to pugixml (<code>load_buffer_inplace_own</code>). There is also a simple helper function, <code>xml_document::load</code>, for cases when you want to load the XML document from null-terminated character string.</p> </div> <div class="paragraph"> <p>This is an example of loading XML document from memory using one of these functions (<a href="samples/load_memory.cpp" class="bare">samples/load_memory.cpp</a>); read the sample code for more examples:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-p">[]</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;&lt;mesh name=&#39;sphere&#39;&gt;&lt;bounds&gt;0 0 1 1&lt;/bounds&gt;&lt;/mesh&gt;&quot;</span><span class="tok-p">;</span> <span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-k">sizeof</span><span class="tok-p">(</span><span class="tok-n">source</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// You can use load_buffer_inplace to load document from mutable memory block; the block&#39;s lifetime must exceed that of document</span> <span class="tok-kt">char</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-k">new</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-p">[</span><span class="tok-n">size</span><span class="tok-p">];</span> <span class="tok-n">memcpy</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">source</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-c1">// The block can be allocated by any method; the block is modified during parsing</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load_buffer_inplace</span><span class="tok-p">(</span><span class="tok-n">buffer</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-c1">// You have to destroy the block yourself after the document is no longer used</span> <span class="tok-k">delete</span><span class="tok-p">[]</span><span class="tok-w"> </span><span class="tok-n">buffer</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>This is a simple example of loading XML document from file using streams (<a href="samples/load_stream.cpp" class="bare">samples/load_stream.cpp</a>); read the sample code for more complex examples involving wide streams and locales:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">ifstream</span><span class="tok-w"> </span><span class="tok-n">stream</span><span class="tok-p">(</span><span class="tok-s">&quot;weekly-utf-8.xml&quot;</span><span class="tok-p">);</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_parse_result</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">load</span><span class="tok-p">(</span><span class="tok-n">stream</span><span class="tok-p">);</span></code></pre> </div> </div> </div> </div> <div class="sect1"> <h2 id="access"><a class="anchor" href="#access"></a><a class="link" href="#access">Accessing document data</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>pugixml features an extensive interface for getting various types of data from the document and for traversing the document. You can use various accessors to get node/attribute data, you can traverse the child node/attribute lists via accessors or iterators, you can do depth-first traversals with <code>xml_tree_walker</code> objects, and you can use XPath for complex data-driven queries.</p> </div> <div class="paragraph"> <p>You can get node or attribute name via <code>name()</code> accessor, and value via <code>value()</code> accessor. Note that both functions never return null pointers - they either return a string with the relevant content, or an empty string if name/value is absent or if the handle is null. Also there are two notable things for reading values:</p> </div> <div class="ulist"> <ul> <li> <p>It is common to store data as text contents of some node - i.e. <code>&lt;node&gt;&lt;description&gt;This is a node&lt;/description&gt;&lt;/node&gt;</code>. In this case, <code>&lt;description&gt;</code> node does not have a value, but instead has a child of type <code>node_pcdata</code> with value <code>"This is a node"</code>. pugixml provides <code>child_value()</code> and <code>text()</code> helper functions to parse such data.</p> </li> <li> <p>In many cases attribute values have types that are not strings - i.e. an attribute may always contain values that should be treated as integers, despite the fact that they are represented as strings in XML. pugixml provides several accessors that convert attribute value to some other type.</p> </li> </ul> </div> <div class="paragraph"> <p>This is an example of using these functions (<a href="samples/traverse_base.cpp" class="bare">samples/traverse_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;: AllowRemote &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;AllowRemote&quot;</span><span class="tok-p">).</span><span class="tok-n">as_bool</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, Timeout &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Timeout&quot;</span><span class="tok-p">).</span><span class="tok-n">as_int</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, Description &#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">child_value</span><span class="tok-p">(</span><span class="tok-s">&quot;Description&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Since a lot of document traversal consists of finding the node/attribute with the correct name, there are special functions for that purpose. For example, <code>child("Tool")</code> returns the first node which has the name <code>"Tool"</code>, or null handle if there is no such node. This is an example of using such functions (<a href="samples/traverse_base.cpp" class="bare">samples/traverse_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool for *.dae generation: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">find_child_by_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;OutputFileMasks&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-s">&quot;*.dae&quot;</span><span class="tok-p">).</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">);</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">next_sibling</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Child node lists and attribute lists are simply double-linked lists; while you can use <code>previous_sibling</code>/<code>next_sibling</code> and other such functions for iteration, pugixml additionally provides node and attribute iterators, so that you can treat nodes as containers of other nodes or attributes. All iterators are bidirectional and support all usual iterator operations. The iterators are invalidated if the node/attribute objects they&#8217;re pointing to are removed from the tree; adding nodes/attributes does not invalidate any iterators.</p> </div> <div class="paragraph"> <p>Here is an example of using iterators for document traversal (<a href="samples/traverse_iter.cpp" class="bare">samples/traverse_iter.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node_iterator</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">it</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool:&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute_iterator</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-o">-&gt;</span><span class="tok-n">attributes_begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-o">-&gt;</span><span class="tok-n">attributes_end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">ait</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-o">-&gt;</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">ait</span><span class="tok-o">-&gt;</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If your C&#43;&#43; compiler supports range-based for-loop (this is a C&#43;&#43;11 feature, at the time of writing it&#8217;s supported by Microsoft Visual Studio 11 Beta, GCC 4.6 and Clang 3.0), you can use it to enumerate nodes/attributes. Additional helpers are provided to support this; note that they are also compatible with <a href="http://www.boost.org/libs/foreach/">Boost Foreach</a>, and possibly other pre-C&#43;&#43;11 foreach facilities.</p> </div> <div class="paragraph"> <p>Here is an example of using C&#43;&#43;11 range-based for loop for document traversal (<a href="samples/traverse_rangefor.cpp" class="bare">samples/traverse_rangefor.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">children</span><span class="tok-p">(</span><span class="tok-s">&quot;Tool&quot;</span><span class="tok-p">))</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tool:&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">attributes</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">tool</span><span class="tok-p">.</span><span class="tok-n">children</span><span class="tok-p">())</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, child &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">child</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">();</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-p">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The methods described above allow traversal of immediate children of some node; if you want to do a deep tree traversal, you&#8217;ll have to do it via a recursive function or some equivalent method. However, pugixml provides a helper for depth-first traversal of a subtree. In order to use it, you have to implement <code>xml_tree_walker</code> interface and to call <code>traverse</code> function.</p> </div> <div class="paragraph"> <p>This is an example of traversing tree hierarchy with xml_tree_walker (<a href="samples/traverse_walker.cpp" class="bare">samples/traverse_walker.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">simple_walker</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_tree_walker</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">bool</span><span class="tok-w"> </span><span class="tok-nf">for_each</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-o">&amp;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-kt">int</span><span class="tok-w"> </span><span class="tok-n">i</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mi">0</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-n">i</span><span class="tok-w"> </span><span class="tok-o">&lt;</span><span class="tok-w"> </span><span class="tok-n">depth</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">i</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot; &quot;</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-c1">// indentation</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node_types</span><span class="tok-p">[</span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">type</span><span class="tok-p">()]</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;: name=&#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;, value=&#39;&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;&#39;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">return</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">;</span><span class="tok-w"> </span><span class="tok-c1">// continue traversal</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-p">};</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">simple_walker</span><span class="tok-w"> </span><span class="tok-n">walker</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">traverse</span><span class="tok-p">(</span><span class="tok-n">walker</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Finally, for complex queries often a higher-level DSL is needed. pugixml provides an implementation of XPath 1.0 language for such queries. The complete description of XPath usage can be found in the manual, but here are some examples:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_nodes</span><span class="tok-p">(</span><span class="tok-s">&quot;/Profile/Tools/Tool[@AllowRemote=&#39;true&#39; and @DeriveCaptionFrom=&#39;lastparam&#39;]&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Tools:</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-k">for</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node_set</span><span class="tok-o">::</span><span class="tok-n">const_iterator</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">begin</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-n">it</span><span class="tok-w"> </span><span class="tok-o">!=</span><span class="tok-w"> </span><span class="tok-n">tools</span><span class="tok-p">.</span><span class="tok-n">end</span><span class="tok-p">();</span><span class="tok-w"> </span><span class="tok-o">++</span><span class="tok-n">it</span><span class="tok-p">)</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-o">*</span><span class="tok-n">it</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-p">}</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xpath_node</span><span class="tok-w"> </span><span class="tok-n">build_tool</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">select_node</span><span class="tok-p">(</span><span class="tok-s">&quot;//Tool[contains(Description, &#39;build system&#39;)]&quot;</span><span class="tok-p">);</span> <span class="tok-k">if</span><span class="tok-w"> </span><span class="tok-p">(</span><span class="tok-n">build_tool</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Build tool: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">build_tool</span><span class="tok-p">.</span><span class="tok-n">node</span><span class="tok-p">().</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;Filename&quot;</span><span class="tok-p">).</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> XPath functions throw <code>xpath_exception</code> objects on error; the sample above does not catch these exceptions. </td> </tr> </table> </div> </div> </div> <div class="sect1"> <h2 id="modify"><a class="anchor" href="#modify"></a><a class="link" href="#modify">Modifying document data</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>The document in pugixml is fully mutable: you can completely change the document structure and modify the data of nodes/attributes. All functions take care of memory management and structural integrity themselves, so they always result in structurally valid tree - however, it is possible to create an invalid XML tree (for example, by adding two attributes with the same name or by setting attribute/node name to empty/invalid string). Tree modification is optimized for performance and for memory consumption, so if you have enough memory you can create documents from scratch with pugixml and later save them to file/stream instead of relying on error-prone manual text writing and without too much overhead.</p> </div> <div class="paragraph"> <p>All member functions that change node/attribute data or structure are non-constant and thus can not be called on constant handles. However, you can easily convert constant handle to non-constant one by simple assignment: <code>void foo(const pugi::xml_node&amp; n) { pugi::xml_node nc = n; }</code>, so const-correctness here mainly provides additional documentation.</p> </div> <div class="paragraph"> <p>As discussed before, nodes can have name and value, both of which are strings. Depending on node type, name or value may be absent. You can use <code>set_name</code> and <code>set_value</code> member functions to set them. Similar functions are available for attributes; however, the <code>set_value</code> function is overloaded for some other types except strings, like floating-point numbers. Also, attribute value can be set using an assignment operator. This is an example of setting node/attribute name and value (<a href="samples/modify_base.cpp" class="bare">samples/modify_base.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// change node name</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;notnode&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new node name: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// change comment text</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;useless comment&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new comment text: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can&#39;t change value of the element or name of the comment</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">last_child</span><span class="tok-p">().</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;id&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// change attribute name/value</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_name</span><span class="tok-p">(</span><span class="tok-s">&quot;key&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;345&quot;</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;, new attribute: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">name</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;=&quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can use numbers or booleans</span> <span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-mf">1.234</span><span class="tok-p">);</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;new attribute value: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span> <span class="tok-c1">// we can also use assignment operators for more concise code</span> <span class="tok-n">attr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-nb">true</span><span class="tok-p">;</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;final attribute value: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">attr</span><span class="tok-p">.</span><span class="tok-n">value</span><span class="tok-p">()</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>Nodes and attributes do not exist without a document tree, so you can&#8217;t create them without adding them to some document. A node or attribute can be created at the end of node/attribute list or before/after some other node. All insertion functions return the handle to newly created object on success, and null handle on failure. Even if the operation fails (for example, if you&#8217;re trying to add a child node to PCDATA node), the document remains in consistent state, but the requested node/attribute is not added.</p> </div> <div class="admonitionblock caution"> <table> <tr> <td class="icon"> <div class="title">Caution</div> </td> <td class="content"> <code>attribute()</code> and <code>child()</code> functions do not add attributes or nodes to the tree, so code like <code>node.attribute("id") = 123;</code> will not do anything if <code>node</code> does not have an attribute with name <code>"id"</code>. Make sure you&#8217;re operating with existing attributes/nodes by adding them if necessary. </td> </tr> </table> </div> <div class="paragraph"> <p>This is an example of adding new attributes/nodes to the document (<a href="samples/modify_add.cpp" class="bare">samples/modify_add.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// add node with some name</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// add description node with text child</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">descr</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">);</span> <span class="tok-n">descr</span><span class="tok-p">.</span><span class="tok-n">append_child</span><span class="tok-p">(</span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">node_pcdata</span><span class="tok-p">).</span><span class="tok-n">set_value</span><span class="tok-p">(</span><span class="tok-s">&quot;Simple node&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// add param node before the description</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">insert_child_before</span><span class="tok-p">(</span><span class="tok-s">&quot;param&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">descr</span><span class="tok-p">);</span> <span class="tok-c1">// add attributes to param node</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;version&quot;</span><span class="tok-p">;</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">append_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;value&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-mf">1.1</span><span class="tok-p">;</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">insert_attribute_after</span><span class="tok-p">(</span><span class="tok-s">&quot;type&quot;</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">))</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-s">&quot;float&quot;</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>If you do not want your document to contain some node or attribute, you can remove it with <code>remove_attribute</code> and <code>remove_child</code> functions. Removing the attribute or node invalidates all handles to the same underlying object, and also invalidates all iterators pointing to the same object. Removing node also invalidates all past-the-end iterators to its attribute or child node list. Be careful to ensure that all such handles and iterators either do not exist or are not used after the attribute/node is removed.</p> </div> <div class="paragraph"> <p>This is an example of removing attributes/nodes from the document (<a href="samples/modify_remove.cpp" class="bare">samples/modify_remove.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// remove description node with the whole subtree</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;node&quot;</span><span class="tok-p">);</span> <span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">remove_child</span><span class="tok-p">(</span><span class="tok-s">&quot;description&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// remove value attribute</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_node</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">node</span><span class="tok-p">.</span><span class="tok-n">child</span><span class="tok-p">(</span><span class="tok-s">&quot;param&quot;</span><span class="tok-p">);</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">remove_attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;value&quot;</span><span class="tok-p">);</span> <span class="tok-c1">// we can also remove nodes/attributes by handles</span> <span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_attribute</span><span class="tok-w"> </span><span class="tok-n">id</span><span class="tok-w"> </span><span class="tok-o">=</span><span class="tok-w"> </span><span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">attribute</span><span class="tok-p">(</span><span class="tok-s">&quot;name&quot;</span><span class="tok-p">);</span> <span class="tok-n">param</span><span class="tok-p">.</span><span class="tok-n">remove_attribute</span><span class="tok-p">(</span><span class="tok-n">id</span><span class="tok-p">);</span></code></pre> </div> </div> </div> </div> <div class="sect1"> <h2 id="saving"><a class="anchor" href="#saving"></a><a class="link" href="#saving">Saving document</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>Often after creating a new document or loading the existing one and processing it, it is necessary to save the result back to file. Also it is occasionally useful to output the whole document or a subtree to some stream; use cases include debug printing, serialization via network or other text-oriented medium, etc. pugixml provides several functions to output any subtree of the document to a file, stream or another generic transport interface; these functions allow to customize the output format, and also perform necessary encoding conversions.</p> </div> <div class="paragraph"> <p>Before writing to the destination the node/attribute data is properly formatted according to the node type; all special XML symbols, such as &lt; and &amp;, are properly escaped. In order to guard against forgotten node/attribute names, empty node/attribute names are printed as <code>":anonymous"</code>. For well-formed output, make sure all node and attribute names are set to meaningful values.</p> </div> <div class="paragraph"> <p>If you want to save the whole document to a file, you can use the <code>save_file</code> function, which returns <code>true</code> on success. This is a simple example of saving XML document to file (<a href="samples/save_file.cpp" class="bare">samples/save_file.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// save document to file</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Saving result: &quot;</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save_file</span><span class="tok-p">(</span><span class="tok-s">&quot;save_file_output.xml&quot;</span><span class="tok-p">)</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">endl</span><span class="tok-p">;</span></code></pre> </div> </div> <div class="paragraph"> <p>To enhance interoperability pugixml provides functions for saving document to any object which implements C&#43;&#43; <code>std::ostream</code> interface. This allows you to save documents to any standard C&#43;&#43; stream (i.e. file stream) or any third-party compliant implementation (i.e. Boost Iostreams). Most notably, this allows for easy debug output, since you can use <code>std::cout</code> stream as saving target. There are two functions, one works with narrow character streams, another handles wide character ones.</p> </div> <div class="paragraph"> <p>This is a simple example of saving XML document to standard output (<a href="samples/save_stream.cpp" class="bare">samples/save_stream.cpp</a>):</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-c1">// save document to standard output</span> <span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-w"> </span><span class="tok-o">&lt;&lt;</span><span class="tok-w"> </span><span class="tok-s">&quot;Document:</span><span class="tok-se">\n</span><span class="tok-s">&quot;</span><span class="tok-p">;</span> <span class="tok-n">doc</span><span class="tok-p">.</span><span class="tok-n">save</span><span class="tok-p">(</span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">cout</span><span class="tok-p">);</span></code></pre> </div> </div> <div class="paragraph"> <p>All of the above saving functions are implemented in terms of writer interface. This is a simple interface with a single function, which is called several times during output process with chunks of document data as input. In order to output the document via some custom transport, for example sockets, you should create an object which implements <code>xml_writer_file</code> interface and pass it to <code>xml_document::save</code> function.</p> </div> <div class="paragraph"> <p>This is a simple example of custom writer for saving document data to STL string (<a href="samples/save_custom_writer.cpp" class="bare">samples/save_custom_writer.cpp</a>); read the sample code for more complex examples:</p> </div> <div class="listingblock"> <div class="content"> <pre class="pygments highlight"><code data-lang="c++"><span></span><span class="tok-k">struct</span><span class="tok-w"> </span><span class="tok-nc">xml_string_writer</span><span class="tok-o">:</span><span class="tok-w"> </span><span class="tok-n">pugi</span><span class="tok-o">::</span><span class="tok-n">xml_writer</span> <span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">std</span><span class="tok-o">::</span><span class="tok-n">string</span><span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">;</span> <span class="tok-w"> </span><span class="tok-k">virtual</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-w"> </span><span class="tok-nf">write</span><span class="tok-p">(</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">void</span><span class="tok-o">*</span><span class="tok-w"> </span><span class="tok-n">data</span><span class="tok-p">,</span><span class="tok-w"> </span><span class="tok-kt">size_t</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">)</span> <span class="tok-w"> </span><span class="tok-p">{</span> <span class="tok-w"> </span><span class="tok-n">result</span><span class="tok-p">.</span><span class="tok-n">append</span><span class="tok-p">(</span><span class="tok-k">static_cast</span><span class="tok-o">&lt;</span><span class="tok-k">const</span><span class="tok-w"> </span><span class="tok-kt">char</span><span class="tok-o">*&gt;</span><span class="tok-p">(</span><span class="tok-n">data</span><span class="tok-p">),</span><span class="tok-w"> </span><span class="tok-n">size</span><span class="tok-p">);</span> <span class="tok-w"> </span><span class="tok-p">}</span> <span class="tok-p">};</span></code></pre> </div> </div> <div class="paragraph"> <p>While the previously described functions save the whole document to the destination, it is easy to save a single subtree. Instead of calling <code>xml_document::save</code>, just call <code>xml_node::print</code> function on the target node. You can save node contents to C&#43;&#43; IOstream object or custom writer in this way. Saving a subtree slightly differs from saving the whole document; <a href="manual.html#saving.subtree">read the manual</a> for more information.</p> </div> </div> </div> <div class="sect1"> <h2 id="feedback"><a class="anchor" href="#feedback"></a><a class="link" href="#feedback">Feedback</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>If you believe you&#8217;ve found a bug in pugixml, please file an issue via <a href="https://github.com/zeux/pugixml/issues/new">issue submission form</a>. Be sure to include the relevant information so that the bug can be reproduced: the version of pugixml, compiler version and target architecture, the code that uses pugixml and exhibits the bug, etc. Feature requests and contributions can be filed as issues, too.</p> </div> <div class="paragraph"> <p>If filing an issue is not possible due to privacy or other concerns, you can contact pugixml author by e-mail directly: <a href="mailto:arseny.kapoulkine@gmail.com">arseny.kapoulkine@gmail.com</a>.</p> </div> </div> </div> <div class="sect1"> <h2 id="license"><a class="anchor" href="#license"></a><a class="link" href="#license">License</a></h2> <div class="sectionbody"> <div class="paragraph"> <p>The pugixml library is distributed under the MIT license:</p> </div> <div class="literalblock"> <div class="content"> <pre>Copyright (c) 2006-2026 Arseny Kapoulkine Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</pre> </div> </div> <div class="paragraph"> <p>This means that you can freely use pugixml in your applications, both open-source and proprietary. If you use pugixml in a product, it is sufficient to add an acknowledgment like this to the product distribution:</p> </div> <div class="literalblock"> <div class="content"> <pre>This software is based on pugixml library (https://pugixml.org). pugixml is Copyright (C) 2006-2026 Arseny Kapoulkine.</pre> </div> </div> </div> </div> </div> <div id="footnotes"> <hr> <div class="footnote" id="_footnotedef_1"> <a href="#_footnoteref_1">1</a>. All trademarks used are properties of their respective owners. </div> </div> <div id="footer"> <div id="footer-text"> Last updated 2026-01-02 09:51:54 -0800 </div> </div> </body> </html>
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/custom_memory_management.cpp
C++
#include "pugixml.hpp" #include <new> // tag::decl[] void* custom_allocate(size_t size) { return new (std::nothrow) char[size]; } void custom_deallocate(void* ptr) { delete[] static_cast<char*>(ptr); } // end::decl[] int main() { // tag::call[] pugi::set_memory_management_functions(custom_allocate, custom_deallocate); // end::call[] pugi::xml_document doc; doc.load_string("<node/>"); } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/include.cpp
C++
#include "pugixml.hpp" #include <string.h> #include <iostream> // tag::code[] bool load_preprocess(pugi::xml_document& doc, const char* path); bool preprocess(pugi::xml_node node) { for (pugi::xml_node child = node.first_child(); child; ) { if (child.type() == pugi::node_pi && strcmp(child.name(), "include") == 0) { pugi::xml_node include = child; // load new preprocessed document (note: ideally this should handle relative paths) const char* path = include.value(); pugi::xml_document doc; if (!load_preprocess(doc, path)) return false; // insert the comment marker above include directive node.insert_child_before(pugi::node_comment, include).set_value(path); // copy the document above the include directive (this retains the original order!) for (pugi::xml_node ic = doc.first_child(); ic; ic = ic.next_sibling()) { node.insert_copy_before(ic, include); } // remove the include node and move to the next child child = child.next_sibling(); node.remove_child(include); } else { if (!preprocess(child)) return false; child = child.next_sibling(); } } return true; } bool load_preprocess(pugi::xml_document& doc, const char* path) { pugi::xml_parse_result result = doc.load_file(path, pugi::parse_default | pugi::parse_pi); // for <?include?> return result ? preprocess(doc) : false; } // end::code[] int main() { pugi::xml_document doc; if (!load_preprocess(doc, "character.xml")) return -1; doc.print(std::cout); } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/load_error_handling.cpp
C++
#include "pugixml.hpp" #include <iostream> void check_xml(const char* source) { // tag::code[] pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(source); if (result) { std::cout << "XML [" << source << "] parsed without errors, attr value: [" << doc.child("node").attribute("attr").value() << "]\n\n"; } else { std::cout << "XML [" << source << "] parsed with errors, attr value: [" << doc.child("node").attribute("attr").value() << "]\n"; std::cout << "Error description: " << result.description() << "\n"; std::cout << "Error offset: " << result.offset << " (error at [..." << (source + result.offset) << "]\n\n"; } // end::code[] } int main() { check_xml("<node attr='value'><child>text</child></node>"); check_xml("<node attr='value'><child>text</chil></node>"); check_xml("<node attr='value'><child>text</child>"); check_xml("<node attr='value\"><child>text</child></node>"); check_xml("<node attr='value'><#tag /></node>"); } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/load_file.cpp
C++
#include "pugixml.hpp" #include <iostream> int main() { // tag::code[] pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file("tree.xml"); std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; // end::code[] } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/load_memory.cpp
C++
#include "pugixml.hpp" #include <iostream> #include <cstring> int main() { // tag::decl[] const char source[] = "<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>"; size_t size = sizeof(source); // end::decl[] pugi::xml_document doc; { // tag::load_buffer[] // You can use load_buffer to load document from immutable memory block: pugi::xml_parse_result result = doc.load_buffer(source, size); // end::load_buffer[] std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; } { // tag::load_buffer_inplace_begin[] // You can use load_buffer_inplace to load document from mutable memory block; the block's lifetime must exceed that of document char* buffer = new char[size]; memcpy(buffer, source, size); // The block can be allocated by any method; the block is modified during parsing pugi::xml_parse_result result = doc.load_buffer_inplace(buffer, size); // end::load_buffer_inplace_begin[] std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; // tag::load_buffer_inplace_end[] // You have to destroy the block yourself after the document is no longer used delete[] buffer; // end::load_buffer_inplace_end[] } { // tag::load_buffer_inplace_own[] // You can use load_buffer_inplace_own to load document from mutable memory block and to pass the ownership of this block // The block has to be allocated via pugixml allocation function - using i.e. operator new here is incorrect char* buffer = static_cast<char*>(pugi::get_memory_allocation_function()(size)); memcpy(buffer, source, size); // The block will be deleted by the document pugi::xml_parse_result result = doc.load_buffer_inplace_own(buffer, size); // end::load_buffer_inplace_own[] std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; } { // tag::load_string[] // You can use load to load document from null-terminated strings, for example literals: pugi::xml_parse_result result = doc.load_string("<mesh name='sphere'><bounds>0 0 1 1</bounds></mesh>"); // end::load_string[] std::cout << "Load result: " << result.description() << ", mesh name: " << doc.child("mesh").attribute("name").value() << std::endl; } } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/load_options.cpp
C++
#include "pugixml.hpp" #include <iostream> int main() { pugi::xml_document doc; // tag::code[] const char* source = "<!--comment--><node>&lt;</node>"; // Parsing with default options; note that comment node is not added to the tree, and entity reference &lt; is expanded doc.load_string(source); std::cout << "First node value: [" << doc.first_child().value() << "], node child value: [" << doc.child_value("node") << "]\n"; // Parsing with additional parse_comments option; comment node is now added to the tree doc.load_string(source, pugi::parse_default | pugi::parse_comments); std::cout << "First node value: [" << doc.first_child().value() << "], node child value: [" << doc.child_value("node") << "]\n"; // Parsing with additional parse_comments option and without the (default) parse_escapes option; &lt; is not expanded doc.load_string(source, (pugi::parse_default | pugi::parse_comments) & ~pugi::parse_escapes); std::cout << "First node value: [" << doc.first_child().value() << "], node child value: [" << doc.child_value("node") << "]\n"; // Parsing with minimal option mask; comment node is not added to the tree, and &lt; is not expanded doc.load_string(source, pugi::parse_minimal); std::cout << "First node value: [" << doc.first_child().value() << "], node child value: [" << doc.child_value("node") << "]\n"; // end::code[] } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/load_stream.cpp
C++
#include "pugixml.hpp" #include <fstream> #include <iomanip> #include <iostream> void print_doc(const char* message, const pugi::xml_document& doc, const pugi::xml_parse_result& result) { std::cout << message << "\t: load result '" << result.description() << "'" << ", first character of root name: U+" << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << pugi::as_wide(doc.first_child().name())[0] << ", year: " << doc.first_child().first_child().first_child().child_value() << std::endl; } bool try_imbue(std::wistream& stream, const char* name) { try { stream.imbue(std::locale(name)); return true; } catch (const std::exception&) { return false; } } int main() { pugi::xml_document doc; { // tag::code[] std::ifstream stream("weekly-utf-8.xml"); pugi::xml_parse_result result = doc.load(stream); // end::code[] // first character of root name: U+9031, year: 1997 print_doc("UTF8 file from narrow stream", doc, result); } { std::ifstream stream("weekly-utf-16.xml"); pugi::xml_parse_result result = doc.load(stream); // first character of root name: U+9031, year: 1997 print_doc("UTF16 file from narrow stream", doc, result); } { // Since wide streams are treated as UTF-16/32 ones, you can't load the UTF-8 file from a wide stream // directly if you have localized characters; you'll have to provide a UTF8 locale (there is no // standard one; you can use utf8_codecvt_facet from Boost or codecvt_utf8 from C++0x) std::wifstream stream("weekly-utf-8.xml"); if (try_imbue(stream, "en_US.UTF-8")) // try Linux encoding { pugi::xml_parse_result result = doc.load(stream); // first character of root name: U+00E9, year: 1997 print_doc("UTF8 file from wide stream", doc, result); } else { std::cout << "UTF-8 locale is not available\n"; } } { // Since wide streams are treated as UTF-16/32 ones, you can't load the UTF-16 file from a wide stream without // using custom codecvt; you can use codecvt_utf16 from C++0x } { // Since encoding names are non-standard, you can't load the Shift-JIS (or any other non-ASCII) file // from a wide stream portably std::wifstream stream("weekly-shift_jis.xml"); if (try_imbue(stream, ".932") || // try Microsoft encoding try_imbue(stream, "ja_JP.SJIS")) // try Linux encoding; run "localedef -i ja_JP -c -f SHIFT_JIS /usr/lib/locale/ja_JP.SJIS" to get it { pugi::xml_parse_result result = doc.load(stream); // first character of root name: U+9031, year: 1997 print_doc("Shift-JIS file from wide stream", doc, result); } else { std::cout << "Shift-JIS locale is not available\n"; } } } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine
docs/samples/modify_add.cpp
C++
#include "pugixml.hpp" #include <iostream> int main() { pugi::xml_document doc; // tag::code[] // add node with some name pugi::xml_node node = doc.append_child("node"); // add description node with text child pugi::xml_node descr = node.append_child("description"); descr.append_child(pugi::node_pcdata).set_value("Simple node"); // add param node before the description pugi::xml_node param = node.insert_child_before("param", descr); // add attributes to param node param.append_attribute("name") = "version"; param.append_attribute("value") = 1.1; param.insert_attribute_after("type", param.attribute("name")) = "float"; // end::code[] doc.print(std::cout); } // vim:et
zeux/pugixml
4,499
Light-weight, simple and fast XML parser for C++ with XPath support
C++
zeux
Arseny Kapoulkine