mirror of https://github.com/mode777/rayjs.git
1 line
36 KiB
JavaScript
1 line
36 KiB
JavaScript
(()=>{"use strict";var t={208:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGenerator=e.GenericCodeGenerator=e.CodeWriter=e.StringWriter=void 0;class n{constructor(){this.buffer=""}write(t){this.buffer+=t}writeLine(t=""){this.buffer+=t+"\n"}toString(){return this.buffer}}var s;e.StringWriter=n,e.CodeWriter=class extends n{constructor(){super(...arguments),this.indent=0,this.needsIndent=!0}writeGenerator(t){const e=t.iterateTokens(),n=t.iterateText(),r=t.iterateChildren();let i=e.next();for(;!i.done;){switch(i.value){case s.STRING:const t=n.next().value;this.needsIndent&&(this.write(" ".repeat(this.indent)),this.needsIndent=!1),this.write(t);break;case s.GOSUB:const e=r.next().value;this.writeGenerator(e);break;case s.INDENT:this.indent++;break;case s.UNINDENT:this.indent=this.indent>0?this.indent-1:0;break;case s.NEWLINE:this.write("\n"),this.needsIndent=!0}i=e.next()}}},function(t){t[t.STRING=0]="STRING",t[t.NEWLINE=1]="NEWLINE",t[t.INDENT=2]="INDENT",t[t.UNINDENT=3]="UNINDENT",t[t.GOSUB=4]="GOSUB"}(s||(s={}));class r{constructor(){this.children=[],this.text=[],this.tokens=[],this.tags={}}getTag(t){return this.tags[t]}setTag(t,e){this.tags[t]=e}iterateTokens(){return this.tokens[Symbol.iterator]()}iterateText(){return this.text[Symbol.iterator]()}iterateChildren(){return this.children[Symbol.iterator]()}line(t){this.tokens.push(s.STRING,s.NEWLINE),this.text.push(t)}comment(t){this.line("// "+t)}call(t,e,n=null){n&&this.inline(`${n.type} ${n.name} = `),this.inline(t+"("),this.inline(e.join(", ")),this.statement(")")}declare(t,e,n=!1,s=null){n&&this.inline("static "),this.inline(e+" "+t),s&&this.inline(" = "+s),this.statement("")}child(t){return t||(t=this.createGenerator()),this.tokens.push(s.GOSUB),this.children.push(t),t}inline(t){this.tokens.push(s.STRING),this.text.push(t)}statement(t){this.line(t+";")}breakLine(){this.tokens.push(s.NEWLINE)}indent(){this.tokens.push(s.INDENT)}unindent(){this.tokens.push(s.UNINDENT)}function(t,e,n,s,r){const i=this.createGenerator();return i.setTag("_type","function-body"),i.setTag("_name",t),i.setTag("_isStatic",s),i.setTag("_returnType",e),s&&this.inline("static "),this.inline(e+" "+t+"("),this.inline(n.map((t=>t.type+" "+t.name)).join(", ")),this.inline(") {"),this.breakLine(),this.indent(),this.child(i),this.unindent(),this.line("}"),this.breakLine(),r&&r(i),i}if(t,e){this.line("if("+t+") {"),this.indent();const n=this.createGenerator();return n.setTag("_type","if-body"),n.setTag("_condition",t),this.child(n),this.unindent(),this.line("}"),e&&e(n),n}else(t){this.line("else {"),this.indent();const e=this.createGenerator();return e.setTag("_type","else-body"),this.child(e),this.unindent(),this.line("}"),t&&t(e),e}returnExp(t){this.statement("return "+t)}include(t){this.line("#include <"+t+">")}for(t,e){this.line(`for(int ${t}; i < ${e}; i++){`),this.indent();const n=this.child();return this.unindent(),this.line("}"),n}header(t,e){this.line("#ifndef "+t),this.line("#define "+t),this.breakLine();const n=this.child();return n.setTag("_type","header-body"),n.setTag("_guardName",t),this.line("#endif // "+t),e&&e(n),n}declareStruct(t,e,n,s=!1){s&&this.inline("static "),this.statement(`${t} ${e} = { ${n.join(", ")} }`)}switch(t){this.line(`switch(${t}) {`),this.indent();const e=this.child();return this.unindent(),this.line("}"),e}case(t){this.line(`case ${t}:`)}defaultBreak(){this.line("default:"),this.line("{"),this.indent();const t=this.child();return this.statement("break"),this.unindent(),this.line("}"),t}caseBreak(t){this.case(t),this.line("{"),this.indent();const e=this.child();return this.statement("break"),this.unindent(),this.line("}"),e}}e.GenericCodeGenerator=r;class i extends r{createGenerator(){return new i}}e.CodeGenerator=i},763:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HeaderParser=void 0,e.HeaderParser=class{parseEnums(t){return[...t.matchAll(/((?:\/\/.+\n)*)typedef enum {\n([^}]+)} ([^;]+)/gm)].map((t=>({description:this.parseComments(t[1]),values:this.parseEnumValues(t[2]),name:t[3]})))}parseEnumValues(t){let e=0;return t.split("\n").map((t=>t.trim().match(/([^ ,]+)(?: = ([0-9]+))?,?(?: *)(?:\/\/ (.+))?/))).filter((t=>null!==t&&!t[0].startsWith("/"))).map((t=>{let n=e=t[2]?parseInt(t[2]):e;return e++,{name:t[1],description:t[3]||"",value:n}}))}parseComments(t){return t.split("\n").map((t=>t.replace("// ",""))).join("\n").trim()}parseFunctionDefinitions(t){return[...t.matchAll(/^[A-Z]+ (.+?)(\w+)\(([^\)]+)\);(?: +\/\/ (.+))?$/gm)].map((t=>({returnType:t[1].trim(),name:t[2],params:this.parseFunctionArgs(t[3]),description:t[4]||""})))}parseFunctions(t,e=!1){return(e?[...t.matchAll(/((?:\/\/.+\n)+)^(.+?)(\w+)\(([^\)]+)\)/gm)]:[...t.matchAll(/((?:\/\/.+\n)+)^[A-Z]+ (.+?)(\w+)\(([^\)]+)\)/gm)]).map((t=>({returnType:t[2].trim(),name:t[3],params:this.parseFunctionArgs(t[4]),description:t[1]?this.parseComments(t[1]):""})))}parseFunctionArgs(t){return t.split(",").filter((t=>"void"!==t)).map((t=>{const e=(t=t.trim().replace(" *","* ")).split(" ");return{name:e.pop()||"",type:e.join(" ").replace("*"," *").trim()}}))}parseStructs(t){return[...t.matchAll(/((?:\/\/.+\n)+)typedef struct {([^}]+)} ([^;]+);/gm)].map((t=>({name:t[3],fields:this.parseStructFields(t[2]),description:this.parseComments(t[1])})))}parseStructFields(t){return t.trim().split("\n").map((t=>t.trim())).filter((t=>!t.startsWith("/")&&t.endsWith(";"))).map((t=>{const e=t.match(/([^ ]+(?: \*)?) ([^;]+);/);return{name:e[2],type:e[1],description:""}}))}}},986:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.QuickJsGenerator=e.GenericQuickJsGenerator=e.QuickJsHeader=void 0;const s=n(147),r=n(208);e.QuickJsHeader=class{constructor(t){this.name=t,this.structLookup={};const e=this.root=new a,n=this.body=e.header("JS_"+this.name+"_GUARD"),s=this.includes=n.child();s.include("stdio.h"),s.include("stdlib.h"),s.include("string.h"),s.breakLine(),s.include("quickjs.h"),n.breakLine(),n.line("#ifndef countof"),n.line("#define countof(x) (sizeof(x) / sizeof((x)[0]))"),n.line("#endif"),n.breakLine(),this.definitions=n.child(),n.breakLine(),this.structs=n.child(),this.functions=n.child(),this.moduleFunctionList=n.jsFunctionList("js_"+t+"_funcs");const r=n.function("js_"+this.name+"_init","int",[{type:"JSContext *",name:"ctx"},{type:"JSModuleDef *",name:"m"}],!0);(this.moduleInit=r.child()).statement(`JS_SetModuleExportList(ctx, m,${this.moduleFunctionList.getTag("_name")},countof(${this.moduleFunctionList.getTag("_name")}))`),r.returnExp("0");const i=n.function("js_init_module_"+this.name,"JSModuleDef *",[{type:"JSContext *",name:"ctx"},{type:"const char *",name:"module_name"}],!1),o=this.moduleEntry=i.child();o.statement("JSModuleDef *m"),o.statement(`m = JS_NewCModule(ctx, module_name, ${r.getTag("_name")})`),o.statement("if(!m) return NULL"),o.statement(`JS_AddModuleExportList(ctx, m, ${this.moduleFunctionList.getTag("_name")}, countof(${this.moduleFunctionList.getTag("_name")}))`),i.statement("return m")}registerStruct(t,e){this.structLookup[t]=e}writeTo(t){const e=new r.CodeWriter;e.writeGenerator(this.root),(0,s.writeFileSync)(t,e.toString())}};class i extends r.GenericCodeGenerator{jsBindingFunction(t){return this.function("js_"+t,"JSValue",[{type:"JSContext *",name:"ctx"},{type:"JSValueConst",name:"this_val"},{type:"int",name:"argc"},{type:"JSValueConst *",name:"argv"}],!0)}jsToC(t,e,n,s={},r=!1,i){switch(i??t){case"const void *":case"void *":case"float *":case"const float *":case"unsigned short *":case"unsigned char *":case"const unsigned char *":this.declare(e+"_size","size_t"),this.declare(e+"_js","void *",!1,`(void *)JS_GetArrayBuffer(ctx, &${e}_size, ${n})`),this.if(e+"_js == NULL").returnExp("JS_EXCEPTION"),this.declare(e,t,!1,"malloc("+e+"_size)"),this.call("memcpy",["(void *)"+e,"(const void *)"+e+"_js",e+"_size"]);break;case"const char *":case"char *":r?this.statement(`${e} = (JS_IsNull(${n}) || JS_IsUndefined(${n})) ? NULL : (${t})JS_ToCString(ctx, ${n})`):this.statement(`${t} ${e} = (JS_IsNull(${n}) || JS_IsUndefined(${n})) ? NULL : (${t})JS_ToCString(ctx, ${n})`);break;case"double":r||this.statement(`${t} ${e}`),this.statement(`JS_ToFloat64(ctx, &${e}, ${n})`);break;case"float":this.statement("double _double_"+e),this.statement(`JS_ToFloat64(ctx, &_double_${e}, ${n})`),r?this.statement(`${e} = (${t})_double_${e}`):this.statement(`${t} ${e} = (${t})_double_${e}`);break;case"char":r?this.statement(`${e} = (JS_IsNull(${n}) || JS_IsUndefined(${n})) ? 0 : JS_ToCString(ctx, ${n})[0]`):this.declare(e,t,!1,`(JS_IsNull(${n}) || JS_IsUndefined(${n})) ? 0 : JS_ToCString(ctx, ${n})[0]`);break;case"short":r||this.statement(`${t} ${e}`),this.statement(`{ int _tmp; JS_ToInt32(ctx, &_tmp, ${n}); ${e} = (short)_tmp; }`);break;case"int":r||this.statement(`${t} ${e}`),this.statement(`JS_ToInt32(ctx, &${e}, ${n})`);break;case"int *":r||this.statement(`int ${e}_int`),this.statement(`JS_ToInt32(ctx, &${e}_int, ${n})`),this.statement(`${t} ${e} = &${e}_int`);break;case"long":r||this.statement(`${t} ${e}`),this.statement(`JS_ToInt64(ctx, &${e}, ${n})`);break;case"unsigned int":r||this.statement(`${t} ${e}`),this.statement(`JS_ToUint32(ctx, &${e}, ${n})`);break;case"unsigned short":r||this.statement(`${t} ${e}`),this.statement(`{ unsigned int _tmp; JS_ToUint32(ctx, &_tmp, ${n}); ${e} = (unsigned short)_tmp; }`);break;case"unsigned long":r||this.statement(`${t} ${e}`),this.statement(`{ unsigned long long _tmp; JS_ToInt64(ctx, (int64_t *)&_tmp, ${n}); ${e} = (unsigned long)_tmp; }`);break;case"unsigned char":this.statement("unsigned int _int_"+e),this.statement(`JS_ToUint32(ctx, &_int_${e}, ${n})`),r?this.statement(`${e} = (${t})_int_${e}`):this.statement(`${t} ${e} = (${t})_int_${e}`);break;case"bool":r?this.statement(`${e} = JS_ToBool(ctx, ${n})`):this.statement(`${t} ${e} = JS_ToBool(ctx, ${n})`);break;case"bool *":r||this.statement(`bool ${e}_val`),this.statement(`${e}_val = JS_ToBool(ctx, ${n})`),this.statement(`${t} ${e} = &${e}_val`);break;default:t.startsWith("const");const i=t.endsWith(" *"),a=s[t.replace("const ","").replace(" *","")];if(!a)throw new Error("Cannot convert into parameter type: "+t);const o=i?"":"_ptr";this.jsOpqToStructPtr(t.replace(" *",""),e+o,n,a),this.statement(`if(${e+o} == NULL) return JS_EXCEPTION`),i||this.declare(e,t,!1,`*${e}_ptr`)}}jsToJs(t,e,n,s={}){switch(t){case"int":case"int *":case"long":this.declare(e,"JSValue",!1,`JS_NewInt32(ctx, ${n})`);break;case"long":this.declare(e,"JSValue",!1,`JS_NewInt64(ctx, ${n})`);break;case"unsigned int":case"unsigned char":this.declare(e,"JSValue",!1,`JS_NewUint32(ctx, ${n})`);break;case"unsigned int *":case"unsigned char *":this.declare(e,"JSValue",!1,`${n} ? JS_NewUint32(ctx, *${n}) : JS_NULL`);break;case"bool":this.declare(e,"JSValue",!1,`JS_NewBool(ctx, ${n})`);break;case"float":case"double":this.declare(e,"JSValue",!1,`JS_NewFloat64(ctx, ${n})`);break;case"const char *":case"char *":this.declare(e,"JSValue",!1,`JS_NewString(ctx, ${n})`);break;default:const r=s[t];if(!r)throw new Error("Cannot convert parameter type to Javascript: "+t);this.jsStructToOpq(t,e,n,r)}}jsStructToOpq(t,e,n,s){this.declare(e+"_ptr",t+"*",!1,`(${t}*)js_malloc(ctx, sizeof(${t}))`),this.statement("*"+e+"_ptr = "+n),this.declare(e,"JSValue",!1,`JS_NewObjectClass(ctx, ${s})`),this.call("JS_SetOpaque",[e,e+"_ptr"])}jsCleanUpParameter(t,e){switch(t){case"char *":case"const char *":this.statement(`JS_FreeCString(ctx, ${e})`);break;case"const void *":case"void *":case"float *":case"unsigned short *":case"unsigned char *":case"const unsigned char *":this.statement(`free((void *)${e})`)}}jsFunctionList(t){this.line("static const JSCFunctionListEntry "+t+"[] = {"),this.indent();const e=this.createGenerator();return e.setTag("_type","js-function-list"),e.setTag("_name",t),this.child(e),this.unindent(),this.statement("}"),this.breakLine(),e}jsFuncDef(t,e,n){this.line(`JS_CFUNC_DEF("${t}",${e},${n}),`)}jsClassId(t){return this.declare(t,"JSClassID",!0),t}jsPropStringDef(t,e){this.line(`JS_PROP_STRING_DEF("${t}","${e}", JS_PROP_CONFIGURABLE),`)}jsGetSetDef(t,e,n){this.line(`JS_CGETSET_DEF("${t}",${e||"NULL"},${n||"NULL"}),`)}jsStructFinalizer(t,e,n){const s=this.function(`js_${e}_finalizer`,"void",[{type:"JSRuntime *",name:"rt"},{type:"JSValue",name:"val"}],!0);return s.statement(`${e}* ptr = JS_GetOpaque(val, ${t})`),s.if("ptr",(t=>{n&&n(t,"ptr"),t.call("js_free_rt",["rt","ptr"])})),s}jsClassDeclaration(t,e,n,s){const r=this.function("js_declare_"+t,"int",[{type:"JSContext *",name:"ctx"},{type:"JSModuleDef *",name:"m"}],!0);r.call("JS_NewClassID",["&"+e]);const i=`js_${t}_def`;return r.declare(i,"JSClassDef",!1,`{ .class_name = "${t}", .finalizer = ${n} }`),r.call("JS_NewClass",["JS_GetRuntime(ctx)",e,"&"+i]),r.declare("proto","JSValue",!1,"JS_NewObject(ctx)"),r.call("JS_SetPropertyFunctionList",["ctx","proto",s,`countof(${s})`]),r.call("JS_SetClassProto",["ctx",e,"proto"]),r.statement("return 0"),r}jsStructGetter(t,e,n,s,r,i){const a=this.function(`js_${t}_get_${n}`,"JSValue",[{type:"JSContext*",name:"ctx"},{type:"JSValueConst",name:"this_val"}],!0);return a.declare("ptr",t+"*",!1,`JS_GetOpaque2(ctx, this_val, ${e})`),i?i(a):a.declare(n,s,!1,"ptr->"+n),a.jsToJs(s,"ret",n,r),a.returnExp("ret"),a}jsStructSetter(t,e,n,s,r,i){const a=this.function(`js_${t}_set_${n}`,"JSValue",[{type:"JSContext*",name:"ctx"},{type:"JSValueConst",name:"this_val"},{type:"JSValueConst",name:"v"}],!0);return a.declare("ptr",t+"*",!1,`JS_GetOpaque2(ctx, this_val, ${e})`),a.jsToC(s,"value","v",r),i?i(a):a.statement("ptr->"+n+" = value"),a.returnExp("JS_UNDEFINED"),a}jsOpqToStructPtr(t,e,n,s){this.declare(e,t+"*",!1,`(${t}*)JS_GetOpaque2(ctx, ${n}, ${s})`)}jsStructConstructor(t,e,n,s){const r=this.jsBindingFunction(t+"_constructor");for(let t=0;t<e.length;t++){const n=e[t];r.jsToC(n.type,n.name,"argv["+t+"]",s)}return r.declareStruct(t,"_struct",e.map((t=>t.name))),r.jsStructToOpq(t,"_return","_struct",n),r.returnExp("_return"),r}}e.GenericQuickJsGenerator=i;class a extends i{createGenerator(){return new a}}e.QuickJsGenerator=a},392:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.RayLibHeader=void 0;const s=n(986),r=n(102);class i extends s.QuickJsHeader{constructor(t){super(t),this.typings=new r.TypeScriptDeclaration,this.includes.include("raylib.h")}addApiFunction(t){const e=t.binding||{};if(e.ignore)return;const n=e.jsName||t.name.charAt(0).toLowerCase()+t.name.slice(1);console.log("Binding function "+t.name);const s=this.functions.jsBindingFunction(n);if(e.body)e.body(s);else{e.before&&e.before(s),t.params=t.params||[];const n=t.params.filter((t=>!t.binding?.ignore));for(let t=0;t<n.length;t++){const e=n[t];e.binding?.customConverter?e.binding.customConverter(s,"argv["+t+"]"):s.jsToC(e.type,e.name,"argv["+t+"]",this.structLookup,!1,e.binding?.typeAlias)}e.customizeCall?s.line(e.customizeCall):s.call(t.name,t.params.map((t=>t.name)),"void"===t.returnType?null:{type:t.returnType,name:"returnVal"});for(let t=0;t<n.length;t++){const e=n[t];e.binding?.customCleanup?e.binding.customCleanup(s,"argv["+t+"]"):s.jsCleanUpParameter(e.type,e.name)}"void"===t.returnType?(e.after&&e.after(s),s.statement("return JS_UNDEFINED")):(s.jsToJs(t.returnType,"ret","returnVal",this.structLookup),e.after&&e.after(s),s.returnExp("ret"))}this.moduleFunctionList.jsFuncDef(n,(t.params||[]).filter((t=>!t.binding?.ignore)).length,s.getTag("_name")),this.typings.addFunction(n,t)}addEnum(t){console.log("Binding enum "+t.name),t.values.forEach((t=>this.exportGlobalInt(t.name,t.description)))}addApiStruct(t){const e=t.binding||{};console.log("Binding struct "+t.name);const n=this.definitions.jsClassId(`js_${t.name}_class_id`);this.registerStruct(t.name,n),e.aliases?.forEach((t=>this.registerStruct(t,n)));const s=this.structs.jsStructFinalizer(n,t.name,((t,n)=>e.destructor&&t.call(e.destructor.name,["*"+n]))),r=this.structs.createGenerator();if(e&&e.properties)for(const s of Object.keys(e.properties)){const i=t.fields.find((t=>t.name===s))?.type;if(!i)throw new Error(`Struct ${t.name} does not contain field ${s}`);const a=e.properties[s];let o,c;a.get&&(o=this.structs.jsStructGetter(t.name,n,s,i,this.structLookup,a.overrideRead)),a.set&&(c=this.structs.jsStructSetter(t.name,n,s,i,this.structLookup,a.overrideWrite)),r.jsGetSetDef(s,o?.getTag("_name"),c?.getTag("_name"))}const i=this.structs.jsFunctionList(`js_${t.name}_proto_funcs`);i.child(r),i.jsPropStringDef("[Symbol.toStringTag]",t.name);const a=this.structs.jsClassDeclaration(t.name,n,s.getTag("_name"),i.getTag("_name"));if(this.moduleInit.call(a.getTag("_name"),["ctx","m"]),e?.createConstructor||e?.createEmptyConstructor){const s=this.functions.jsStructConstructor(t.name,e?.createEmptyConstructor?[]:t.fields,n,this.structLookup);this.moduleInit.statement(`JSValue ${t.name}_constr = JS_NewCFunction2(ctx, ${s.getTag("_name")},"${t.name})", ${t.fields.length}, JS_CFUNC_constructor_or_func, 0)`),this.moduleInit.call("JS_SetModuleExport",["ctx","m",`"${t.name}"`,t.name+"_constr"]),this.moduleEntry.call("JS_AddModuleExport",["ctx","m",'"'+t.name+'"'])}this.typings.addStruct(t)}exportGlobalStruct(t,e,n,s){this.moduleInit.declareStruct(t,e+"_struct",n);const r=this.structLookup[t];if(!r)throw new Error("Struct "+t+" not found in register");this.moduleInit.jsStructToOpq(t,e+"_js",e+"_struct",r),this.moduleInit.call("JS_SetModuleExport",["ctx","m",`"${e}"`,e+"_js"]),this.moduleEntry.call("JS_AddModuleExport",["ctx","m",`"${e}"`]),this.typings.constants.tsDeclareConstant(e,t,s)}exportGlobalInt(t,e){this.moduleInit.statement(`JS_SetModuleExport(ctx, m, "${t}", JS_NewInt32(ctx, ${t}))`),this.moduleEntry.statement(`JS_AddModuleExport(ctx, m, "${t}")`),this.typings.constants.tsDeclareConstant(t,"number",e)}exportGlobalDouble(t,e){this.moduleInit.statement(`JS_SetModuleExport(ctx, m, "${t}", JS_NewFloat64(ctx, ${t}))`),this.moduleEntry.statement(`JS_AddModuleExport(ctx, m, "${t}")`),this.typings.constants.tsDeclareConstant(t,"number",e)}}e.RayLibHeader=i},102:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TypescriptGenerator=e.GenericTypescriptGenerator=e.TypeScriptDeclaration=void 0;const s=n(208),r=n(147);e.TypeScriptDeclaration=class{constructor(){this.root=new a,this.structs=this.root.child(),this.functions=this.root.child(),this.constants=this.root.child()}addFunction(t,e){const n=e.binding||{},s=(e.params||[]).filter((t=>!t.binding?.ignore)).map((t=>({name:t.name,type:t.binding?.jsType??this.toJsType(t.type)}))),r=n.jsReturns??this.toJsType(e.returnType);this.functions.tsDeclareFunction(t,s,r,e.description)}addStruct(t){const e=t.binding||{};var n=t.fields.filter((t=>!!(e.properties||{})[t.name])).map((t=>({name:t.name,description:t.description,type:this.toJsType(t.type)})));this.structs.tsDeclareInterface(t.name,n),this.structs.tsDeclareType(t.name,!(!e.createConstructor&&!e.createEmptyConstructor),e.createEmptyConstructor?[]:n)}toJsType(t){switch(t){case"int":case"long":case"unsigned int":case"unsigned char":case"float":case"double":return"number";case"const unsigned char *":case"unsigned char *":case"unsigned short *":case"float *":return"ArrayBuffer";case"bool":return"boolean";case"const char *":case"char *":return"string | undefined | null";case"void *":case"const void *":return"any";case"Camera":case"Camera *":return"Camera3D";case"Texture2D":case"Texture2D *":case"TextureCubemap":return"Texture";case"RenderTexture2D":case"RenderTexture2D *":return"RenderTexture";case"Quaternion":return"Vector4";default:return t.replace(" *","").replace("const ","")}}writeTo(t){const e=new s.CodeWriter;e.writeGenerator(this.root),(0,r.writeFileSync)(t,e.toString())}};class i extends s.GenericCodeGenerator{tsDeclareFunction(t,e,n,s){this.tsDocComment(s),this.statement(`declare function ${t}(${e.map((t=>t.name+": "+t.type)).join(", ")}): ${n}`)}tsDeclareConstant(t,e,n){this.tsDocComment(n),this.statement(`declare var ${t}: ${e}`)}tsDeclareType(t,e,n){this.line(`declare var ${t}: {`),this.indent(),this.statement("prototype: "+t),e&&this.statement(`new(${n.map((t=>t.name+": "+t.type)).join(", ")}): ${t}`),this.unindent(),this.line("}")}tsDeclareInterface(t,e){this.line(`interface ${t} {`),this.indent();for(const t of e)t.description&&this.tsDocComment(t.description),this.line(t.name+": "+t.type+",");this.unindent(),this.line("}")}tsDocComment(t){this.line(`/** ${t} */`)}}e.GenericTypescriptGenerator=i;class a extends i{createGenerator(){return new a}}e.TypescriptGenerator=a},147:t=>{t.exports=require("fs")}},e={};function n(s){var r=e[s];if(void 0!==r)return r.exports;var i=e[s]={exports:{}};return t[s](i,i.exports,n),i.exports}(()=>{const t=n(147),e=n(392),s=n(763);let r;function i(t,e){return t.find((t=>t.name===e))}function a(t,e){return t.find((t=>t.name===e))}function o(t,e){return t.filter((t=>t.type===e)).map((t=>t.name))}function c(t){i(r.functions,t).binding={ignore:!0}}!function(){r=JSON.parse((0,t.readFileSync)("thirdparty/raylib/parser/output/raylib_api.json","utf8"));const n=new s.HeaderParser,l=(0,t.readFileSync)("thirdparty/raylib/src/raymath.h","utf8");n.parseFunctions(l).forEach((t=>r.functions.push(t)));const u=(0,t.readFileSync)("thirdparty/raylib/src/rcamera.h","utf8");n.parseFunctionDefinitions(u).forEach((t=>r.functions.push(t)));const d=(0,t.readFileSync)("thirdparty/raygui/src/raygui.h","utf8"),p=n.parseFunctionDefinitions(d),m=n.parseEnums(d);p.forEach((t=>r.functions.push(t))),m.forEach((t=>r.enums.push(t)));const h=(0,t.readFileSync)("include/rlights.h","utf8"),g=n.parseFunctions(h,!0);r.functions.push(g[0]),r.functions.push(g[1]),n.parseEnums(h).forEach((t=>r.enums.push(t)));const S=n.parseStructs(h);S[0].binding={properties:{type:{get:!0,set:!0},enabled:{get:!0,set:!0},position:{get:!0,set:!0},target:{get:!0,set:!0},color:{get:!0,set:!0},attenuation:{get:!0,set:!0}}},r.structs.push(S[0]);const f=(0,t.readFileSync)("include/reasings.h","utf8");n.parseFunctions(f).forEach((t=>r.functions.push(t)));const _=(0,t.readFileSync)("src/rlightmapper.h","utf8"),b=n.parseFunctionDefinitions(_),y=n.parseStructs(_);b.forEach((t=>r.functions.push(t))),y.forEach((t=>r.structs.push(t))),y[0].binding={properties:{w:{get:!0},h:{get:!0},progress:{get:!0}}},y[1].binding={properties:{hemisphereSize:{get:!0,set:!0},zNear:{get:!0,set:!0},zFar:{get:!0,set:!0},backgroundColor:{get:!0,set:!0},interpolationPasses:{get:!0,set:!0},interpolationThreshold:{get:!0,set:!0},cameraToSurfaceDistanceModifier:{get:!0,set:!0}}};const x=(0,t.readFileSync)("src/rextensions.h","utf8"),C=n.parseFunctionDefinitions(x);console.log(C),C.forEach((t=>r.functions.push(t)));const T=new e.RayLibHeader("raylib_core");T.includes.include("raymath.h"),T.includes.include("rcamera.h"),T.includes.line("#define RAYGUI_IMPLEMENTATION"),T.includes.include("raygui.h"),T.includes.line("#define RLIGHTS_IMPLEMENTATION"),T.includes.include("rlights.h"),T.includes.include("reasings.h"),T.includes.line("#define RLIGHTMAPPER_IMPLEMENTATION"),T.includes.include("rlightmapper.h"),a(r.structs,"Color").binding={properties:{r:{get:!0,set:!0},g:{get:!0,set:!0},b:{get:!0,set:!0},a:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Rectangle").binding={properties:{x:{get:!0,set:!0},y:{get:!0,set:!0},width:{get:!0,set:!0},height:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Vector2").binding={properties:{x:{get:!0,set:!0},y:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Vector3").binding={properties:{x:{get:!0,set:!0},y:{get:!0,set:!0},z:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Vector4").binding={properties:{x:{get:!0,set:!0},y:{get:!0,set:!0},z:{get:!0,set:!0},w:{get:!0,set:!0}},createConstructor:!0,aliases:o(r.aliases,"Vector4")},a(r.structs,"Ray").binding={properties:{position:{get:!1,set:!0},direction:{get:!1,set:!0}},createConstructor:!0},a(r.structs,"RayCollision").binding={properties:{hit:{get:!0,set:!1},distance:{get:!0,set:!1},point:{get:!0,set:!1},normal:{get:!0,set:!1}},createConstructor:!1},a(r.structs,"Camera2D").binding={properties:{offset:{get:!0,set:!0},target:{get:!0,set:!0},rotation:{get:!0,set:!0},zoom:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Camera3D").binding={properties:{position:{get:!0,set:!0},target:{get:!0,set:!0},up:{get:!1,set:!0},fovy:{get:!0,set:!0},projection:{get:!0,set:!0}},createConstructor:!0,aliases:o(r.aliases,"Camera3D")},a(r.structs,"BoundingBox").binding={properties:{min:{get:!0,set:!0},max:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Matrix").binding={properties:{},createConstructor:!1},a(r.structs,"NPatchInfo").binding={properties:{source:{get:!0,set:!0},left:{get:!0,set:!0},top:{get:!0,set:!0},right:{get:!0,set:!0},bottom:{get:!0,set:!0},layout:{get:!0,set:!0}},createConstructor:!0},a(r.structs,"Image").binding={properties:{data:{set:!0},width:{get:!0,set:!0},height:{get:!0,set:!0},mipmaps:{get:!0,set:!0},format:{get:!0,set:!0}},createEmptyConstructor:!0},a(r.structs,"Wave").binding={properties:{frameCount:{get:!0},sampleRate:{get:!0},sampleSize:{get:!0},channels:{get:!0}}},a(r.structs,"Sound").binding={properties:{frameCount:{get:!0}}},a(r.structs,"Music").binding={properties:{frameCount:{get:!0},looping:{get:!0,set:!0},ctxType:{get:!0}}},a(r.structs,"Model").binding={properties:{transform:{get:!0,set:!0},meshCount:{get:!0},materialCount:{get:!0},boneCount:{get:!0}}},a(r.structs,"Mesh").binding={properties:{vertexCount:{get:!0,set:!0},triangleCount:{get:!0,set:!0},vertices:{set:!0},texcoords:{set:!0},texcoords2:{set:!0},normals:{set:!0},tangents:{set:!0},colors:{set:!0},indices:{set:!0},animVertices:{set:!0},animNormals:{set:!0},boneIds:{set:!0},boneWeights:{set:!0}},createEmptyConstructor:!0},a(r.structs,"Shader").binding={properties:{id:{get:!0}}},a(r.structs,"Texture").binding={properties:{width:{get:!0},height:{get:!0},mipmaps:{get:!0},format:{get:!0}},aliases:o(r.aliases,"Texture")},a(r.structs,"Font").binding={properties:{baseSize:{get:!0},glyphCount:{get:!0},glyphPadding:{get:!0}}},a(r.structs,"RenderTexture").binding={properties:{id:{get:!0},texture:{get:!0},depth:{get:!0}},aliases:o(r.aliases,"RenderTexture")},a(r.structs,"MaterialMap").binding={properties:{texture:{set:!0},color:{set:!0,get:!0},value:{get:!0,set:!0}}},a(r.structs,"Material").binding={properties:{shader:{get:!0,set:!0}}};const $=a(r.structs,"VrDeviceInfo");$.fields.filter((t=>"lensDistortionValues"===t.name))[0].type="Vector4",$.binding={createEmptyConstructor:!0,properties:{hResolution:{set:!0,get:!0},vResolution:{set:!0,get:!0},hScreenSize:{set:!0,get:!0},vScreenSize:{set:!0,get:!0},eyeToScreenDistance:{set:!0,get:!0},lensSeparationDistance:{set:!0,get:!0},interpupillaryDistance:{set:!0,get:!0}}},i(r.functions,"EndDrawing").binding={after:t=>t.call("app_update_quickjs",[])},c("SetWindowIcons"),c("GetWindowHandle"),c("SwapScreenBuffer"),c("PollInputEvents"),c("WaitTime"),i(r.functions,"SetShaderValue").binding={body:t=>{t.jsToC("Shader","shader","argv[0]",T.structLookup),t.jsToC("int","locIndex","argv[1]",T.structLookup),t.declare("value","void *",!1,"NULL"),t.declare("valueFloat","float"),t.declare("valueInt","int"),t.jsToC("int","uniformType","argv[3]",T.structLookup);const e=t.switch("uniformType");let n=e.caseBreak("SHADER_UNIFORM_FLOAT");n.jsToC("float","valueFloat","argv[2]",T.structLookup,!0),n.statement("value = (void *)&valueFloat"),n=e.caseBreak("SHADER_UNIFORM_VEC2"),n.jsToC("Vector2 *","valueV2","argv[2]",T.structLookup),n.statement("value = (void*)valueV2"),n=e.caseBreak("SHADER_UNIFORM_VEC3"),n.jsToC("Vector3 *","valueV3","argv[2]",T.structLookup),n.statement("value = (void*)valueV3"),n=e.caseBreak("SHADER_UNIFORM_VEC4"),n.jsToC("Vector4 *","valueV4","argv[2]",T.structLookup),n.statement("value = (void*)valueV4"),n=e.caseBreak("SHADER_UNIFORM_INT"),n.jsToC("int","valueInt","argv[2]",T.structLookup,!0),n.statement("value = (void*)&valueInt"),n=e.defaultBreak(),n.returnExp("JS_EXCEPTION"),t.call("SetShaderValue",["shader","locIndex","value","uniformType"]),t.returnExp("JS_UNDEFINED")}},c("SetShaderValueV");const v=i(r.functions,"TraceLog");v.params?.pop();const J=new Set(["void","int","float","double","bool","unsigned int","unsigned char","long","char *","const char *","void *","const void *","unsigned char *","const unsigned char *","unsigned short *","float *","int *","unsigned int *","Color","Rectangle","Vector2","Vector3","Vector4","Matrix","Image","Texture","Texture2D","TextureCubemap","RenderTexture","RenderTexture2D","NPatchInfo","GlyphInfo","Font","Camera","Camera3D","Camera2D","Mesh","Shader","Material","MaterialMap","Transform","BoneInfo","Model","ModelAnimation","ModelAnimPose","Ray","RayCollision","BoundingBox","Wave","AudioStream","Sound","Music","VrDeviceInfo","VrStereoConfig","FilePathList","AutomationEvent","AutomationEventList","Light","Lightmapper","LightmapperConfig","Quaternion","ModelSkeleton","GestureEvent","TraceLogCallback","LoadFileDataCallback","SaveFileDataCallback","LoadFileTextCallback","SaveFileTextCallback"]);r.functions.forEach((t=>{if(t.binding?.ignore)return;const e=t=>t.replace(/^const /,"").replace(/\*+$/,"").replace(/ \*$/,"").trim(),n=(t.params||[]).every((t=>{const n=t.binding?.typeAlias||t.type;return J.has(n)||J.has(e(n))})),s=e(t.returnType);n&&(J.has(t.returnType)||J.has(s))||(t.name.startsWith("Text")||console.log(`Auto-ignoring ${t.name} (return: ${t.returnType}, params: [${(t.params||[]).map((t=>t.type)).join(", ")}])`),t.binding={ignore:!0})})),r.functions.filter((t=>{if("unsigned char *"!==t.returnType)return!1;const e=t.params?.[t.params.length-1];return e&&("int *"===e.type||"unsigned int *"===e.type)})).forEach((t=>{const e=t.params[t.params.length-1],n="CompressData"===t.name?"compData":"data";t.binding={body:s=>{for(let e=0;e<t.params.length-1;e++){const n=t.params[e];s.jsToC(n.type,n.name,`argv[${e}]`,T.structLookup)}s.declare(e.name,"int",!1,"0"),s.call(t.name,t.params.map((t=>t.name)).slice(0,-1).concat(["&"+e.name]),{type:"unsigned char *",name:n}),s.statement(`JSValue buf = JS_NewArrayBufferCopy(ctx, (const uint8_t*)${n}, ${e.name})`),s.statement(`if (${n}) MemFree(${n})`),s.returnExp("buf")}},console.log(`Special buffer binding for ${t.name}`)})),c("MemAlloc"),c("MemRealloc"),c("MemFree"),c("SetTraceLogCallback"),c("SetLoadFileDataCallback"),c("SetSaveFileDataCallback"),c("SetLoadFileTextCallback"),c("SetSaveFileTextCallback");const E=i(r.functions,"LoadFileData");E.params[E.params.length-1].binding={ignore:!0},E.binding={body:t=>{t.jsToC("const char *","fileName","argv[0]"),t.declare("bytesRead","unsigned int"),t.call("LoadFileData",["fileName","&bytesRead"],{type:"unsigned char *",name:"retVal"}),t.statement("JSValue buffer = JS_NewArrayBufferCopy(ctx, (const uint8_t*)retVal, bytesRead)"),t.call("UnloadFileData",["retVal"]),t.jsCleanUpParameter("const char*","fileName"),t.returnExp("buffer")}},c("UnloadFileData"),i(r.functions,"SaveFileData").binding={},c("ExportDataAsCode"),c("LoadRandomSequence"),i(r.functions,"LoadFileText").binding={after:t=>t.call("UnloadFileText",["returnVal"])},i(r.functions,"SaveFileText").params[1].binding={typeAlias:"const char *"},c("UnloadFileText");const L=(t,e,n,s)=>{t.call(e,s,{type:"FilePathList",name:"files"}),t.call("JS_NewArray",["ctx"],{type:"JSValue",name:"ret"}),t.for("i","files.count").call("JS_SetPropertyUint32",["ctx","ret","i","JS_NewString(ctx,files.paths[i])"]),t.call(n,["files"])};i(r.functions,"LoadDirectoryFiles").binding={jsReturns:"string[]",body:t=>{t.jsToC("const char *","dirPath","argv[0]"),L(t,"LoadDirectoryFiles","UnloadDirectoryFiles",["dirPath"]),t.jsCleanUpParameter("const char *","dirPath"),t.returnExp("ret")}},i(r.functions,"LoadDirectoryFilesEx").binding={jsReturns:"string[]",body:t=>{t.jsToC("const char *","basePath","argv[0]"),t.jsToC("const char *","filter","argv[1]"),t.jsToC("bool","scanSubdirs","argv[2]"),L(t,"LoadDirectoryFilesEx","UnloadDirectoryFiles",["basePath","filter","scanSubdirs"]),t.jsCleanUpParameter("const char *","basePath"),t.jsCleanUpParameter("const char *","filter"),t.returnExp("ret")}},c("UnloadDirectoryFiles"),i(r.functions,"LoadDroppedFiles").binding={jsReturns:"string[]",body:t=>{L(t,"LoadDroppedFiles","UnloadDroppedFiles",[]),t.returnExp("ret")}},c("UnloadDroppedFiles"),c("CompressData"),c("DecompressData"),c("EncodeDataBase64"),c("DecodeDataBase64"),c("DrawLineStrip"),c("DrawTriangleFan"),c("DrawTriangleStrip"),c("CheckCollisionPointPoly"),c("CheckCollisionLines"),c("LoadImageAnim"),c("ExportImageAsCode"),i(r.functions,"LoadImageColors").binding={jsReturns:"ArrayBuffer",body:t=>{t.jsToC("Image","image","argv[0]",T.structLookup),t.call("LoadImageColors",["image"],{name:"colors",type:"Color *"}),t.statement("JSValue retVal = JS_NewArrayBufferCopy(ctx, (const uint8_t*)colors, image.width*image.height*sizeof(Color))"),t.call("UnloadImageColors",["colors"]),t.returnExp("retVal")}},c("LoadImagePalette"),c("UnloadImageColors"),c("UnloadImagePalette"),c("GetPixelColor"),c("SetPixelColor");const D=i(r.functions,"LoadFontEx");D.params[2].binding={ignore:!0},D.params[3].binding={ignore:!0},D.binding={customizeCall:"Font returnVal = LoadFontEx(fileName, fontSize, NULL, 0);"},c("LoadFontFromMemory"),c("LoadFontData"),c("GenImageFontAtlas"),c("UnloadFontData"),c("ExportFontAsCode"),c("DrawTextCodepoints"),c("GetGlyphInfo"),c("LoadUTF8"),c("UnloadUTF8"),c("LoadCodepoints"),c("UnloadCodepoints"),c("GetCodepointCount"),c("GetCodepoint"),c("GetCodepointNext"),c("GetCodepointPrevious"),c("CodepointToUTF8"),r.functions.filter((t=>t.name.startsWith("Text"))).forEach((t=>c(t.name))),c("DrawTriangleStrip3D"),c("LoadMaterials"),c("LoadModelAnimations"),c("UpdateModelAnimation"),c("UnloadModelAnimation"),c("UnloadModelAnimations"),c("IsModelAnimationValid"),c("ExportWaveAsCode"),c("LoadWaveSamples"),c("UnloadWaveSamples"),c("LoadMusicStreamFromMemory"),c("LoadAudioStream"),c("UnloadAudioStream"),c("UpdateAudioStream"),c("IsAudioStreamProcessed"),c("PlayAudioStream"),c("PauseAudioStream"),c("ResumeAudioStream"),c("IsAudioStreamPlaying"),c("StopAudioStream"),c("SetAudioStreamVolume"),c("SetAudioStreamPitch"),c("SetAudioStreamPan"),c("SetAudioStreamBufferSizeDefault"),c("SetAudioStreamCallback"),c("AttachAudioStreamProcessor"),c("DetachAudioStreamProcessor"),c("AttachAudioMixedProcessor"),c("DetachAudioMixedProcessor"),T.exportGlobalDouble("DEG2RAD","(PI/180.0)"),T.exportGlobalDouble("RAD2DEG","(180.0/PI)");const I=(t,e)=>{const n=t.params[e];n.binding={jsType:`{ ${n.name}: number }`,customConverter:(t,e)=>{t.declare(n.name,n.type,!1,"NULL"),t.declare(n.name+"_out",n.type.replace(" *",""));const s=t.if("!JS_IsNull("+e+")");s.statement(n.name+" = &"+n.name+"_out"),s.call("JS_GetPropertyStr",["ctx",e,'"'+n.name+'"'],{name:n.name+"_js",type:"JSValue"}),s.call("JS_ToInt32",["ctx",n.name,n.name+"_js"])},customCleanup:(t,e)=>{t.if("!JS_IsNull("+e+")").call("JS_SetPropertyStr",["ctx",e,`"${n.name}"`,"JS_NewInt32(ctx,"+n.name+"_out)"])}}};T.definitions.declare("textbuffer[4096]","char",!0),I(i(r.functions,"GuiDropdownBox"),2),I(i(r.functions,"GuiSpinner"),2),I(i(r.functions,"GuiValueBox"),2),I(i(r.functions,"GuiListView"),2),I(i(r.functions,"GuiListView"),3),c("GuiListViewEx"),((t,e,n)=>{const s=t.params[2];s.binding={ignore:!0};const r=t.params[1];r.binding={jsType:`{ ${r.name}: string }`,customConverter:(t,e)=>{t.call("JS_GetPropertyStr",["ctx",e,'"'+r.name+'"'],{name:r.name+"_js",type:"JSValue"}),t.declare(r.name+"_len","size_t"),t.call("JS_ToCStringLen",["ctx","&"+r.name+"_len",r.name+"_js"],{name:r.name+"_val",type:"const char *"}),t.call("memcpy",["(void *)textbuffer",r.name+"_val",r.name+"_len"]),t.statement("textbuffer["+r.name+"_len] = 0"),t.declare(r.name,r.type,!1,"textbuffer"),t.declare(s.name,s.type,!1,"4096")},customCleanup:(t,e)=>{t.jsCleanUpParameter("const char *",r.name+"_val"),t.call("JS_SetPropertyStr",["ctx",e,`"${r.name}"`,"JS_NewString(ctx,"+r.name+")"])}}})(i(r.functions,"GuiTextBox")),i(r.functions,"GuiTextInputBox").binding={body:t=>{t.jsToC("Rectangle","bounds","argv[0]",T.structLookup),t.jsToC("const char *","title","argv[1]",T.structLookup),t.jsToC("const char *","message","argv[2]",T.structLookup),t.jsToC("const char *","buttons","argv[3]",T.structLookup),t.jsToC("char *","text","argv[4]",T.structLookup),t.jsToC("int","textMaxSize","argv[5]",T.structLookup),t.call("GuiTextInputBox",["bounds","title","message","buttons","text","textMaxSize","NULL"],{type:"int",name:"returnVal"}),t.jsCleanUpParameter("const char *","text"),t.statement("return JS_NewInt32(ctx, returnVal)")}},c("GuiTabBar"),c("GuiGetIcons"),c("GuiLoadIcons"),r.structs.forEach((t=>T.addApiStruct(t))),r.functions.forEach((t=>T.addApiFunction(t))),r.defines.filter((t=>"COLOR"===t.type)).map((t=>({name:t.name,description:t.description,values:(t.value.match(/\{([^}]+)\}/)||"")[1].split(",").map((t=>t.trim()))}))).forEach((t=>{T.exportGlobalStruct("Color",t.name,t.values,t.description)})),r.enums.forEach((t=>T.addEnum(t))),T.exportGlobalInt("MATERIAL_MAP_DIFFUSE","Albedo material (same as: MATERIAL_MAP_DIFFUSE"),T.exportGlobalInt("MATERIAL_MAP_SPECULAR","Metalness material (same as: MATERIAL_MAP_SPECULAR)"),T.writeTo("src/bindings/js_raylib_core.h"),T.typings.writeTo("examples/lib.raylib.d.ts");const F=r.functions.filter((t=>t.binding?.ignore)).length;console.log(`Converted ${r.functions.length-F} function. ${F} ignored`),console.log("Success!")}()})()})(); |